lost and found ( for me ? )

Python: send HTTP requests with Cookie strings by using Session objects

Referred to http://www.python-requests.org/en/latest/user/quickstart/ , http://www.python-requests.org/en/latest/user/advanced/

# tail -1 /etc/lsb-release ;uname -ri
3.8.0-33-generic x86_64

# pip install requests


# apt-get install python-requests

use http://httpbin.org/ for testing.

on the interactive mode,
>>> import requests
>>> s = requests.Session()
>>> r = s.get('http://httpbin.org/cookies')
>>> r.headers
{'content-length': '19', 'date': 'Tue, 26 Nov 2013 08:47:51 GMT', 'access-control-allow-origin': '*', 'content-type': 'application/json', 'connection': 'keep-alive', 'server': 'gunicorn/0.17.4'}
>>> r.cookies
<<class 'requests.cookies.RequestsCookieJar'>[]>

put cookie in the Cookie Jar.
>>> cookies = dict(X-test-cookies='hello')
 File "<stdin>", line 1
SyntaxError: keyword can't be an expression

>>> name = 'X-cookies'
>>> val = 'hello'
>>> cookies = {name: val}
>>> cookies
{'X-cookies': 'hello'}

send an HTTP request with Cookie

update headers
>>> s.headers.update(cookies)
>>> s.headers
{'X-cookies': 'hello', 'Accept-Encoding': 'gzip, deflate, compress', 'Accept': '*/*', 'User-Agent': 'python-requests/1.1.0 CPython/2.7.4 Linux/3.8.0-33-generic'}

send the request.
>>> r2 = s.get('http://httpbin.org/cookies')

Here a capture data.
   GET /cookies HTTP/1.1\r\n
       [Expert Info (Chat/Sequence): GET /cookies HTTP/1.1\r\n]
           [Message: GET /cookies HTTP/1.1\r\n]
           [Severity level: Chat]
           [Group: Sequence]
       Request Method: GET
       Request URI: /cookies
       Request Version: HTTP/1.1
   Host: httpbin.org\r\n
   Content-Length: 0\r\n
       [Content length: 0]
   X-cookies: hello\r\n
   Accept-Encoding: gzip, deflate, compress\r\n
   Accept: */*\r\n
   User-Agent: python-requests/1.1.0 CPython/2.7.4 Linux/3.8.0-33-generic\r\n
   [Full request URI: http://httpbin.org/cookies]

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.