Skip to content

Instantly share code, notes, and snippets.

@rokclimb15
Created July 10, 2015 14:04
Show Gist options
  • Save rokclimb15/e6c34e04dc969a3ba0f9 to your computer and use it in GitHub Desktop.
Save rokclimb15/e6c34e04dc969a3ba0f9 to your computer and use it in GitHub Desktop.
Sample upload file to DVIDS API
from form_post import encode_multipart_formdata
import httplib, json, mimetypes
DVIDS_API_SECRET = ''
def post_to_dvids(my_unit_id, path_to_asset):
response_data = {}
access_token = get_token(request)
if not access_token:
tokens = refresh_tokens(request)
access_token = tokens.get('access_token')
fields = {
("unit", str(my_unit_id))
}
f = open(path_to_asset)
files = [
("file", path_to_asset, f.read())
]
f.close()
content_type, body = encode_multipart_formdata(fields, files)
headers = {
"Content-Type": "text/HTML",
"Accept": "application/json",
"Cache-Control": "no-cache, no-store, must-revalidate",
"Pragma": "no-cache",
"Expires": 0
}
headers["Authorization"] = access_token
headers["Content-Type"] = content_type
headers["Content-Length"] = str(len(body))
mimeguess = mimetypes.guess_type(path_to_asset, strict=True)
mimetype = mimeguess[0]
if mimetype == "image/jpeg":
uri_type = 'images'
else:
uri_type = 'videos'
uri = "/%s?api_key=%s" % (uri_type, DVIDS_API_SECRET)
conn = httplib.HTTPSConnection('api.dvidshub.net')
conn.request("POST", uri, body, headers)
response = conn.getresponse()
data = response.read()
conn.close()
J = json.loads(data)
if response.status == 201:
response_data = json.dumps({
'status': 'success',
'batch_id': J.get('batch_id')
})
else:
response_data["message"] = "The asset has been rejected by DVIDS"
response_data["dvids_error"] = J
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment