我因此陷入困境:
\nwith httpx.Client(**sessions[scraperIndex]) as client:\n try:\n response = client.get(...)\n except TimeoutError as e:\n print(\'does not hit\')\n except Exception as e:\n print(f\'\xe2\x9b\x94\xef\xb8\x8f Unexpected exception: {e}\')\n print_exc() # hits!\nRun Code Online (Sandbox Code Playgroud)\n不过我收到了以下故障转储。
\n拉出关键线:
\nTimeoutError: The read operation timed out\n\nDuring handling of the above exception, another exception occurred:\n httpcore.ReadTimeout: The read operation timed out\n\nThe above exception was the direct cause of the following exception:\n httpx.ReadTimeout: The read operation timed out\nRun Code Online (Sandbox Code Playgroud)\n为什么我没有TimeoutError抓住这个?
正确的做法是什么?有人可以给出推论的逻辑吗?
\n崩溃转储:
\n\xe2\x9b\x94\xef\xb8\x8f …Run Code Online (Sandbox Code Playgroud) 我在 VirtualBox 上配置并配置了一台具有 2048 MB RAM 的 Fedora 34 虚拟机,以便在localhost:7070. 完整的应用程序源代码和依赖代码以及说明位于此处。以下是我可以制作的最小的可重现示例。
main.py
import os, pathlib
import fastapi as fast
import aiofiles
ROOT_DIR = os.path.dirname(os.path.abspath(__file__))
RESULTS_DIR = pathlib.Path('/'.join((ROOT_DIR, 'results')))
app = fast.FastAPI()
@app.post('/api')
async def upload(
request: fast.Request,
file: fast.UploadFile = fast.File(...),
filedir: str = ''):
dest = RESULTS_DIR.joinpath(filedir, file.filename)
dest.parent.mkdir(parents=True, exist_ok=True)
async with aiofiles.open(dest, 'wb') as buffer:
await file.seek(0)
contents = await file.read()
await buffer.write(contents)
return f'localhost:7070/{dest.parent.name}/{dest.name}'
Run Code Online (Sandbox Code Playgroud)
start.sh服务器应用程序
#! /bin/bash
uvicorn --host "0.0.0.0" --log-level debug …Run Code Online (Sandbox Code Playgroud) 我对异步编程非常陌生,我正在尝试使用 httpx。我有以下代码,我确信我做错了什么 - 只是不知道它是什么。有两种方法,一种是同步,另一种是异步。它们都来自谷歌金融。在我的系统上,我看到花费的时间如下:
异步:5.015218734741211
同步:5.173618316650391
这是代码:
import httpx
import asyncio
import time
#
#--------------------------------------------------------------------
#
#--------------------------------------------------------------------
#
def sync_pull(url):
r = httpx.get(url)
print(r.status_code)
#
#--------------------------------------------------------------------
#
#--------------------------------------------------------------------
#
async def async_pull(url):
async with httpx.AsyncClient() as client:
r = await client.get(url)
print(r.status_code)
#
#--------------------------------------------------------------------
#
#--------------------------------------------------------------------
#
if __name__ == "__main__":
goog_fin_nyse_url = 'https://www.google.com/finance/quote/'
tickers = ['F', 'TWTR', 'CVX', 'VZ', 'GME', 'GM', 'PG', 'AAL',
'MARK', 'AAP', 'THO', 'NGD', 'ZSAN', 'SEAC',
]
print("Running asynchronously...")
async_start = time.time()
for ticker in tickers: …Run Code Online (Sandbox Code Playgroud) 我正在尝试使用 python Fast API 框架代理外部网站(在不同容器上运行的 Flower 监控 URL):
\nclient = AsyncClient(base_url=f'http://containername:7800/monitor')\n\n@app.get(\xe2\x80\x9c/monitor/{path:path}\xe2\x80\x9d)\nasync def tile_request(path: str):\n req = client.build_request("GET", path)\n r = await client.send(req, stream=True)\n return StreamingResponse(\n r.aiter_raw(),\n background=BackgroundTask(r.aclose),\n headers=r.headers\n )\nRun Code Online (Sandbox Code Playgroud)\n它能够代理每个路径的容器 URL。对于前。
\nhttp://python_server:8001/monitor/dashboard --> http://containername:7800/monitor/dashboard
\nhttp://python_server:8001/monitor/tasks --> http://containername:7800/monitor/tasks
\n效果很好。但是当 PATH 的 URL 中有一些查询参数时,它会失败。
\n对于前。
\nhttp://python_server:8001/monitor/dashboard?json=1&_=1641485992460 --> redirects to http://containername:7800/monitor/dashboard \nRun Code Online (Sandbox Code Playgroud)\n(请注意,URL 中不会附加任何查询参数)。
\n任何人都可以帮助我们如何使用任何查询参数代理此外部网站的任何路径。
\n我正在使用httpx库,但我认为aiohttp的原理是相同的。如果我在应用程序的整个生命周期中为多个请求创建并重用 AsyncClient,我是否需要在应用程序关闭事件时调用aclose()(或者如果使用 Client)?close或者这些联系会自行消失。
如果我在 Docker 容器中运行应用程序会怎样?这也会是一个因素吗?
我不明白 AsyncClient 或 Client (或 aoihttp 中的 ClientSession)对象下面发生了什么。
感谢帮助。
我在使用 HTTPX 模块时多次遇到此错误。我相信我知道这意味着什么,但我不知道如何解决。
在下面的示例中,我有一个异步函数 Gather_players(),它将 get 请求发送到我正在使用的 API,然后返回指定 NBA 球队的所有球员的列表。在 teamRoster() 内部,我使用 asyncio.run() 来启动 Gather_players() ,这就是产生此错误的行:RuntimeError: The connection pool was closed while 6 HTTP requests/responses were still in-flight
async def gather_players(list_of_urlCodes):
async def get_json(client, link):
response = await client.get(BASE_URL + link)
return response.json()['league']['standard']['players']
async with httpx.AsyncClient() as client:
tasks = []
for code in list_of_urlCodes:
link = f'/prod/v1/2022/teams/{code}/roster.json'
tasks.append(asyncio.create_task(get_json(client, link)))
list_of_people = await asyncio.gather(*tasks)
return list_of_people
def teamRoster(list_of_urlCodes: list) -> list:
list_of_personIds = asyncio.run(gather_players(list_of_urlCodes))
finalResult = []
for person …Run Code Online (Sandbox Code Playgroud) httpx ×6
python ×5
fastapi ×3
asynchronous ×2
aiohttp ×1
exception ×1
file-upload ×1
httprequest ×1