I have a python (python 2.7) script that uses the requests module to make a post to a web application I have running on the localhost. The form that needs to be filled out has areas for data and areas for file uploads.
import requests
root = "http://localhost/qatrack/"
test_list_url =root+"qa/utc/perform/17/day=next&next=/qatrack/qa/unit/7/"
s = requests.Session()
s.get(login_url)
token = s.cookies['csrftoken']
login_data = {
'username':'user',
'password':'pass',
'csrfmiddlewaretoken': token
}
login_resp = s.post(login_url, data=login_data)
data1=open('C:/deploy/qatrackplus/python/imgs/test1.png','rb')
data2=open('C:/deploy/qatrackplus/python/imgs/test2.png','rb')
test_data = {
'csrfmiddlewaretoken': token,
"work_started":timestr,
"work_completed":timestr,
"status":"1",
"form-TOTAL_FORMS":"4",
"form-INITIAL_FORMS":"4",
"form-MAX_NUM_FORMS":"1000",
"form-0-value":"5"
}
f={
"form-1-string_value":data1,
"form-2-string_value":data2
}
resp = s.post(test_list_url, data=test_data, files=f)
The response gives a 500 error code, as well when I put the input to an .html file, it will say that there is an Attribute error in one of the scripts of the web application. I do not get this if I run the script for a form that does not have a file upload that needs to be filled.
I think your problem comes from how you are passing
data1anddata2to the form. You are callingopen()on the image files, but that doesn't give you any data by itself. It gives you a file reader object. To get the data from it, you need to use something likeread()to actually get the data from the stream so you can pass it on.