英文:
Does python have asynchronous web client requests (like C# async/await)? Or is each call fundamentally synchronous (like Java 1.8)?
问题
我正在为一个RESTful服务编写Python客户端,以便在Python应用程序内进行请求。已经存在一个C#和一个Java客户端,我正在尝试弄清楚我应该参考这两个客户端中的哪一个作为指南。所以,Python是否有异步的网络客户端请求(类似于C#的async/await)?还是每个调用都是基本同步的(类似于Java 1.8)?我并不是在寻求关于软件库、编程语言等的建议。我所询问的是,Python运行时是否有一个可以进行异步请求的网络客户端类,类似于C#,或者是否像Java 1.8那样只有同步调用。
英文:
Im writing a Python client for a restful service so that I can make requests within a python application. There already exists a C# and a Java client and Im trying to figure out which of the two clients I should follow as a guide. So does python have asynchronous web client requests (like C# async/await)? Or is each call fundamentally synchronous (like Java 1.8)? I am not asking for a recommendation for a software library, programming language, etc. What I'm asking is if the python runtime has a web client class that can make async requests like C#. Or if it's like Java 1.8 where all it has is the synchronous calls.
答案1
得分: 2
你可以使用Asyncio库。
import asyncio
async def wait_around(n, name):
for i in range(n):
print(f"{name}: iteration {i}")
await asyncio.sleep(1.0)
async def main():
await asyncio.gather(*[
wait_around(2, "coroutine 0"), wait_around(5, "coroutine 1")
])
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
英文:
you can use the Asyncio library
import asyncio
async def wait_around(n, name):
for i in range(n):
print(f"{name}: iteration {i}")
await asyncio.sleep(1.0)
async def main():
await asyncio.gather(*[
wait_around(2, "coroutine 0"), wait_around(5, "coroutine 1")
])
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
答案2
得分: 0
没有,运行时本身不支持异步网络请求,而根据之前的回答,使用asynchio也无法用于网络请求。
我知道你说你不需要库的推荐,但为了完整起见,我所见过的唯一一种从Python进行异步网络请求的方式是使用aiohttp包。
英文:
> What I'm asking is if the python runtime has a web client class that can make async requests
No, the runtime itself does not have support for async web requests, and using asynchio as per the previous answer doesn't work for web requests.
I know you said you weren't looking for library recommendations, but for completeness sake, the only way I've seen to make async web requests from python is by using the
aiohttp package.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论