|
| 1 | +from collections import defaultdict |
| 2 | +from functools import partial |
| 3 | + |
| 4 | +import requests |
| 5 | +from six.moves.urllib.parse import urlparse |
| 6 | + |
| 7 | +_REQUESTS_METHODS = ('get', 'post', 'put', 'delete', 'patch') |
| 8 | + |
| 9 | + |
| 10 | +# see test_dynamic_sessions.py for how to use it |
| 11 | + |
| 12 | +class DynamicSession(object): |
| 13 | + """ This looks intricate but its a way to make requests.session work transparently creating different |
| 14 | + session depending on the hostname of the urls |
| 15 | + """ |
| 16 | + _session_by_host = defaultdict(requests.session) |
| 17 | + |
| 18 | + @staticmethod |
| 19 | + def get_session_from_args(args, kwargs): |
| 20 | + url = kwargs.get('url', None) |
| 21 | + if url is None: |
| 22 | + url = args[0] # get the positional url |
| 23 | + parsed_uri = urlparse(url) |
| 24 | + session_key = '{uri.scheme}://{uri.netloc}/'.format(uri=parsed_uri) |
| 25 | + if 'verify' in kwargs: |
| 26 | + session_key += "-noverify" # unverified calls get a different session |
| 27 | + session = DynamicSession._session_by_host[session_key] |
| 28 | + return session |
| 29 | + |
| 30 | + @staticmethod |
| 31 | + def get_session_method(method, *args, **kwargs): |
| 32 | + # this will be returned as a partial - it will get a session for the url in the call |
| 33 | + # that will get the proper session for that host |
| 34 | + session = DynamicSession.get_session_from_args(args, kwargs) |
| 35 | + return getattr(session, method)(*args, **kwargs) |
| 36 | + |
| 37 | + @staticmethod |
| 38 | + def __getattr__(method): |
| 39 | + # when we do DynamicSession.post - it will return a partial - that will ask to get |
| 40 | + if method in _REQUESTS_METHODS: |
| 41 | + return partial(DynamicSession.get_session_method, method) |
| 42 | + return getattr(requests, method) |
| 43 | + |
| 44 | + @staticmethod |
| 45 | + def get_session(*args, **kwargs): |
| 46 | + """ This is the only method that is only from here - everything else is taken from requests """ |
| 47 | + return DynamicSession.get_session_from_args(args, kwargs) |
0 commit comments