嗯,今天本来想好好学习别人的代码的,突然看到 requests 模块,想想貌似这模块很常用的说,我竟然没用过,于是我就找了下文档看了下,嗯,光看不练是不对的,然后我就想做点什么,突然想到我每次写 hexo blog 的时候,每次要把图片截取保存到本地,然后上传到我的图床,然后拷贝链接, OMG 好烦啊,于是发现这篇文档 , 是时候造个轮子了。 下面是代码 - #coding=utf-8
- import requests
- import json
- import mimetypes
- from PIL import ImageGrab
- import datetime
- def upload(files):
- APIKey = "YOUR API KEY"
- format = "json"
- url = "http://domain.com/api/1/upload/?key="+ APIKey + "&format=" + format
- #files =
- r = requests.post(url , files = files)
- return json.loads(r.text)
- def formatSource(filename):
- imageList = []
- type = mimetypes.guess_type(filename)[0]
- imageList.append(('source' , (filename , open(filename , 'rb') , type)))
- print imageList
- return imageList
- if __name__ == "__main__":
- print "将图片截图或复制到剪切板中即可~~, ctrl+z 结束"
- recentVal = None
- while(True):
- tmpValue = ImageGrab.grabclipboard()
- if recentVal != tmpValue:
- recentVal = tmpValue
- now = datetime.datetime.now()
- now = now.strftime("%Y-%m-%d %H:%M:%S")
- filename = 'IMG'+ now + '.png'
- if recentVal is not None:
- recentVal.save(filename, 'png')
- #filenames.append(filename)
- #recentVal = None
- print filename
- jsonData = upload(formatSource(filename))
- if jsonData['status_code'] != 200:
- print "error: " , jsonData['error']['message']
- print "status code : " , jsonData['status_code']
- else:
- print "orignal url: " , jsonData['image']['display_url']
- print "thumb url: " , jsonData['image']['thumb']['url']
复制代码
运行示例
有点慢啊,因为我的服务器在国外~~ 使用方法将你的 chevereto 的 API key 拷贝到对应位置,替换 domain.com 为你自己的域名,嗯,就这样,这只是练习代码,难免有些 bug ,你懂得 其实讲道理用curl就可以弄的,但是我不会把本地的图片传到服务器上,据说要base64编码~~~sad 嗯,开年第一个轮子,大家新年快乐!
|