Skip to content

Instantly share code, notes, and snippets.

@SharkyRawr
Last active September 26, 2016 19:26
Show Gist options
  • Save SharkyRawr/4b6f4a366d3c86573da90d050590b3a9 to your computer and use it in GitHub Desktop.
Save SharkyRawr/4b6f4a366d3c86573da90d050590b3a9 to your computer and use it in GitHub Desktop.
# -- parf of a class that handles all User API interactions --
def upload_video(self, path, title):
import os
if not os.path.exists(path):
raise IOError("file not found", path)
info = os.stat(path)
size = info.st_size
fn = os.path.basename(path)
v = self.req('/video/request', data=dict(filename=fn, size=size, title=title, mode='chunked'))
code = v['code']
print ("New video requested:", code)
#print (v)
# This works fine, uploading a file in one go, files= ... open(path, 'rb')
#return self.req('/video/upload', data=dict(code=code), files=files)
# Create upload with the size of the file in bytes
upload = self.req('/upload/create', data=dict(code=code, size=size))
upid = upload['upload']['upload_id']
print ("Upload created: %(state)s %(size_completed)d bytes of %(size_total)d" % upload['upload'])
with open(path, 'rb') as f:
chunksize = 1024*1000*10
def readchunk(f):
read = 0
while True:
c = f.read(chunksize)
yield c
read += len(c)
print ("Read %d bytes of %d (%.2f%%) ..." % (read, size, (read/size)*100))
if len(c) < chunksize:
break
r = self.req('/upload/chunk', params=dict(code=code,upload=upid), data=readchunk(f))
v = r['video']
u = r['upload']
print ("chunk uploaded: %(state)s %(size_completed)d bytes of %(size_total)d" % u)
return v
# -- somewhere else in the class --
def req(self, *args, **kwargs):
kwargs['accesstoken'] = self.token
return do_request(*args, **kwargs)
# -- yet somewhere else in a different file --
from requests import get, post
API_EP = 'https://api.vid.me'
def do_request(uri, accesstoken=None, method='POST', extraheaders=None, **kwargs):
headers = makeauthheaders(uri) # generate the required Authorization header
if extraheaders is not None:
headers.update(extraheaders)
if accesstoken is not None:
headers['AccessToken'] = accesstoken
myfn = post
if method == 'POST':
myfn = post
elif method == 'GET':
myfn = get
else:
raise Exception('unhandled method for do_request', method)
r = myfn(API_EP + uri, headers=headers, **kwargs)
if r.status_code >= 400:
raise Exception("do_request server error", r.text)
json = r.json()
if json is None or not 'status' in json or json['status'] is False:
raise Exception('do_request failed', json)
return json
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment