Pelicanux

Just A Few Random Words

Librairie Requests De Python

Introducing requests:

requests: HTTP for humans let to easily forge HTTP[S] requests. The library get simply installed on Debian with this command:

1
aptitude install python-requests

It is then really simple to create one’s first request and display HTTP variables, following the example given on the official website:

1
2
3
4
5
6
7
8
import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.headers
>>{'status': '401 Unauthorized', 'content-length': '82', 'x-github-media-type': 'github.beta',
 'access-control-expose-headers': 'ETag, Link, X-RateLimit-Limit, X-RateLimit-Remaining,
X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes', 'x-github-request-id': 
'588EBA11:32F8:16EEAAD:5241F718', 'server': 'GitHub.com', 'access-control-allow-credentials': 'true', 'date':
'Tue, 24 Sep 2013 20:33:29 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json; charset=utf-8'}

Of course, this is just a dummy connection, let’s go to applications:

The API gives us the parameters of the requests function: and more particulary its header, payload, (POST, GET fields), cookies, sessions:

Here is an example showing how can one change headers:

1
2
3
url = 'https://some_domain/some_location''
headers = {'x-forwarded-for': 172.17.2.1'}
r = requests.post(url, headers=headers)

POST and GET requests:

1
r = requests.request(method='POST', url=r1_url, data=response_1

Where response_1 is a dictionnary containing as keys<–>values couples the POST variables and values. for GET:

1
r = requests.request(method='GET', url=r1_url)

Getting authenticated:

This leads often to create a session which returns a cookie to keep for the following transactions:

1
2
3
4
5
6
7
s = requests.Session()
nc_auth  = {
    'user'      :'philippe_',
    'passwrd'   :'*********',
}
r = s.post(nc_url, nc_auth)
req = requests.request(method='GET', url=q1_url, cookies=r.cookies)

We reuse this very cookie for the next exchanges:

1
r = requests.request(method='POST', url=r1_url, data=response_1, cookies=req.cookies)

That’s all, folks!