Chapter 9. The Context Management Protocol: Hooking into Python’s with Statement
It’s time to take what you’ve just learned and put it to work.
Chapter 7 discussed using a relational database with Python, while Chapter 8 provided an introduction to using classes in your Python code. In this chapter, both of these techniques are combined to produce a context manager that lets us extend the with
statement to work with relational database systems. In this chapter, you’ll hook into the with
statement by creating a new class, which conforms to Python’s context management protocol.
What’s the Best Way to Share Our Webapp’s Database Code?
During Chapter 7 you created database code in your log_request
function that worked, but you had to pause to consider how best to share it. Recall the suggestions from the end of Chapter 7:
At the time, we proposed that each of these suggestions was valid, but believed Python programmers would be unlikely to embrace any of these proposed solutions on their own. We decided that a better strategy was to hook into the context management protocol using the with
statement, but in order to do that, you needed to learn a bit about classes. They were the subject of the last chapter. Now that you know how to create a class, it’s time to return to the task at hand: creating ...
Get Head First Python, 2nd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.