Quiz
- What is a 'Flask request' specifically? Is making a new database connection within each function enough to ensure no threading bugs?
A Flask request is an object that represents one HTTP request. The Flask infrastructure in a deployed app ensures that these are thread-specific, so that the "request" object which seems like it's a global variable is in fact thread-global, not process-global.
If you really want to know the underlying details, check out this Q&A with ChatGPT: Flask Request Implementation
No, making a database connection per request doesn't avoid all possible threading bugs. It only allows correct use of the MySQL
last_insert_id()function. If you used a global database connection, you might get the wrong answer. Imagine:- I start up a MySQL shell on my laptop.
- Abby comes up and inserts herself in the staff table. She then steps aside to check her phone.
- Betty comes up and inserts herself in the staff table.
- Betty selects
last_insert_id()and gets 71; She walks away. - Abby says "oh, I forgot to get my ID!". She returns and selects
last_insert_id()and gets 71;
- What are the performance implications of creating multiple connections?
Great question! MySQL is designed to handle multiple connections. Remember in the beginning of the course when we all were running the MySQL client (shell) at the same time? Those are multiple connections.
Also, last time, we learned about locks and transactions, whose purpose is to support concurrency.
As to performance, MySQL does very well. At the very lowest levels, the DMBS needs to have exclusive access to the data structure for a row or table, but that is kept small to maximize concurrency.
I asked ChatGPT about how does mysql perform on measure of concurrency
- can't think of any for now!
Great!