Python 异步非阻塞 Requests POST 请求示例
以下是一个使用异步非阻塞的 requests.post() 函数示例:
import aiohttp
async def async_post(url, headers=None, data=None, json=None, timeout=None):
async with aiohttp.ClientSession() as session:
async with session.post(url, headers=headers, data=data, json=json, timeout=timeout) as response:
return await response.text()
使用示例:
import asyncio
async def main():
url = 'https://httpbin.org/post'
headers = {'Content-Type': 'application/json'}
data = {'key': 'value'}
response = await async_post(url, headers=headers, json=data)
print(response)
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
注意:这里使用了 aiohttp 库来实现异步非阻塞的请求。同时,注意使用 async/await 语法。如果使用 Python 3.6 以下版本,可以使用 asyncio.coroutine 和 yield from 语法来实现异步。
原文地址: https://www.cveoy.top/t/topic/oo6D 著作权归作者所有。请勿转载和采集!