Merge branch 'feature/session' of https://github.com/tomhsx/requests into feature/session

Conflicts:
	AUTHORS
This commit is contained in:
Kenneth Reitz
2011-08-16 02:34:44 -04:00
4 changed files with 92 additions and 1 deletions
+2 -1
View File
@@ -33,4 +33,5 @@ Patches and Suggestions
- Peter Manser
- Jeremy Selie
- Jens Diemer
- Alex <@alopatin>
- Alex <@alopatin>
- Tom Hogans <tomhsx@gmail.com>
+22
View File
@@ -0,0 +1,22 @@
.. _advanced:
Advanced Usage
==============
This document covers more advanced features.
Session Objects
===============
.. module:: requests.session
The Session object allows you to persist certain parameters across requests. It also establishes a CookieJar by default and passes it along in any requests made from the Session instance. For a complete list of allowed parameters, please see the *__attrs__* field in *requests/session.py*. ::
from requests.session import Session
s = Session()
s.get("http://httpbin.org/cookies/set/sessioncookie/123456789")
r = s.get("http://httpbin.org/cookies")
print r.content
Note: Certain parameters are best set at the request.config level (i.e. a global proxy, user agent header).
+44
View File
@@ -0,0 +1,44 @@
# -*- coding: utf-8 -*-
"""
requests.session
~~~~~~~~~~~~~~~
This module provides a Session object to manage and persist settings across
requests (cookies, auth, proxies).
"""
import requests.api
import cookielib
class Session(object):
__attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies']
def __init__(self, **kwargs):
# Set up a CookieJar to be used by default
self.cookies = cookielib.FileCookieJar()
# Map args from kwargs to instance-local variables
map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),
kwargs.iterkeys(), kwargs.itervalues())
# Map and wrap requests.api methods
self._map_api_methods()
def _map_api_methods(self):
""" Reads each available method from requests.api and decorates
them with a wrapper that inserts any instance-local attributes
(from __attrs__) that have been set, combining them with **kwargs """
def pass_args(func):
def wrapper_func(*args, **kwargs):
inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems()
if k in self.__attrs__)
# Combine instance-local values with kwargs values, with
# priority to values in kwargs
kwargs = dict(inst_attrs.items() + kwargs.items())
return func(*args, **kwargs)
return wrapper_func
# Map and decorate each function available in requests.api
map(lambda fn: setattr(self, fn, pass_args(getattr(requests.api, fn))),
requests.api.__all__)
+24
View File
@@ -13,6 +13,7 @@ except ImportError:
import requests
from requests.session import Session
HTTPBIN_URL = 'http://httpbin.org/'
@@ -455,5 +456,28 @@ class RequestsTestSuite(unittest.TestCase):
self.assertEquals(len(r.history), 3)
def test_session_HTTP_200_OK_GET(self):
s = Session()
r = s.get(httpbin('/'))
self.assertEqual(r.status_code, 200)
def test_session_HTTPS_200_OK_GET(self):
s = Session()
r = s.get(httpsbin('/'))
self.assertEqual(r.status_code, 200)
def test_session_persistent_headers(self):
heads = {'User-agent': 'Mozilla/5.0'}
s = Session()
s.headers = heads
# Make 2 requests from Session object, should send header both times
r1 = s.get(httpbin('user-agent')
assert heads['User-agent'] in r1.content
r2 = s.get(httpbin('user-agent')
assert heads['User-agent'] in r2.content
self.assertEqual(r.status_code, 200)
if __name__ == '__main__':
unittest.main()