Python Requests: Hook or no Hook? -
i '.get' request , process response like:
resp = requests.get('url') resp = resp.text .. # stuff resp
after reading package's docs, saw there hook functionality permit me do:
def process_r(resp, **kwargs): .. stuff resp resp = requests.get('url', hooks = {'response': process_r})
my questions:
when should use hooks? or, why should use hooks?
i wish initiate object (a parser) after request's response returned using requests resp.text
procedure.
what pythonic, correct approach here scenario?
thank you
hooks not million miles 'magic'. have effect of making code potentially things surprise other people (thereby violating "explicit better implicit").
hooks should therefore used drive behaviours make things more predictable, not less. example, requests uses them internally handle 401 responses various kinds of authentication.
you should therefore guided restrictions on hooks. relevant part of documentation states hooks need return response
object. leads few obvious possible behaviours: make additional requests (like 401 hook above does), or mutate response
in way.
initiating parser kind of thing shouldn't hook. should part of business logic. write utility function instead.
Comments
Post a Comment