Python queries: hook or not hook?

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

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

After reading the package documents, I saw that there is a hook function that would allow 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 want to initiate an object (parser) after responding to a request using the resp.text request resp.text .

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

thanks

+4
source share
1 answer

Hooks are not a million miles from magic. They lead to the fact that your code can potentially do something that will surprise other people (thereby violating "Explicit is better than implicit").

Hooks should therefore only be used to control behavior that will make things more predictable, not less. For example, requests use them internally to process 401 responses for various types of authentication.

Therefore, you should be guided by the restrictions on hooks. The relevant part of the documentation states that hooks should return a Response object. This leads to several obvious possible behaviors: you can make additional requests (e.g. 401 above), or you can somehow modify the Response .

Initiating a parser is exactly what you don't need to do with a hook. It should be part of your business logic. Instead, I will write a utility function.

+6
source

Source: https://habr.com/ru/post/1492572/


All Articles