问题
I want to send a PUT request with the following data structure:
{ body : { version: integer, file_id: string }}
Here is the client code:
def check_id():
id = request.form['id']
res = logic.is_id_valid(id)
file_uuid = request.form['file_id']
url = 'http://localhost:8050/firmwares'
r = requests.put(url = url, data = {'body' : {'version': id, 'file_id': str(file_uuid)}})
Here is the server code:
api.add_resource(resources.FirmwareNewVerUpload, '/firmwares')
class FirmwareNewVerUpload(rest.Resource):
def put(self):
try:
args = parser.parse_args()
except:
print traceback.format_exc()
print 'data: ', str(args['body']), ' type: ', type(args['body'])
return
The server prints:
data: version type: <type 'unicode'>
And this result is not what I want. Instead of inner dictionary I got a string with name of one dictionary key. If I change 'version' to 'ver'
r = requests.put(url = url, data = {'body' : {'ver': id, 'file_id': str(file_uuid)}})
server prints
data: ver type: <type 'unicode'>
How to send a dictionary with inner dictionary?
回答1:
Use json=
instead of data=
when doing requests.put
and headers = {'content-type':'application/json'}
:
r = requests.put(url = url,
json = {'body' : {'version': id, 'file_id': str(file_uuid)}},
headers = {'content-type':'application/json'})
回答2:
In official doc you found a topic called More complicated POST requests
There are many times that you want to send data that is not form-encoded. If you pass in a string instead of a dict, that data will be posted directly.
>>> import json
>>> url = 'https://api.github.com/some/endpoint'
>>> payload = {'some': 'data'}
>>> r = requests.post(url, data=json.dumps(payload))
Maybe convert your data to JSON could be a good approach.
import json
def check_id():
id = request.form['id']
res = logic.is_id_valid(id)
file_uuid = request.form['file_id']
url = 'http://localhost:8050/firmwares'
payload = {'body' : {'version': id, 'file_id': str(file_uuid)}}
r = requests.put(url=url, data=json.dumps(payload))
来源:https://stackoverflow.com/questions/38752091/put-dictionary-in-dictionary-in-python-requests