Session proxy¶
-
class
ahoyhoy.http.proxy.
SessionProxy
(session=None, pre_callback=None, post_callback=None, exception_callback=None)[source]¶ Proxy adapter so a subclass can proxy methods of a Requests Session, but can alter behavior via pre, post, and exception callbacks.
Can be used by itself, but is intended to be subclassed with overwritten callbacks.
>>> from ahoyhoy.http import SessionProxy >>> sp = SessionProxy() >>> sp.get('http://google.com') <Response [200]>
In order to be a bit more transparent, excpetion_callback will raise the thrown exception.
>>> from ahoyhoy.http import SessionProxy >>> import requests >>> sp = SessionProxy(requests.Session()) >>> try: ... sp.get('http://wwwwww.google.com') ... except requests.exceptions.ConnectionError as e: ... print("Error raised") ... Error raised
You may override the pre|post|exception callbacks either by subclassing them or by runtime configuration.
>>> from ahoyhoy.http import SessionProxy >>> import requests >>> >>> def pre_callback(url): ... print('pre') ... return url >>> >>> def post_callback(res): ... print('post') >>> >>> def exception_callback(e): ... print('Exception!!') >>> >>> sp = SessionProxy(requests.Session(), pre_callback=pre_callback, post_callback=post_callback, exception_callback=exception_callback) >>> sp.get('http://google.com') pre post >>> sp.get('http://google1.com') pre Exception!! post
Test proxy for other methods and attributes:
>>> sp.headers {...'User-Agent': ...}
Parameters: - session – custom session
- pre_callback – executed before the proxied method
- post_callback – executed after the proxied method
- exception_callback – the proxied method is wrapped in a try/except block, and when an exception occurs, the exception is passed to this callback
-
exception_callback
(exc)[source]¶ Executed when an exception is thrown by the proxied Requests Session method.
Intended to be overwritten or set by a derived class.
Parameters: exc – the exception raised by the proxied Requests Session method. By default, returns what’s passed in.
-
post_callback
(result)[source]¶ Executed after the proxied Requests method.
Intended to be overwritten or set by a derived class.
Parameters: result – the return value of the proxied Requests method. By default, returns what’s passed in.
-
pre_callback
(urlpath)[source]¶ Executed before the proxied Requests method.
Intended to be overwritten or set by a derived class.
Parameters: urlpath – the arg[0] of the called proxied method. Requests Session methods all take ‘url’ as the first positional parameter. By default, returns what’s passed in.