Python Concurrency with asyncio....1
contents....7
preface....13
acknowledgments....15
about this book....16
Who should read this book?....16
How this book is organized: A road map....17
About the code....18
liveBook discussion forum....18
about the author....19
about the cover illustration....20
1 Getting to know asyncio....21
1.1 What is asyncio?....22
1.2 What is I/O-bound and what is CPU-bound?....23
1.3 Understanding concurrency, parallelism, and multitasking....24
1.3.1 Concurrency....24
1.3.2 Parallelism....25
1.3.3 The difference between concurrency and parallelism....26
1.3.4 What is multitasking?....27
1.3.5 The benefits of cooperative multitasking....27
1.4 Understanding processes, threads, multithreading, and multiprocessing....28
1.4.1 Process....28
1.4.2 Thread....28
1.5 Understanding the global interpreter lock....32
1.5.1 Is the GIL ever released?....35
1.5.2 asyncio and the GIL....37
1.6 How single-threaded concurrency works....37
1.6.1 What is a socket?....37
1.7 How an event loop works....40
Summary....42
2 asyncio basics....43
2.1 Introducing coroutines....44
2.1.1 Creating coroutines with the async keyword....44
2.1.2 Pausing execution with the await keyword....46
2.2 Introducing long-running coroutines with sleep....47
2.3 Running concurrently with tasks....50
2.3.1 The basics of creating tasks....50
2.3.2 Running multiple tasks concurrently....51
2.4 Canceling tasks and setting timeouts....53
2.4.1 Canceling tasks....54
2.4.2 Setting a timeout and canceling with wait_for....55
2.5 Tasks, coroutines, futures, and awaitables....57
2.5.1 Introducing futures....57
2.5.2 The relationship between futures, tasks, and coroutines....59
2.6 Measuring coroutine execution time with decorators....60
2.7 The pitfalls of coroutines and tasks....62
2.7.1 Running CPU-bound code....62
2.7.2 Running blocking APIs....64
2.8 Accessing and manually managing the event loop....65
2.8.1 Creating an event loop manually....66
2.8.2 Accessing the event loop....66
2.9 Using debug mode....67
2.9.1 Using asyncio.run....67
2.9.2 Using command-line arguments....67
2.9.3 Using environment variables....68
Summary....69
3 A first asyncio application....70
3.1 Working with blocking sockets....71
3.2 Connecting to a server with Telnet....73
3.2.1 Reading and writing data to and from a socket....74
3.2.2 Allowing multiple connections and the dangers of blocking....76
3.3 Working with non-blocking sockets....77
3.4 Using the selectors module to build a socket event loop....81
3.5 An echo server on the asyncio event loop....84
3.5.1 Event loop coroutines for sockets....84
3.5.2 Designing an asyncio echo server....85
3.5.3 Handling errors in tasks....87
3.6 Shutting down gracefully....89
3.6.1 Listening for signals....89
3.6.2 Waiting for pending tasks to finish....90
Summary....94
4 Concurrent web requests....95
4.1 Introducing aiohttp....96
4.2 Asynchronous context managers....97
4.2.1 Making a web request with aiohttp....99
4.2.2 Setting timeouts with aiohttp....101
4.3 Running tasks concurrently, revisited....102
4.4 Running requests concurrently with gather....104
4.4.1 Handling exceptions with gather....106
4.5 Processing requests as they complete....108
4.5.1 Timeouts with as_completed....110
4.6 Finer-grained control with wait....112
4.6.1 Waiting for all tasks to complete....112
4.6.2 Watching for exceptions....114
4.6.3 Processing results as they complete....116
4.6.4 Handling timeouts....119
4.6.5 Why wrap everything in a task?....120
Summary....121
5 Non-blocking database drivers....122
5.1 Introducing asyncpg....123
5.2 Connecting to a Postgres database....123
5.3 Defining a database schema....124
5.4 Executing queries with asyncpg....127
5.5 Executing queries concurrently with connection pools....129
5.5.1 Inserting random SKUs into the product database....130
5.5.2 Creating a connection pool to run queries concurrently....133
5.6 Managing transactions with asyncpg....138
5.6.1 Nested transactions....139
5.6.2 Manually managing transactions....140
5.7 Asynchronous generators and streaming result sets....142
5.7.1 Introducing asynchronous generators....143
5.7.2 Using asynchronous generators with a streaming cursor....144
Summary....147
6 Handling CPU-bound work....148
6.1 Introducing the multiprocessing library....149
6.2 Using process pools....151
6.2.1 Using asynchronous results....152
6.3 Using process pool executors with asyncio....153
6.3.1 Introducing process pool executors....153
6.3.2 Process pool executors with the asyncio event loop....154
6.4 Solving a problem with MapReduce using asyncio....156
6.4.1 A simple MapReduce example....157
6.4.2 The Google Books Ngram dataset....159
6.4.3 Mapping and reducing with asyncio....160
6.5 Shared data and locks....165
6.5.1 Sharing data and race conditions....166
6.5.2 Synchronizing with locks....169
6.5.3 Sharing data with process pools....171
6.6 Multiple processes, multiple event loops....174
Summary....178
7 Handling blocking work with threads....179
7.1 Introducing the threading module....180
7.2 Using threads with asyncio....184
7.2.1 Introducing the requests library....184
7.2.2 Introducing thread pool executors....185
7.2.3 Thread pool executors with asyncio....187
7.2.4 Default executors....188
7.3 Locks, shared data, and deadlocks....189
7.3.1 Reentrant locks....191
7.3.2 Deadlocks....193
7.4 Event loops in separate threads....195
7.4.1 Introducing Tkinter....196
7.4.2 Building a responsive UI with asyncio and threads....198
7.5 Using threads for CPU-bound work....205
7.5.1 Multithreading with hashlib....205
7.5.2 Multithreading with NumPy....208
Summary....210
8 Streams....211
8.1 Introducing streams....212
8.2 Transports and protocols....212
8.3 Stream readers and stream writers....216
8.4 Non-blocking command-line input....218
8.4.1 Terminal raw mode and the read coroutine....222
8.5 Creating servers....229
8.6 Creating a chat server and client....231
Summary....236
9 Web applications....237
9.1 Creating a REST API with aiohttp....238
9.1.1 What is REST?....238
9.1.2 aiohttp server basics....239
9.1.3 Connecting to a database and returning results....240
9.1.4 Comparing aiohttp with Flask....246
9.2 The asynchronous server gateway interface....248
9.2.1 How does ASGI compare to WSGI?....248
9.3 ASGI with Starlette....250
9.3.1 A REST endpoint with Starlette....250
9.3.2 WebSockets with Starlette....251
9.4 Django asynchronous views....255
9.4.1 Running blocking work in an asynchronous view....260
9.4.2 Using async code in synchronous views....262
Summary....263
10 Microservices....264
10.1 Why microservices?....265
10.1.1 Complexity of code....265
10.1.2 Scalability....266
10.1.3 Team and stack independence....266
10.1.4 How can asyncio help?....266
10.2 Introducing the backend-for-frontend pattern....266
10.3 Implementing the product listing API....268
10.3.1 User favorite service....268
10.3.2 Implementing the base services....269
10.3.3 Implementing the backend-for-frontend service....273
10.3.4 Retrying failed requests....278
10.3.5 The circuit breaker pattern....281
Summary....285
11 Synchronization....287
11.1 Understanding single-threaded concurrency bugs....288
11.2 Locks....292
11.3 Limiting concurrency with semaphores....296
11.3.1 Bounded semaphores....298
11.4 Notifying tasks with events....300
11.5 Conditions....305
Summary....309
12 Asynchronous queues....310
12.1 Asynchronous queue basics....311
12.1.1 Queues in web applications....317
12.1.2 A web crawler queue....320
12.2 Priority queues....323
12.3 LIFO queues....329
Summary....331
13 Managing subprocesses....332
13.1 Creating a subprocess....333
13.1.1 Controlling standard output....335
13.1.2 Running subprocesses concurrently....338
13.2 Communicating with subprocesses....342
Summary....345
14 Advanced asyncio....347
14.1 APIs with coroutines and functions....348
14.2 Context variables....350
14.3 Forcing an event loop iteration....351
14.4 Using different event loop implementations....353
14.5 Creating a custom event loop....354
14.5.1 Coroutines and generators....355
14.5.2 Generator-based coroutines are deprecated....355
14.5.3 Custom awaitables....357
14.5.4 Using sockets with futures....360
14.5.5 A task implementation....362
14.5.6 Implementing an event loop....363
14.5.7 Implementing a server with a custom event loop....366
Summary....368
index....369
A....369
B....370
C....370
D....371
E....372
F....372
G....372
H....372
I....372
J....373
K....373
L....373
M....373
N....373
O....373
P....373
Q....374
R....374
S....374
T....375
U....375
V....376
W....376
Learn how to speed up slow Python code with concurrent programming and the cutting-edge asyncio library.
Python is flexible, versatile, and easy to learn. It can also be very slow compared to lower-level languages. Python Concurrency with asyncio teaches you how to boost Python's performance by applying a variety of concurrency techniques. You'll learn how the complex-but-powerful asyncio library can achieve concurrency with just a single thread and use asyncio's APIs to run multiple web requests and database queries simultaneously. The book covers using asyncio with the entire Python concurrency landscape, including multiprocessing and multithreading.
It’s easy to overload standard Python and watch your programs slow to a crawl. Th e asyncio library was built to solve these problems by making it easy to divide and schedule tasks. It seamlessly handles multiple operations concurrently, leading to apps that are lightning fast and scalable.
Python Concurrency with asyncio introduces asynchronous, parallel, and concurrent programming through hands-on Python examples. Hard-to-grok concurrency topics are broken down into simple flowcharts that make it easy to see how your tasks are running. You’ll learn how to overcome the limitations of Python using asyncio to speed up slow web servers and microservices. You’ll even combine asyncio with traditional multiprocessing techniques for huge improvements to performance.
For intermediate Python programmers. No previous experience of concurrency required.