Debian Codegraph @

docs/tutorials/asyncio.rst

raw
1 .. _asyncio:
2
3 Introduction to asyncio
4 =======================
5
6 Asyncio is the part of the Python standard library that provides an
7 event loop with IO (input/output) operations. It exists to allow
8 concurrent programming in Python, whereby the event loop switches to
9 another task whilst the previous task waits on IO. This concurrency
10 allows for greater CPU utilisation and hence greater throughput
11 performance.
12
13 The easiest way to understand this is to consider something concrete,
14 namely a demonstrative simulation In the following we fetch a url with
15 a simulated IO delay,
16
17 .. code-block:: python
18
19 import asyncio
20
21
22 async def simulated_fetch(url, delay):
23 await asyncio.sleep(delay)
24 print(f"Fetched {url} after {delay}")
25 return f"<html>{url}"
26
27
28 def main():
29 loop = asyncio.get_event_loop()
30 results = loop.run_until_complete(asyncio.gather(
31 simulated_fetch('http://google.com', 2),
32 simulated_fetch('http://bbc.co.uk', 1),
33 ))
34 print(results)
35
36 you should see the following output,
37
38 >>> Fetched http://bbc.co.uk after 1
39 >>> Fetched http://google.com after 2
40 >>> ['<html>http://google.com', '<html>http://bbc.co.uk']
41
42 which indicates that despite calling the ``google.com`` fetch first,
43 the ``bbc.co.uk`` actually completed first i.e. the code ran
44 concurrently. Additionally the code runs in a little over 2 seconds
45 rather than over 3 as expected with synchronous code.
46
47 Relevance to web servers
48 ------------------------
49
50 Web servers by definition do IO, in that they receive and respond to
51 requests from the network. This means that asyncio is a very good fit
52 even if the code within the framework does no IO itself. Yet in
53 practice IO is present, for example when loading a template from a
54 file, or contacting a database or another server.
55
56 Common pitfalls
57 ---------------
58
59 It is very easy to await the wrong thing, for example,
60
61 .. code-block:: python
62
63 await awaitable.attribute
64
65 will not await the ``awaitable`` object as you might expect, but
66 rather attempt to resolve the attribute and then await it. This is
67 quite commonly seen as,
68
69 .. code-block:: python
70
71 await request.form.get('key')
72
73 which fails with an error that the coroutine wrapper has no get
74 attribute. To work around this simply use brackets to indicate what
75 must be awaited first,
76
77 .. code-block:: python
78
79 (await awaitable).attribute
80 (await request.form).get('key')