Python file send as post request multipart form data



I need to send a multipart/form-data with file request to my web service. I've been using requests module from Python.


I have a code like this:



filename = "file.xml"
fileToBeSent = open(filename,"w")
fileToBeSent.write(**something.to_xml()**)


Basically, what I want to achieve is to take something.to_xml() append it to my request form as file parameter and send it to my webservice, instead of writing it onto a file.


Currently, what I have is this:



import requests
files = {"file": something.to_xml()}
response = requests.post('http://localhost:9333/submit', files=files)
print response


But the code above gives me an error. So my problem is, how can I send the xml file to my webservice without storing its content into the file system.


Should I make use of NamedTemporaryFile? If so, how? I just started coding in Python so code samples will be so much appreciated!


No comments:

Post a Comment