Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Requests: Hook or no Hook?

I '.get' a request and process the response like:

resp = requests.get('url')
resp = resp.text
.. # do stuff with resp

After reading the package's docs, I saw that there is a hook functionality which would permit me to do:

def process_r(resp, **kwargs): .. do stuff with resp

resp = requests.get('url', hooks = {'response': process_r})

My questions:

When should I use hooks? Or, why should I use hooks?

I wish to initiate an object (a parser) after a request's response is returned using the requests resp.text procedure.

What is the Pythonic, correct approach here for this scenario?

Thank you

like image 729
Phil Avatar asked Jul 21 '13 13:07

Phil


People also ask

What is a hook in request?

It is applied after additional private query variables have been added in, and is one of the places you can hook into to modify the query that will generate your list of posts (or pages) before the main query is executed and the database is actually accessed. Use this hook within functions.

Does Python requests use https?

Requests verifies SSL certificates for HTTPS requests, just like a web browser.

Does Python 3 have requests?

The Requests library is available for both Python 2 and Python 3 from the Python Package Index (PyPI), and has the following features: Allows you to send HTTP/1.1 PUT, DELETE, HEAD, GET and OPTIONS requests with ease.

Are Python requests encrypted?

The process of authentication is required by many APIs to allow access to user specific details. Requests support various types of authentication, such as: Basic Auth: This transfers the authentication details as base64 encoding (text as bytes), meaning there is no encryption and security.


1 Answers

Hooks are not a million miles from 'magic'. They have the effect of making your code potentially do things that will surprise other people (thereby violating "Explicit is better than implicit").

Hooks should really therefore only be used to drive behaviours that will make things more predictable, not less. For example, Requests uses them internally to handle 401 responses for various kinds of authentication.

You should therefore be guided by the restrictions on hooks. The relevant part of the documentation states that hooks need to return a Response object. This leads to a few obvious possible behaviours: you could make additional requests (like the 401 hook above does), or you could mutate the Response in some way.

Initiating a parser is exactly the kind of thing that you shouldn't do with a hook. It should be part of your business logic. I would write a utility function instead.

like image 152
Lukasa Avatar answered Nov 11 '22 22:11

Lukasa