Skip to content

Instantly share code, notes, and snippets.

@ficapy
Last active December 21, 2015 13:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ficapy/25960a11472ad4cde359 to your computer and use it in GitHub Desktop.
Save ficapy/25960a11472ad4cde359 to your computer and use it in GitHub Desktop.
阿里云OSS单文件上传
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: Ficapy
import requests
import base64
import hmac
import os
import sys
import datetime
from hashlib import sha1
from progressbar import ProgressBar, Percentage, Bar, ETA, FileTransferSpeed
KEY = '---------'
SECRET = '---------'
BUCKET = ''
url = 'ficapy.oss-cn-hangzhou.aliyuncs.com'
file_path = sys.argv[-1]
assert os.path.exists(file_path)
headers = {
'Date': datetime.datetime.utcnow().strftime('%a, %d %b %Y %H:%M:%S GMT'),
'Content-Type': 'application/octet-stream',
'HOST': url,
}
Signature = base64.b64encode(hmac.new(SECRET,
'PUT' + "\n"
+ '' + "\n"
+ headers['Content-Type'] + "\n"
+ headers['Date'] + "\n"
+ '/' + BUCKET + '/' + file_path, sha1).digest()).strip()
headers.update({'Authorization': 'OSS ' + KEY + ':' + Signature})
class ProgressBarHandler(object):
def __init__(self, params, totalsize):
widgets = [params, Percentage(), ' ',
Bar(marker='=', left='[', right=']'), ' ',
ETA(), ' ', FileTransferSpeed()]
self.pbar = ProgressBar(widgets=widgets, maxval=totalsize).start()
def update(self, readsofar):
try:
self.pbar.update(readsofar + self.pbar.currval)
except ValueError:
pass
def finish(self):
self.pbar.finish()
def read_in_chunks(file_object, blocksize=1024, chunks=-1):
pbar = ProgressBarHandler(' Uploading',os.path.getsize(file_path))
while chunks:
data = file_object.read(blocksize)
pbar.update(blocksize)
if not data:
pbar.finish()
break
yield data
chunks -= 1
with open(file_path) as f:
url = 'http://' + url + '/' + file_path
res = requests.put(url, headers=headers, data=read_in_chunks(f))
print(res.text)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment