Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python-requests: order get parameters

Tags:

I am implementing a client library for a private HTTP-API using python requests. The API(which I don't control) expects the parameters to be in a certain order, but python-requests doesn't honor a sorted dict as parameter.

This is what i tried:

import requests from django.utils.datastructures import SortedDict  params = SortedDict() params['s'] = 'value1' params['f'] = 'value2'  requests.get('https://example.org/private_api', params=params) #performs request as https://example.org/private_api?f=value1&s=value2  

This is what I am trying to avoid:

requests.get('https://example.org?{0}'.format(urlencode(params))) 
like image 864
tback Avatar asked Jan 10 '12 12:01

tback


People also ask

What does request get Do Python?

get() method sends a request for data to a web server. The response object it returns contains various types of data such as the webpage text, status code, and the reason for that response.

How do you pass a header in a POST request in Python?

In order to pass HTTP headers into a POST request using the Python requests library, you can use the headers= parameter in the . post() function. The headers= parameter accepts a Python dictionary of key-value pairs, where the key represents the header type and the value is the header value.

What is payload in Python request?

JSON Payload Example [Python Code] A request payload is data that clients send to the server in the body of an HTTP POST, PUT, or PATCH message that contains important information about the request.


2 Answers

The requests lib now supports this out-of-the-box: To get ordered parameters you use a sequence of two-valued tuples instead. This eliminates the additional requirement of OrderedDict.

payload = (('key1', 'value1'), ('key2', 'value2')) r = requests.get("http://httpbin.org/get", params=payload) 

Demo:

>>> import requests >>> requests.__version__ 1.2.3 >>> payload = (('key1', 'value1'), ('key2', 'value2'), ('key3', 'value3')) >>> r = requests.get("http://httpbin.org/get", params=payload) >>> print r.json()['url'] http://httpbin.org/get?key1=value1&key2=value2&key3=value3 
like image 140
Jeff Sheffield Avatar answered Nov 30 '22 15:11

Jeff Sheffield


Currently requests doesn't allow to do this as you wish. This is of course shortcoming that will be fixed. However as params parameter can take not only dictionary but bytes as well you should be able to do something in between:

from collections import OrderedDict from urllib import urlencode import requests  params = OrderedDict([('first', 1), ('second', 2), ('third', 3)]) requests.get('https://example.org/private_api', params=urlencode(params)) 

This doesn't work as I see due to bug in line 85 of models.py: self.params = dict(params or []. I raised this problem in issue Wrong handling of params given as bytes object

like image 30
Piotr Dobrogost Avatar answered Nov 30 '22 15:11

Piotr Dobrogost