Skip to content

Instantly share code, notes, and snippets.

@staticor
Forked from ficapy/img_upload.py
Created January 11, 2016 09:15
Show Gist options
  • Save staticor/a9d3faed5e77ebe91dff to your computer and use it in GitHub Desktop.
Save staticor/a9d3faed5e77ebe91dff to your computer and use it in GitHub Desktop.
当做图床使用,读取粘贴板的图像保存上传,完成后将url地址写入到剪贴板
#!/usr/local/bin/python2
# -*- coding: utf-8 -*-
# Author: Ficapy
# Create: '16/1/1'
import datetime
import sys
import os
import atexit
import requests
from hashlib import md5
from subprocess import call
NAME = '------'
PWD = '------'
URL = 'http://v0.api.upyun.com/'
BUCKET = '------'
DIR = 'capture'
try:
call(['/usr/local/bin/pngpaste', '-v'], stderr=open('/dev/null', 'w'))
except OSError:
print('please preinstall pngpaste use `brew install pngpaste` before use this script')
sys.exit()
file_name = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S.png')
file_path = os.path.join('/tmp', file_name)
atexit.register(lambda x: os.remove(x) if os.path.exists(x) else None, file_path)
save = call(['/usr/local/bin/pngpaste', file_path])
if save == 1:
sys.exit()
size = str(os.path.getsize(file_path))
date = datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT')
# method,path,date,CONTENT_LENGTH,password
params = ['PUT', '/' + BUCKET + '/' + DIR + '/' + file_name, date, size, md5(PWD).hexdigest()]
sign = md5('&'.join(params)).hexdigest()
with open(file_path) as f:
url = URL + BUCKET + '/' + DIR + '/' + file_name
ret = requests.put(url, headers={'Authorization': 'UpYun ' + NAME + ':' + sign, 'Date': date}, data=f)
ret.raise_for_status()
ret = 'http://{0}.b0.upaiyun.com/{1}/{2}'.format(BUCKET, DIR, file_name)
call('echo {0} | tr -d "\n" | pbcopy'.format(ret), shell=True)
print(ret)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment