python 异步请求
python asynchronous requests
所以我有一个图像列表 url,我想用请求库迭代这些图像并将所有图像下载到一个目录中。
def get_image(url, image_name):
path = pathlib.Path('/path/to/some/directory')
response = requests.get(url, stream=True)
with open('{}/{}.png'.format(path, image_name), 'wb') as file:
for block in response.iter_content(1024):
file.write(block)
for url in urls:
get_image(url, image_name)
现在,一旦针对特定异步请求返回响应,我是否无法创建一个装饰器来使函数回调到 运行?
如果你想要多个并发 requests
+ 回调,你可以使用像 grequests 这样的模块。与asyncio
.
无关
asyncio
- 就是要避免使用回调(避免 callback hell)并使异步代码的编写与同步代码一样简单。
如果您决定尝试 asyncio
,您应该使用 aiohttp
client instead of requests
(this is preferred way) or run requests
in thread pool managed by asyncio. Example of both ways can be found .
所以我有一个图像列表 url,我想用请求库迭代这些图像并将所有图像下载到一个目录中。
def get_image(url, image_name):
path = pathlib.Path('/path/to/some/directory')
response = requests.get(url, stream=True)
with open('{}/{}.png'.format(path, image_name), 'wb') as file:
for block in response.iter_content(1024):
file.write(block)
for url in urls:
get_image(url, image_name)
现在,一旦针对特定异步请求返回响应,我是否无法创建一个装饰器来使函数回调到 运行?
如果你想要多个并发 requests
+ 回调,你可以使用像 grequests 这样的模块。与asyncio
.
asyncio
- 就是要避免使用回调(避免 callback hell)并使异步代码的编写与同步代码一样简单。
如果您决定尝试 asyncio
,您应该使用 aiohttp
client instead of requests
(this is preferred way) or run requests
in thread pool managed by asyncio. Example of both ways can be found