Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PUT dictionary in dictionary in Python requests

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?

like image 334
Michael Lukin Avatar asked Aug 03 '16 19:08

Michael Lukin


1 Answers

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'})
like image 93
Tommy Avatar answered Sep 22 '22 19:09

Tommy