2

I'm using requests lib and python 2.7 When doing this :

import requests

uri_params = {
    u'email': u'[email protected]',
    u'id_user': 15,
    u'user_var': {
        u'var1': u'val1',
        u'var2': u'val2',
    }
}

r = requests.get('http://google.com/',  params=uri_params)
print r.url

it gives me as a result : http://www.google.com/?id_user=15&email=myEmail%40domain.com&user_var=var1&user_var=var2

instead of http://www.google.com/?id_user=15&email=myEmail%40domain.com&user_var%5Bvar1%5D=val1&user_var%5Bvar2%5D=val2 (= user_var[var1]=val1&user_var[var2]=val2)

Do you know if the requests lib as a method to handle this ?

EDIT : It took me few minutes too understand how to use Martijn Pieters's code. So here is the the final code for other people new to python like me :

import requests
import urllib

def nested_object(name, mapping):
    return [(u'{}[{}]'.format(name, key), value) for key, value in mapping.iteritems()]

uri_params = [
    (u'email', u'[email protected]'),
    (u'id_user', 15),
]

uri_params.extend(nested_object(u'user_var', {u'var1': u'val1', u'var2': u'val2'}))
encoded = urllib.urlencode(uri_params)

r = requests.get('http://google.com/',  params=encoded)
print r.url

1 Answer 1

2

No, the requests lib has no method to handle that.

The application/x-www-form-urlencoded encoding standard used for GET and POST requests allows only for one level of key-value pairs, and there is no standard for nested values. Instead various frameworks invented their own to handle this. You are looking at one of many variations.

The output you see is created by the urllib.urlencode() function, which handles sequences by repeating the key multiple times; your nested dictionary is seen as a sequence and only the keys are thus serialized. Normally this would be used for lists of values instead, and mimics what a browser would do when serialising multiple form fields with the same name.

You'll have to encode the nested dictionary yourself:

def nested_object(name, mapping):
    return [(u'{}[{}]'.format(name, key), value) for key, value in mapping.iteritems()]

would return a sequence of key-value tuples. Keep the rest of your URL parameters in the same format:

uri_params = [
    (u'email', u'[email protected]'),
    (u'id_user', 15),
]

uri_params.extend(nested_object(u'user_var', {u'var1': u'val1', u'var2': u'val2'}))
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.