- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
所以我了解如何通过列表创建异步任务集合并使用 asyncio.gather() 来执行它们,但我不知道如何使用字典执行相同的操作:
from fastapi import FastAPI
import asyncio
import httpx
app = FastAPI()
urls = [
"http://www.google.com",
"https://www.example.org",
"https://stackoverflow.com/",
"https://www.wikipedio.org"
]
async def async_request_return_dict(url: str):
async with httpx.AsyncClient() as client:
r = await client.get(url)
return {url : r.status_code}
# List of async coroutines
@app.get("/async_list")
async def async_list():
tasks = []
for url in urls:
tasks.append(async_request_return_dict(url=url))
response = await asyncio.gather(*tasks)
# Convert list of dict -> dict
dict_response = dict()
for url in response:
dict_response.update(url)
return dict_response
async def async_request_return_status(url: str):
async with httpx.AsyncClient() as client:
r = await client.get(url)
return r.status_code
# Dict of async coroutines
@app.get("/async_dict")
async def async_dict():
tasks = dict()
for url in urls:
tasks[url] = async_request_return_status(url=url)
### How do you run async co-routines inside a dict??? ###
await asyncio.gather(*tasks.values())
print(tasks)
return tasks
/async_list 的输出:
{
"http://www.google.com":200,
"https://www.example.org":200,
"https://stackoverflow.com/":200,
"https://www.wikipedio.org":200
}
/async_dict 的回溯:
INFO: Application startup complete.
{'http://www.google.com': <coroutine object async_request_return_status at 0x7fec83ded6c0>, 'https://www.example.org': <coroutine object async_request_return_status at 0x7fec83ded740>, 'https://stackoverflow.com/': <coroutine object async_request_return_status at 0x7fec83ded7c0>, 'https://www.wikipedio.org': <coroutine object async_request_return_status at 0x7fec83ded840>}
INFO: 127.0.0.1:58350 - "GET /async_dict HTTP/1.1" 500 Internal Server Error
ERROR: Exception in ASGI application
Traceback (most recent call last):
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/uvicorn/protocols/http/h11_impl.py", line 396, in run_asgi
result = await app(self.scope, self.receive, self.send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/uvicorn/middleware/proxy_headers.py", line 45, in __call__
return await self.app(scope, receive, send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/applications.py", line 199, in __call__
await super().__call__(scope, receive, send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/applications.py", line 111, in __call__
await self.middleware_stack(scope, receive, send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 181, in __call__
raise exc from None
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/middleware/errors.py", line 159, in __call__
await self.app(scope, receive, _send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 82, in __call__
raise exc from None
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/exceptions.py", line 71, in __call__
await self.app(scope, receive, sender)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 566, in __call__
await route.handle(scope, receive, send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 227, in handle
await self.app(scope, receive, send)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/starlette/routing.py", line 41, in app
response = await func(request)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 209, in app
response_data = await serialize_response(
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/routing.py", line 137, in serialize_response
return jsonable_encoder(response_content)
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/encoders.py", line 90, in jsonable_encoder
encoded_value = jsonable_encoder(
File "/home/cmaggio/repos/async_dict/.venv/lib/python3.8/site-packages/fastapi/encoders.py", line 141, in jsonable_encoder
raise ValueError(errors)
ValueError: [TypeError("'coroutine' object is not iterable"), TypeError('vars() argument must have __dict__ attribute')]
基本上如何使用字典执行 asyncio.gather()。或者是在列表中执行协程并在解析所有可等待对象后重新构建字典的第一种方法。
最佳答案
这不会像您预期的那样工作,因为您的字典值是协程,但实际结果值是从 asyncio.gather
返回的。
The order of result values corresponds to the order of awaitables inaws.
基于这个事实你可以这样做:
测试.py:
import asyncio
import httpx
URLS = (
"http://www.google.com",
"https://www.example.org",
"https://stackoverflow.com/",
"https://www.wikipedio.org",
)
async def req(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
return r.status_code
async def main():
tasks = []
for url in URLS:
tasks.append(asyncio.create_task(req(url)))
results = await asyncio.gather(*tasks)
print(dict(zip(URLS, results)))
if __name__ == "__main__":
asyncio.run(main())
测试:
$ python test.py
{'http://www.google.com': 200, 'https://www.example.org': 200, 'https://stackoverflow.com/': 200, 'https://www.wikipedio.org': 200}
关于Python asyncio 收集字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67427194/
我正在我的一个项目中使用 aiohttp 并想限制每秒发出的请求数。我正在使用 asyncio.Semaphore 来做到这一点。我的挑战是我可能想要增加/减少每秒允许的请求数。 例如: limit
如何混合 async with api.open() as o: ... 和 o = await api.open() 在一个功能中? 自从第一次需要带有 __aenter__ 的对象以来和
有 2 个工作:“wash_clothes”(job1) 和“setup_cleaning_robot”(job2),每个工作需要你 7 和 3 秒,你必须做到世界末日。 这是我的代码: import
我们有一种设置线程名称的方法:thread = threading.Thread(name='Very important thread', target=foo),然后在格式化程序中使用 %(thr
我有一些代码,用于抓取 URL、解析信息,然后使用 SQLAlchemy 将其放入数据库中。我尝试异步执行此操作,同时限制同时请求的最大数量。 这是我的代码: async def get_url(ai
1>Python Asyncio 未使用 asyncio.run_coroutine_threadsafe 运行新的协程。下面是在Mac上进行的代码测试。 ——————————————————————
asyncio.gather和 asyncio.wait似乎有类似的用途:我有一堆我想要执行/等待的异步事情(不一定要在下一个开始之前等待一个完成)。它们使用不同的语法,并且在某些细节上有所不同,但对
我正在尝试使用 asyncio 运行以下程序: import asyncio async def main(): print('Hello') await asyncio.sleep(
我正在尝试在事件循环之外使用协程函数。 (在这种情况下,我想在 Django 中调用一个也可以在事件循环中使用的函数) 如果不使调用函数成为协程,似乎没有办法做到这一点。 我意识到 Django 是为
我有一个假设 asyncio.gather设想: await asyncio.gather( cor1, [cor2, cor3], cor4, ) 我要 cor2和 cor3
我有多个服务器,每个服务器都是 asyncio.start_server 返回的实例。我需要我的 web_server 与 websockets 一起使用,以便能够使用我的 javascript 客户
我正在使用 Python 3 asyncio 框架评估定期执行的不同模式(为简洁起见省略了实际 sleep /延迟),我有两段代码表现不同,我无法解释原因。第一个版本使用 yield from 递归调
从事件线程外部将协程推送到事件线程的 pythonic 方法是什么? 最佳答案 更新信息: 从Python 3.7 高级函数asyncio.create_task(coro)开始was added并且
我有一个大型 (1M) 数据库结果集,我想为其每一行调用一个 REST API。 API 可以接受批处理请求,但我不确定如何分割 rows 生成器,以便每个任务处理一个行列表,比如 10。我宁愿不预先
迷失在异步中。 我同时在学习Kivy和asyncio,卡在了解决运行Kivy和运行asyncio循环的问题上,无论怎么转,都是阻塞调用,需要顺序执行(好吧,我希望我是错的),例如 loop = asy
我有这个 3.6 异步代码: async def send(command,userPath,token): async with websockets.connect('wss://127.
首先,我需要警告你:我是 asyncio 的新手,而且我是 我马上警告你,我是 asyncio 的新手,我很难想象引擎盖下的库里有什么。 这是我的代码: import asyncio semaphor
我有一个asyncio.PriorityQueue,用作网络爬虫的URL队列,当我调用url_queue.get时,得分最低的URL首先从队列中删除()。当队列达到 maxsize 项时,默认行为是阻
探索 Python 3.4.0 的 asyncio 模块,我试图创建一个类,其中包含从类外部的 event_loop 调用的 asyncio.coroutine 方法。 我的工作代码如下。 impor
我有一个可能是无用的问题,但尽管如此,我还是觉得我错过了一些对于理解 asyncio 的工作方式可能很重要的东西。 我刚刚开始熟悉 asyncio 并编写了这段非常基本的代码: import asyn
我是一名优秀的程序员,十分优秀!