From aedb0bb4b803215a62db6f52aba52c037aec91c5 Mon Sep 17 00:00:00 2001 From: Christian Clauss Date: Wed, 19 Jul 2023 17:41:39 +0200 Subject: [PATCH] Fix async functions should not call open() % [`ruff --select=ASYNC .`](https://beta.ruff.rs/docs/rules/open-sleep-or-subprocess-in-async-function) 2 ASYNC101 [ ] Async functions should not call `open`, `time.sleep`, or `subprocess` methods --- examples/web_ws.py | 6 ++++-- requirements/lint.txt | 1 + requirements/test.txt | 1 + tools/bench-asyncio-write.py | 6 ++++-- 4 files changed, 10 insertions(+), 4 deletions(-) diff --git a/examples/web_ws.py b/examples/web_ws.py index ec817d501b9..d09df5612a4 100755 --- a/examples/web_ws.py +++ b/examples/web_ws.py @@ -8,6 +8,8 @@ import os from typing import List, Union +import aiofiles + from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), "websocket.html") @@ -18,8 +20,8 @@ async def wshandler(request: web.Request) -> Union[web.WebSocketResponse, web.Re resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: - with open(WS_FILE, "rb") as fp: - return web.Response(body=fp.read(), content_type="text/html") + async with aiofiles.open(WS_FILE, "rb") as fp: + return web.Response(body=await fp.read(), content_type="text/html") await resp.prepare(request) diff --git a/requirements/lint.txt b/requirements/lint.txt index 1fe526e0c91..fc4c03dbe7c 100644 --- a/requirements/lint.txt +++ b/requirements/lint.txt @@ -4,4 +4,5 @@ mypy==0.982; implementation_name=="cpython" pre-commit==2.17.0 pytest==6.2.5 slotscheck==0.8.0 +types-aiofiles==23.1.0.4 uvloop==0.17.0; platform_system!="Windows" diff --git a/requirements/test.txt b/requirements/test.txt index 83ab6f34ffe..2f649c2f7af 100644 --- a/requirements/test.txt +++ b/requirements/test.txt @@ -1,4 +1,5 @@ -r base.txt +aiofiles Brotli==1.0.9 coverage==6.4.2 cryptography==36.0.1; platform_machine!="i686" # no 32-bit wheels; no python 3.9 wheels yet diff --git a/tools/bench-asyncio-write.py b/tools/bench-asyncio-write.py index 5ae347172fb..1e0b458b884 100644 --- a/tools/bench-asyncio-write.py +++ b/tools/bench-asyncio-write.py @@ -5,6 +5,8 @@ import signal from typing import List, Tuple +import aiofiles + PORT = 8888 server = os.fork() @@ -123,9 +125,9 @@ async def bench(job_title, w, body, base=None): base = await bench(t, writes[0], c) for w in writes[1:]: await bench("", w, c, base) - with open("bench.md", "w") as f: + async with aiofiles.open("bench.md", "w") as f: for line in res: - f.write("| {} |\n".format(" | ".join(line))) + await f.write("| {} |\n".format(" | ".join(line))) loop = asyncio.get_event_loop()