简体   繁体   中英

http 500 error when attempting to make a post request with python requests module

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 data1 and data2 to the form. You are calling open() 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 like read() to actually get the data from the stream so you can pass it on.

As an update to this, I've figured out the solution. It was looking for a filename, however based on the uploading mechanism of the web application it was looking for it in a folder C:/deploy/.../media/uploads/tmp/. Upon saving the files to be uploaded there, removing the files=f parameter in the post request and submitting the test_data form as:

test_data = {
  'csrfmiddlewaretoken': token,
  "work_started":timestr,
  "work_completed":timestr,
  "status":"1",
  "form-TOTAL_FORMS":"3",
  "form-INITIAL_FORMS":"3",
  "form-MAX_NUM_FORMS":"1000",
  "form-0-value":"5"
  "form-1-string_value":test1.png #saved in C:/deploy/.../media/uploads/tmp/
  "form-2-string_value":test2.png
}
 resp = s.post(test_list_url, data=test_data)

The files uploaded as desired. Thank you for all the help!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM