Merge branch 'feature/session' of https://github.com/tomhsx/requests into feature/session
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Conflicts: AUTHORS
authored by Kenneth Reitz · committed by Kenneth Reitz · parents 8f72c48, 0ed641a · Browse files · 4 files·+92 added−1 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+92 added−1 removed
- other:+92 added−1 removed
Provenance
- Commit
2fa0215- Tree
51f3244- Author
Kenneth Reitz <me@kennethreitz.com>- Committer
Kenneth Reitz <me@kennethreitz.com>- Parent 1
8f72c48- Parent 2
0ed641a
4 files changed+92 added−1 removed
modified:docs/user/advanced.rst+22 added
1+.. _advanced:2+3+Advanced Usage4+==============5+6+This document covers more advanced features.7+8+Session Objects9+===============10+11+.. module:: requests.session 12+13+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*. ::14+15+ from requests.session import Session16+17+ s = Session()18+ s.get("http://httpbin.org/cookies/set/sessioncookie/123456789")19+ r = s.get("http://httpbin.org/cookies")20+ print r.content21+22+Note: Certain parameters are best set at the request.config level (i.e. a global proxy, user agent header).added:requests/session.py+44 added
1+# -*- coding: utf-8 -*-2+3+"""4+requests.session5+~~~~~~~~~~~~~~~6+7+This module provides a Session object to manage and persist settings across8+requests (cookies, auth, proxies).9+10+"""11+12+import requests.api13+import cookielib14+15+class Session(object):16+ __attrs__ = ['headers', 'cookies', 'auth', 'timeout', 'proxies']17+18+ def __init__(self, **kwargs):19+ # Set up a CookieJar to be used by default20+ self.cookies = cookielib.FileCookieJar()21+ # Map args from kwargs to instance-local variables22+ map(lambda k, v: (k in self.__attrs__) and setattr(self, k, v),23+ kwargs.iterkeys(), kwargs.itervalues())24+ # Map and wrap requests.api methods25+ self._map_api_methods()26+ 27+ def _map_api_methods(self):28+ """ Reads each available method from requests.api and decorates29+ them with a wrapper that inserts any instance-local attributes30+ (from __attrs__) that have been set, combining them with **kwargs """31+ def pass_args(func):32+ def wrapper_func(*args, **kwargs):33+ inst_attrs = dict((k, v) for k, v in self.__dict__.iteritems() 34+ if k in self.__attrs__)35+ # Combine instance-local values with kwargs values, with 36+ # priority to values in kwargs37+ kwargs = dict(inst_attrs.items() + kwargs.items())38+ return func(*args, **kwargs)39+ return wrapper_func40+ # Map and decorate each function available in requests.api41+ map(lambda fn: setattr(self, fn, pass_args(getattr(requests.api, fn))),42+ requests.api.__all__) 43+44+modified:AUTHORS+2 added-1 removed
31 unmodified lines32 - Rubén Abad33 - Peter Manser34 - Jeremy Selie35 - Jens Diemer36-- Alex <@alopatin>36+- Alex <@alopatin>37+- Tom Hogans <tomhsx@gmail.com>modified:test_requests.py+24 added
11 unmodified lines12 import json13 14 import requests15 16+from requests.session import Session17 18 19 HTTPBIN_URL = 'http://httpbin.org/'20 HTTPSBIN_URL = 'https://httpbin.ep.io/'434 unmodified lines455 self.assertEquals(r.status_code, 200)456 self.assertEquals(len(r.history), 3)457 458 459+ def test_session_HTTP_200_OK_GET(self):460+ s = Session()461+ r = s.get(httpbin('/'))462+ self.assertEqual(r.status_code, 200)463+464+ def test_session_HTTPS_200_OK_GET(self):465+ s = Session()466+ r = s.get(httpsbin('/'))467+ self.assertEqual(r.status_code, 200)468+469+ def test_session_persistent_headers(self):470+ heads = {'User-agent': 'Mozilla/5.0'}471+ s = Session()472+ s.headers = heads473+ # Make 2 requests from Session object, should send header both times474+ r1 = s.get(httpbin('user-agent')475+ assert heads['User-agent'] in r1.content476+ r2 = s.get(httpbin('user-agent')477+ assert heads['User-agent'] in r2.content478+ self.assertEqual(r.status_code, 200)479+ 480+ 481+482 if __name__ == '__main__':483 unittest.main()