Mixing synchronous/asynchronous use of httpx calls in py3

Original link: https://blog.est.im/2023/stdout-07

For example, the development requirement is to request an http API, get the data, analyze the return, then the general approach is to encapsulate a method, such as

 import httpx def get_sth(p1, default=MY_VAL): # network r = httpx.get(API_URL, params={'t1': p1}) # parsing res = r.json().get('my_key') or MY_VAL

But if you want to use this code in async/await, you have to change it to

 import httpx async def get_sth(p1, default=MY_VAL): # network with http.AsyncClient() as client: r = await client.get(API_URL, params={'t1': p1}) # parsing res = r.json().get('my_key') or MY_VAL

Note that def get_sth() must also be changed async def get_sth . This is called async/await contagion

At this time, if you want to abstract this piece of code so that both synchronous and asynchronous libraries can be called, I found a best practice in the recent refactoring:

 import httpx def get_sth(p1, default=MY_VAL): r = httpx.Request('GET', API_URL, params={'t1': p1}) r.parse = lambda x: (x.get('my_key') or MY_VAL) # 同步调用: with httpx.Client() as client: r = client.send(get_sth()) r.request.parse(r.json()) # 异步调用: async with httpx.AsyncClient() as client: r = await client.send(get_sth()) r.request.parse(r.json())

The idea is to decouple logic and transport, which is Sans-IO in a sense, right?

This article is transferred from: https://blog.est.im/2023/stdout-07
This site is only for collection, and the copyright belongs to the original author.