Skip to content

Instantly share code, notes, and snippets.

@vladwa
Created December 30, 2017 12:14
Show Gist options
  • Save vladwa/ba0ba632c0dcda33354c2d5e833672aa to your computer and use it in GitHub Desktop.
Save vladwa/ba0ba632c0dcda33354c2d5e833672aa to your computer and use it in GitHub Desktop.
Python snippet to invoke HTTP Post request with file attached(multipart/form-data) in the body of the request. This function returns Response object.
# importing the requests library
import requests
def postFileAttachment(url,fileName,contentType):
"""Sends a POST request.
:param url: URL for the new :class:`Request` object.
:param fileName: File to be sent/attached in the body of the request.
:return: :class:`Response <Response>` object.
"""
multipart = MultipartEncoder(
fields={'field1': ('filename', open(fileName, 'rb'), contentType)}
)
response = requests.post(url, data=multipart,headers={'Content-Type': multipart.content_type})
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment