Closed Scylla2020 closed 5 months ago
Check out SessionWrapper.request_hooks and RequestHook:
>>> from reader import make_reader
>>> reader = make_reader('')
>>> reader.add_feed('http://localhost:8080')
>>>
>>> def hook(session, request, **kwargs):
... request.headers.setdefault('custom', 'header')
...
>>> reader._parser.session_factory.request_hooks.append(hook)
>>> reader.update_feed('http://localhost:8080')
Note the custom
header received by nc
:
$ echo 'HTTP/1.1 304' | nc -l localhost 8080
GET / HTTP/1.1
Host: localhost:8080
User-Agent: python-reader/3.13.dev0 (+https://github.com/lemon24/reader)
Accept-Encoding: gzip, deflate
Accept: application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/feed+json,application/xml;q=0.9,application/json;q=0.9,text/xml;q=0.2,*/*;q=0.1
Connection: keep-alive
A-IM: feed
custom: header
If you want to retry a request only for specific responses, check out ResponseHook; for example, the ua_fallback plugin uses it to retry with a different user agent if it gets a 403 the first time (source).
How do I add headers that can be used by the underlying requests session? I currently have
It fails and I get a long response part of which is
When I simply use requests library with those headers I get the correct response so not sure how to add the headers to reader?