Skip to content

Commit 6f73339

Browse files
authored
Added typing to examples (#5256)
1 parent 5357858 commit 6f73339

16 files changed

+82
-72
lines changed

examples/background_tasks.py

Lines changed: 9 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,12 +2,12 @@
22
"""Example of aiohttp.web.Application.on_startup signal handler"""
33
import asyncio
44

5-
import aioredis
5+
import aioredis # type: ignore
66

77
from aiohttp import web
88

99

10-
async def websocket_handler(request):
10+
async def websocket_handler(request: web.Request) -> web.StreamResponse:
1111
ws = web.WebSocketResponse()
1212
await ws.prepare(request)
1313
request.app["websockets"].append(ws)
@@ -20,14 +20,15 @@ async def websocket_handler(request):
2020
return ws
2121

2222

23-
async def on_shutdown(app):
23+
async def on_shutdown(app: web.Application) -> None:
2424
for ws in app["websockets"]:
2525
await ws.close(code=999, message="Server shutdown")
2626

2727

28-
async def listen_to_redis(app):
28+
async def listen_to_redis(app: web.Application) -> None:
2929
try:
30-
sub = await aioredis.create_redis(("localhost", 6379), loop=app.loop)
30+
loop = asyncio.get_event_loop()
31+
sub = await aioredis.create_redis(("localhost", 6379), loop=loop)
3132
ch, *_ = await sub.subscribe("news")
3233
async for msg in ch.iter(encoding="utf-8"):
3334
# Forward message to all connected websockets:
@@ -43,17 +44,17 @@ async def listen_to_redis(app):
4344
print("Redis connection closed.")
4445

4546

46-
async def start_background_tasks(app):
47+
async def start_background_tasks(app: web.Application) -> None:
4748
app["redis_listener"] = app.loop.create_task(listen_to_redis(app))
4849

4950

50-
async def cleanup_background_tasks(app):
51+
async def cleanup_background_tasks(app: web.Application) -> None:
5152
print("cleanup background tasks...")
5253
app["redis_listener"].cancel()
5354
await app["redis_listener"]
5455

5556

56-
def init():
57+
def init() -> web.Application:
5758
app = web.Application()
5859
app["websockets"] = []
5960
app.router.add_get("/news", websocket_handler)

examples/cli_app.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,18 @@
1414
"""
1515

1616
from argparse import ArgumentParser
17+
from typing import Optional, Sequence
1718

1819
from aiohttp import web
1920

2021

21-
def display_message(req):
22+
async def display_message(req: web.Request) -> web.StreamResponse:
2223
args = req.app["args"]
2324
text = "\n".join([args.message] * args.repeat)
2425
return web.Response(text=text)
2526

2627

27-
def init(argv):
28+
def init(argv: Optional[Sequence[str]]) -> web.Application:
2829
arg_parser = ArgumentParser(
2930
prog="aiohttp.web ...", description="Application CLI", add_help=False
3031
)

examples/client_auth.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
import aiohttp
55

66

7-
async def fetch(session):
7+
async def fetch(session: aiohttp.ClientSession) -> None:
88
print("Query http://httpbin.org/basic-auth/andrew/password")
99
async with session.get("http://httpbin.org/basic-auth/andrew/password") as resp:
1010
print(resp.status)
1111
body = await resp.text()
1212
print(body)
1313

1414

15-
async def go():
15+
async def go() -> None:
1616
async with aiohttp.ClientSession(
1717
auth=aiohttp.BasicAuth("andrew", "password")
1818
) as session:

examples/client_json.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,15 @@
44
import aiohttp
55

66

7-
async def fetch(session):
7+
async def fetch(session: aiohttp.ClientSession):
88
print("Query http://httpbin.org/get")
99
async with session.get("http://httpbin.org/get") as resp:
1010
print(resp.status)
1111
data = await resp.json()
1212
print(data)
1313

1414

15-
async def go():
15+
async def go() -> None:
1616
async with aiohttp.ClientSession() as session:
1717
await fetch(session)
1818

examples/client_ws.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,11 @@
88
import aiohttp
99

1010

11-
async def start_client(loop, url):
11+
async def start_client(loop: asyncio.AbstractEventLoop, url: str) -> None:
1212
name = input("Please enter your name: ")
1313

1414
# input reader
15-
def stdin_callback():
15+
def stdin_callback() -> None:
1616
line = sys.stdin.buffer.readline().decode("utf-8")
1717
if not line:
1818
loop.stop()
@@ -21,7 +21,7 @@ def stdin_callback():
2121

2222
loop.add_reader(sys.stdin.fileno(), stdin_callback)
2323

24-
async def dispatch():
24+
async def dispatch() -> None:
2525
while True:
2626
msg = await ws.receive()
2727

@@ -30,7 +30,7 @@ async def dispatch():
3030
elif msg.type == aiohttp.WSMsgType.BINARY:
3131
print("Binary: ", msg.data)
3232
elif msg.type == aiohttp.WSMsgType.PING:
33-
ws.pong()
33+
await ws.pong()
3434
elif msg.type == aiohttp.WSMsgType.PONG:
3535
print("Pong received")
3636
else:

examples/curl.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66
import aiohttp
77

88

9-
async def curl(url):
9+
async def curl(url: str) -> None:
1010
async with aiohttp.ClientSession() as session:
1111
async with session.request("GET", url) as response:
1212
print(repr(response))

examples/fake_server.py

Lines changed: 23 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -3,22 +3,25 @@
33
import pathlib
44
import socket
55
import ssl
6+
from typing import Any, Dict, List, Union
67

7-
import aiohttp
8-
from aiohttp import web
9-
from aiohttp.resolver import DefaultResolver
10-
from aiohttp.test_utils import unused_port
8+
from aiohttp import ClientSession, TCPConnector, resolver, test_utils, web
119

1210

1311
class FakeResolver:
1412
_LOCAL_HOST = {0: "127.0.0.1", socket.AF_INET: "127.0.0.1", socket.AF_INET6: "::1"}
1513

16-
def __init__(self, fakes):
14+
def __init__(self, fakes: Dict[str, int]) -> None:
1715
"""fakes -- dns -> port dict"""
1816
self._fakes = fakes
19-
self._resolver = DefaultResolver()
20-
21-
async def resolve(self, host, port=0, family=socket.AF_INET):
17+
self._resolver = resolver.DefaultResolver()
18+
19+
async def resolve(
20+
self,
21+
host: str,
22+
port: int = 0,
23+
family: Union[socket.AddressFamily, int] = socket.AF_INET,
24+
) -> List[Dict[str, Any]]:
2225
fake_port = self._fakes.get(host)
2326
if fake_port is not None:
2427
return [
@@ -34,9 +37,12 @@ async def resolve(self, host, port=0, family=socket.AF_INET):
3437
else:
3538
return await self._resolver.resolve(host, port, family)
3639

40+
async def close(self) -> None:
41+
self._resolver.close()
42+
3743

3844
class FakeFacebook:
39-
def __init__(self):
45+
def __init__(self) -> None:
4046
self.app = web.Application()
4147
self.app.router.add_routes(
4248
[
@@ -51,21 +57,20 @@ def __init__(self):
5157
self.ssl_context = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
5258
self.ssl_context.load_cert_chain(str(ssl_cert), str(ssl_key))
5359

54-
async def start(self):
55-
port = unused_port()
56-
self.runner = web.AppRunner(self.app)
60+
async def start(self) -> Dict[str, int]:
61+
port = test_utils.unused_port()
5762
await self.runner.setup()
5863
site = web.TCPSite(self.runner, "127.0.0.1", port, ssl_context=self.ssl_context)
5964
await site.start()
6065
return {"graph.facebook.com": port}
6166

62-
async def stop(self):
67+
async def stop(self) -> None:
6368
await self.runner.cleanup()
6469

65-
async def on_me(self, request):
70+
async def on_me(self, request: web.Request) -> web.StreamResponse:
6671
return web.json_response({"name": "John Doe", "id": "12345678901234567"})
6772

68-
async def on_my_friends(self, request):
73+
async def on_my_friends(self, request: web.Request) -> web.StreamResponse:
6974
return web.json_response(
7075
{
7176
"data": [
@@ -88,15 +93,15 @@ async def on_my_friends(self, request):
8893
)
8994

9095

91-
async def main():
96+
async def main() -> None:
9297
token = "ER34gsSGGS34XCBKd7u"
9398

9499
fake_facebook = FakeFacebook()
95100
info = await fake_facebook.start()
96101
resolver = FakeResolver(info)
97-
connector = aiohttp.TCPConnector(resolver=resolver, ssl=False)
102+
connector = TCPConnector(resolver=resolver, ssl=False)
98103

99-
async with aiohttp.ClientSession(connector=connector) as session:
104+
async with ClientSession(connector=connector) as session:
100105
async with session.get(
101106
"https://graph.facebook.com/v2.7/me", params={"access_token": token}
102107
) as resp:

examples/lowlevel_srv.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,13 @@
11
import asyncio
22

3-
from aiohttp import web
3+
from aiohttp import web, web_request
44

55

6-
async def handler(request):
6+
async def handler(request: web_request.BaseRequest) -> web.StreamResponse:
77
return web.Response(text="OK")
88

99

10-
async def main(loop):
10+
async def main(loop: asyncio.AbstractEventLoop) -> None:
1111
server = web.Server(handler)
1212
await loop.create_server(server, "127.0.0.1", 8080)
1313
print("======= Serving on http://127.0.0.1:8080/ ======")

examples/server_simple.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,13 @@
22
from aiohttp import web
33

44

5-
async def handle(request):
5+
async def handle(request: web.Request) -> web.StreamResponse:
66
name = request.match_info.get("name", "Anonymous")
77
text = "Hello, " + name
88
return web.Response(text=text)
99

1010

11-
async def wshandle(request):
11+
async def wshandle(request: web.Request) -> web.StreamResponse:
1212
ws = web.WebSocketResponse()
1313
await ws.prepare(request)
1414

examples/web_classview.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,15 +2,14 @@
22
"""Example for aiohttp.web class based views
33
"""
44

5-
65
import functools
76
import json
87

98
from aiohttp import web
109

1110

1211
class MyView(web.View):
13-
async def get(self):
12+
async def get(self) -> web.StreamResponse:
1413
return web.json_response(
1514
{
1615
"method": self.request.method,
@@ -20,7 +19,7 @@ async def get(self):
2019
dumps=functools.partial(json.dumps, indent=4),
2120
)
2221

23-
async def post(self):
22+
async def post(self) -> web.StreamResponse:
2423
data = await self.request.post()
2524
return web.json_response(
2625
{
@@ -32,7 +31,7 @@ async def post(self):
3231
)
3332

3433

35-
async def index(request):
34+
async def index(request: web.Request) -> web.StreamResponse:
3635
txt = """
3736
<html>
3837
<head>
@@ -51,7 +50,7 @@ async def index(request):
5150
return web.Response(text=txt, content_type="text/html")
5251

5352

54-
def init():
53+
def init() -> web.Application:
5554
app = web.Application()
5655
app.router.add_get("/", index)
5756
app.router.add_get("/get", MyView)

0 commit comments

Comments
 (0)