Skip to content

Instantly share code, notes, and snippets.

@nitrocode
Last active December 5, 2017 03:58
Show Gist options
  • Save nitrocode/bd839676e76144a83b6def30e53b2afd to your computer and use it in GitHub Desktop.
Save nitrocode/bd839676e76144a83b6def30e53b2afd to your computer and use it in GitHub Desktop.
Uploads file with a rest end point using python's request module
#!/usr/bin/env python
import requests
import os
def upload_file(url, file_loc, cookies=None, headers=None,
file_type='application/vnd.ms-excel'):
"""Upload a file using an end point using requests posting of
a multipart encoded file
Based on source from http://stackoverflow.com/a/22974646
:param url: URL of end point
:param file_loc: location of the file
:param cookies: optional dictionary of cookies or a CookieJar
:param headers: optional dictionary of headers
:param file_type: optional file type. Defaults to excel.
:returns: request return object
"""
file_name = os.path.basename(file_loc)
file_params = {
# controls the contents of the file; see open()
'file': (file_name, open(file_loc, 'rb'), file_type),
# controls the title of the file and this can easily be any param
'filename': ('', file_name)
}
params = {
'url': url,
'cookies': cookies,
'headers': headers,
'files': file_params,
}
try:
res = requests.post(**params)
except:
print("upload_file() is unable to upload the file")
raise
return res
if __main__ == "__name__":
# find os agnostic location of file path for files/data.xlsx
file_loc = os.path.join('files', 'data.xlsx')
res = upload_file(url, file_loc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment