Skip to content

Instantly share code, notes, and snippets.

@liuhenry
Created June 28, 2012 02:41
Show Gist options
  • Select an option

  • Save liuhenry/3008447 to your computer and use it in GitHub Desktop.

Select an option

Save liuhenry/3008447 to your computer and use it in GitHub Desktop.
Chute Upload using API v2 (Python)
import requests
import json
import os
import hashlib
class Chute:
BASE_URI = 'http://api.getchute.com'
def __init__(self, app_id, access_token):
self.app_id = app_id
self.authorization = access_token
self.headers = { 'x-client_id' : self.app_id,
'Authorization' : 'OAUTH ' + self.authorization }
def md5_for_file(self, f, block_size=128):
md5 = hashlib.md5()
while True:
data = f.read(block_size)
if not data:
break
md5.update(data)
return md5.hexdigest()
def process_paths(self, path):
f = open(path)
size = os.path.getsize(path)
return {
'filename' : path,
'md5' : self.md5_for_file(f),
'size' : size,
}
def upload(self, file_paths, chutes=[]):
file_paths = [file_paths] if not isinstance(file_paths, list) else file_paths
chutes = [chutes] if not isinstance(chutes, list) else chutes
file_paths = [self.process_paths(path) for path in file_paths]
data = {
'data' : {
'files' : file_paths,
'chutes' : chutes,
}
}
response = requests.post(Chute.BASE_URI + '/v2/uploads',
headers = self.headers,
data = json.dumps(data))
print response.json
new_assets = response.json['data']['new_assets']
existing_assets = response.json['data']['existing_assets']
job_id = response.json['data']['id']
for new_asset in new_assets:
_headers = { 'Date' : new_asset['upload_info']['date'],
'Authorization' : new_asset['upload_info']['signature'],
'Content-Type' : new_asset['upload_info']['content_type'],
'x-amz-acl' : 'public-read' }
f = open(new_asset['upload_info']['file_path'], 'r')
response = requests.put(new_asset['upload_info']['upload_url'],
headers = _headers,
data = f.read())
requests.post(Chute.BASE_URI + "/v2/uploads/%s/complete" % (job_id),
headers = self.headers)
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment