问题
I am using flask-restful as an api server and am constructing the first PUT method. Using request imported from flask, I am able to access request.form data without issue with the following cURL command:
curl http://127.0.0.1:5000/api/v1/system/account -X PUT -d username=asdas -d email=asdasd@test.com
My PUT method logs out both the username and email without issue:
def put(self):
print 'SystemAccountPut'
print request.form['username']
print request.form['email']
return
Output:
SystemAccountPut
asdas
asdasd@test.com
I have an app using the axios project to make api calls. When axios attempts to PUT form data, request.form no longer works. Here is the call axios is making converted to cURL command from Chrome Dev Console:
curl 'http://127.0.0.1:5000/api/v1/system/account' -X PUT -H 'Pragma: no-cache' -H 'Origin: http://127.0.0.1:5000' -H 'Accept-Encoding: gzip, deflate, sdch' -H 'Accept-Language: en-US,en;q=0.8' -H 'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36' -H 'Content-Type: application/json;charset=UTF-8' -H 'Accept: application/json, text/plain, */*' -H 'Cache-Control: no-cache' -H 'Referer: http://127.0.0.1:5000/settings' -H 'Connection: keep-alive' --data-binary '{"username":"asdas","email":"asdasd@test.com"}' --compressed
With the same method above request.form['username'] and request.form['email'] are empty. request.data however has the form data in it, and request.get_json() also will output the form data in JSON format.
My question is what should I be using in this case to retrieve the form data? The first curl command is clean with request.form having the data I need, but request.data is empty. The second cURL command leaves request.form broken but does populate request.data. Is there a best practice on how I should retrieve form data in both cURL cases?
回答1:
I figured out the issue after further learning more about incoming forms and some insight from davidism. The first cURL example has the following Content-Type: application/x-www-form-urlencoded. The second cURL command has the following Content-Type: application/json;charset=UTF-8. Unsurprisingly, the first cURL command sends form data to request.form and the second cURL command is interpreted as data and can retrieved at request.data or request.get_json(). For my needs I want to get the form data either way, so in my put method I have the following:
data = request.get_json() or request.form
print data['email']
print data['username']
This gives me the email and password in both cURL examples.
来源:https://stackoverflow.com/questions/35995817/handling-form-data-with-flask-request