diff --git a/examples/background_tasks.py b/examples/background_tasks.py index 2a1ec12afae..5ce9a03d54f 100755 --- a/examples/background_tasks.py +++ b/examples/background_tasks.py @@ -2,12 +2,12 @@ """Example of aiohttp.web.Application.on_startup signal handler""" import asyncio -import aioredis +import aioredis # type: ignore from aiohttp import web -async def websocket_handler(request): +async def websocket_handler(request: web.Request) -> web.StreamResponse: ws = web.WebSocketResponse() await ws.prepare(request) request.app["websockets"].append(ws) @@ -20,14 +20,15 @@ async def websocket_handler(request): return ws -async def on_shutdown(app): +async def on_shutdown(app: web.Application) -> None: for ws in app["websockets"]: await ws.close(code=999, message="Server shutdown") -async def listen_to_redis(app): +async def listen_to_redis(app: web.Application) -> None: try: - sub = await aioredis.create_redis(("localhost", 6379), loop=app.loop) + loop = asyncio.get_event_loop() + sub = await aioredis.create_redis(("localhost", 6379), loop=loop) ch, *_ = await sub.subscribe("news") async for msg in ch.iter(encoding="utf-8"): # Forward message to all connected websockets: @@ -43,17 +44,17 @@ async def listen_to_redis(app): print("Redis connection closed.") -async def start_background_tasks(app): +async def start_background_tasks(app: web.Application) -> None: app["redis_listener"] = app.loop.create_task(listen_to_redis(app)) -async def cleanup_background_tasks(app): +async def cleanup_background_tasks(app: web.Application) -> None: print("cleanup background tasks...") app["redis_listener"].cancel() await app["redis_listener"] -def init(): +def init() -> web.Application: app = web.Application() app["websockets"] = [] app.router.add_get("/news", websocket_handler) diff --git a/examples/cli_app.py b/examples/cli_app.py index 9fbd3b76049..5357a0233f4 100755 --- a/examples/cli_app.py +++ b/examples/cli_app.py @@ -14,17 +14,18 @@ """ from argparse import ArgumentParser +from typing import Optional, Sequence from aiohttp import web -def display_message(req): +async def display_message(req: web.Request) -> web.StreamResponse: args = req.app["args"] text = "\n".join([args.message] * args.repeat) return web.Response(text=text) -def init(argv): +def init(argv: Optional[Sequence[str]]) -> web.Application: arg_parser = ArgumentParser( prog="aiohttp.web ...", description="Application CLI", add_help=False ) diff --git a/examples/client_auth.py b/examples/client_auth.py index 52b4f6cc0a3..248f67a48d6 100755 --- a/examples/client_auth.py +++ b/examples/client_auth.py @@ -4,7 +4,7 @@ import aiohttp -async def fetch(session): +async def fetch(session: aiohttp.ClientSession) -> None: print("Query http://httpbin.org/basic-auth/andrew/password") async with session.get("http://httpbin.org/basic-auth/andrew/password") as resp: print(resp.status) @@ -12,7 +12,7 @@ async def fetch(session): print(body) -async def go(): +async def go() -> None: async with aiohttp.ClientSession( auth=aiohttp.BasicAuth("andrew", "password") ) as session: diff --git a/examples/client_json.py b/examples/client_json.py index 8a9a609bc91..e24e0690708 100755 --- a/examples/client_json.py +++ b/examples/client_json.py @@ -4,7 +4,7 @@ import aiohttp -async def fetch(session): +async def fetch(session: aiohttp.ClientSession): print("Query http://httpbin.org/get") async with session.get("http://httpbin.org/get") as resp: print(resp.status) @@ -12,7 +12,7 @@ async def fetch(session): print(data) -async def go(): +async def go() -> None: async with aiohttp.ClientSession() as session: await fetch(session) diff --git a/examples/client_ws.py b/examples/client_ws.py index 2b2bf5869b5..1a55b36c4da 100755 --- a/examples/client_ws.py +++ b/examples/client_ws.py @@ -8,11 +8,11 @@ import aiohttp -async def start_client(loop, url): +async def start_client(loop: asyncio.AbstractEventLoop, url: str) -> None: name = input("Please enter your name: ") # input reader - def stdin_callback(): + def stdin_callback() -> None: line = sys.stdin.buffer.readline().decode("utf-8") if not line: loop.stop() @@ -21,7 +21,7 @@ def stdin_callback(): loop.add_reader(sys.stdin.fileno(), stdin_callback) - async def dispatch(): + async def dispatch() -> None: while True: msg = await ws.receive() @@ -30,7 +30,7 @@ async def dispatch(): elif msg.type == aiohttp.WSMsgType.BINARY: print("Binary: ", msg.data) elif msg.type == aiohttp.WSMsgType.PING: - ws.pong() + await ws.pong() elif msg.type == aiohttp.WSMsgType.PONG: print("Pong received") else: diff --git a/examples/curl.py b/examples/curl.py index a39639af34e..c3b54da6af2 100755 --- a/examples/curl.py +++ b/examples/curl.py @@ -6,7 +6,7 @@ import aiohttp -async def curl(url): +async def curl(url: str) -> None: async with aiohttp.ClientSession() as session: async with session.request("GET", url) as response: print(repr(response)) diff --git a/examples/fake_server.py b/examples/fake_server.py index 74767f5f126..9105d990ea4 100755 --- a/examples/fake_server.py +++ b/examples/fake_server.py @@ -3,22 +3,25 @@ import pathlib import socket import ssl +from typing import Any, Dict, List, Union -import aiohttp -from aiohttp import web -from aiohttp.resolver import DefaultResolver -from aiohttp.test_utils import unused_port +from aiohttp import ClientSession, TCPConnector, resolver, test_utils, web class FakeResolver: _LOCAL_HOST = {0: "127.0.0.1", socket.AF_INET: "127.0.0.1", socket.AF_INET6: "::1"} - def __init__(self, fakes): + def __init__(self, fakes: Dict[str, int]) -> None: """fakes -- dns -> port dict""" self._fakes = fakes - self._resolver = DefaultResolver() - - async def resolve(self, host, port=0, family=socket.AF_INET): + self._resolver = resolver.DefaultResolver() + + async def resolve( + self, + host: str, + port: int = 0, + family: Union[socket.AddressFamily, int] = socket.AF_INET, + ) -> List[Dict[str, Any]]: fake_port = self._fakes.get(host) if fake_port is not None: return [ @@ -34,9 +37,12 @@ async def resolve(self, host, port=0, family=socket.AF_INET): else: return await self._resolver.resolve(host, port, family) + async def close(self) -> None: + self._resolver.close() + class FakeFacebook: - def __init__(self): + def __init__(self) -> None: self.app = web.Application() self.app.router.add_routes( [ @@ -51,21 +57,20 @@ def __init__(self): self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH) self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key)) - async def start(self): - port = unused_port() - self.runner = web.AppRunner(self.app) + async def start(self) -> Dict[str, int]: + port = test_utils.unused_port() await self.runner.setup() site = web.TCPSite(self.runner, "127.0.0.1", port, ssl_context=self.ssl_context) await site.start() return {"graph.facebook.com": port} - async def stop(self): + async def stop(self) -> None: await self.runner.cleanup() - async def on_me(self, request): + async def on_me(self, request: web.Request) -> web.StreamResponse: return web.json_response({"name": "John Doe", "id": "12345678901234567"}) - async def on_my_friends(self, request): + async def on_my_friends(self, request: web.Request) -> web.StreamResponse: return web.json_response( { "data": [ @@ -88,15 +93,15 @@ async def on_my_friends(self, request): ) -async def main(): +async def main() -> None: token = "ER34gsSGGS34XCBKd7u" fake_facebook = FakeFacebook() info = await fake_facebook.start() resolver = FakeResolver(info) - connector = aiohttp.TCPConnector(resolver=resolver, ssl=False) + connector = TCPConnector(resolver=resolver, ssl=False) - async with aiohttp.ClientSession(connector=connector) as session: + async with ClientSession(connector=connector) as session: async with session.get( "https://graph.facebook.com/v2.7/me", params={"access_token": token} ) as resp: diff --git a/examples/lowlevel_srv.py b/examples/lowlevel_srv.py index 5a003f40f42..bd97bc23dc7 100644 --- a/examples/lowlevel_srv.py +++ b/examples/lowlevel_srv.py @@ -1,13 +1,13 @@ import asyncio -from aiohttp import web +from aiohttp import web, web_request -async def handler(request): +async def handler(request: web_request.BaseRequest) -> web.StreamResponse: return web.Response(text="OK") -async def main(loop): +async def main(loop: asyncio.AbstractEventLoop) -> None: server = web.Server(handler) await loop.create_server(server, "127.0.0.1", 8080) print("======= Serving on http://127.0.0.1:8080/ ======") diff --git a/examples/server_simple.py b/examples/server_simple.py index 3b07cb7d68b..c68e141b33e 100644 --- a/examples/server_simple.py +++ b/examples/server_simple.py @@ -2,13 +2,13 @@ from aiohttp import web -async def handle(request): +async def handle(request: web.Request) -> web.StreamResponse: name = request.match_info.get("name", "Anonymous") text = "Hello, " + name return web.Response(text=text) -async def wshandle(request): +async def wshandle(request: web.Request) -> web.StreamResponse: ws = web.WebSocketResponse() await ws.prepare(request) diff --git a/examples/web_classview.py b/examples/web_classview.py index a1bf6e47170..fc3fe67b851 100755 --- a/examples/web_classview.py +++ b/examples/web_classview.py @@ -2,7 +2,6 @@ """Example for aiohttp.web class based views """ - import functools import json @@ -10,7 +9,7 @@ class MyView(web.View): - async def get(self): + async def get(self) -> web.StreamResponse: return web.json_response( { "method": self.request.method, @@ -20,7 +19,7 @@ async def get(self): dumps=functools.partial(json.dumps, indent=4), ) - async def post(self): + async def post(self) -> web.StreamResponse: data = await self.request.post() return web.json_response( { @@ -32,7 +31,7 @@ async def post(self): ) -async def index(request): +async def index(request: web.Request) -> web.StreamResponse: txt = """ @@ -51,7 +50,7 @@ async def index(request): return web.Response(text=txt, content_type="text/html") -def init(): +def init() -> web.Application: app = web.Application() app.router.add_get("/", index) app.router.add_get("/get", MyView) diff --git a/examples/web_cookies.py b/examples/web_cookies.py index 7ba0c856958..bd3d5961c4b 100755 --- a/examples/web_cookies.py +++ b/examples/web_cookies.py @@ -16,25 +16,25 @@ """ -async def root(request): +async def root(request: web.Request) -> web.StreamResponse: resp = web.Response(content_type="text/html") resp.text = tmpl.format(pformat(request.cookies)) return resp -async def login(request): +async def login(request: web.Request) -> None: exc = web.HTTPFound(location="/") exc.set_cookie("AUTH", "secret") raise exc -async def logout(request): +async def logout(request: web.Request) -> None: exc = web.HTTPFound(location="/") exc.del_cookie("AUTH") raise exc -def init(): +def init() -> web.Application: app = web.Application() app.router.add_get("/", root) app.router.add_get("/login", login) diff --git a/examples/web_rewrite_headers_middleware.py b/examples/web_rewrite_headers_middleware.py index e21012525fc..7fc569bce7a 100755 --- a/examples/web_rewrite_headers_middleware.py +++ b/examples/web_rewrite_headers_middleware.py @@ -2,15 +2,18 @@ """ Example for rewriting response headers by middleware. """ +from typing import Awaitable, Callable from aiohttp import web +_WebHandler = Callable[[web.Request], Awaitable[web.StreamResponse]] -async def handler(request): + +async def handler(request: web.Request) -> web.StreamResponse: return web.Response(text="Everything is fine") -async def middleware(request, handler): +async def middleware(request: web.Request, handler: _WebHandler) -> web.StreamResponse: try: response = await handler(request) except web.HTTPException as exc: @@ -20,7 +23,7 @@ async def middleware(request, handler): return response -def init(): +def init() -> web.Application: app = web.Application(middlewares=[middleware]) app.router.add_get("/", handler) return app diff --git a/examples/web_srv.py b/examples/web_srv.py index b572326a3a2..b87f6c43baf 100755 --- a/examples/web_srv.py +++ b/examples/web_srv.py @@ -7,7 +7,7 @@ from aiohttp import web -async def intro(request): +async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent( """\ Type {url}/hello/John {url}/simple or {url}/change_body @@ -23,18 +23,18 @@ async def intro(request): return resp -async def simple(request): +async def simple(request: web.Request) -> web.StreamResponse: return web.Response(text="Simple answer") -async def change_body(request): +async def change_body(request: web.Request) -> web.StreamResponse: resp = web.Response() resp.body = b"Body changed" resp.content_type = "text/plain" return resp -async def hello(request): +async def hello(request: web.Request) -> web.StreamResponse: resp = web.StreamResponse() name = request.match_info.get("name", "Anonymous") answer = ("Hello, " + name).encode("utf8") @@ -46,7 +46,7 @@ async def hello(request): return resp -def init(): +def init() -> web.Application: app = web.Application() app.router.add_get("/", intro) app.router.add_get("/simple", simple) diff --git a/examples/web_srv_route_deco.py b/examples/web_srv_route_deco.py index 332990362cc..65a4f8618b2 100644 --- a/examples/web_srv_route_deco.py +++ b/examples/web_srv_route_deco.py @@ -11,7 +11,7 @@ @routes.get("/") -async def intro(request): +async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent( """\ Type {url}/hello/John {url}/simple or {url}/change_body @@ -28,12 +28,12 @@ async def intro(request): @routes.get("/simple") -async def simple(request): +async def simple(request: web.Request) -> web.StreamResponse: return web.Response(text="Simple answer") @routes.get("/change_body") -async def change_body(request): +async def change_body(request: web.Request) -> web.StreamResponse: resp = web.Response() resp.body = b"Body changed" resp.content_type = "text/plain" @@ -41,7 +41,7 @@ async def change_body(request): @routes.get("/hello") -async def hello(request): +async def hello(request: web.Request) -> web.StreamResponse: resp = web.StreamResponse() name = request.match_info.get("name", "Anonymous") answer = ("Hello, " + name).encode("utf8") @@ -53,7 +53,7 @@ async def hello(request): return resp -def init(): +def init() -> web.Application: app = web.Application() app.router.add_routes(routes) return app diff --git a/examples/web_srv_route_table.py b/examples/web_srv_route_table.py index f53142adad4..4d1acc43c57 100644 --- a/examples/web_srv_route_table.py +++ b/examples/web_srv_route_table.py @@ -8,7 +8,7 @@ from aiohttp import web -async def intro(request): +async def intro(request: web.Request) -> web.StreamResponse: txt = textwrap.dedent( """\ Type {url}/hello/John {url}/simple or {url}/change_body @@ -24,18 +24,18 @@ async def intro(request): return resp -async def simple(request): +async def simple(request: web.Request) -> web.StreamResponse: return web.Response(text="Simple answer") -async def change_body(request): +async def change_body(request: web.Request) -> web.StreamResponse: resp = web.Response() resp.body = b"Body changed" resp.content_type = "text/plain" return resp -async def hello(request): +async def hello(request: web.Request) -> web.StreamResponse: resp = web.StreamResponse() name = request.match_info.get("name", "Anonymous") answer = ("Hello, " + name).encode("utf8") @@ -47,7 +47,7 @@ async def hello(request): return resp -def init(): +def init() -> web.Application: app = web.Application() app.router.add_routes( [ diff --git a/examples/web_ws.py b/examples/web_ws.py index 970f1506be3..24610f09bfc 100755 --- a/examples/web_ws.py +++ b/examples/web_ws.py @@ -3,13 +3,14 @@ """ import os +from typing import Union from aiohttp import web WS_FILE = os.path.join(os.path.dirname(__file__), "websocket.html") -async def wshandler(request): +async def wshandler(request: web.Request) -> Union[web.WebSocketResponse, web.Response]: resp = web.WebSocketResponse() available = resp.can_prepare(request) if not available: @@ -42,12 +43,12 @@ async def wshandler(request): await ws.send_str("Someone disconnected.") -async def on_shutdown(app): +async def on_shutdown(app: web.Application) -> None: for ws in app["sockets"]: await ws.close() -def init(): +def init() -> web.Application: app = web.Application() app["sockets"] = [] app.router.add_get("/", wshandler)