Connection pooling helps Flask apps by:
Think about what happens when you open and close database connections repeatedly.
Connection pooling keeps a set of open connections ready to use, so the app doesn't spend time opening new ones each request.
Consider a Flask app using a connection pool with a max size of 5. What occurs when 6 requests try to get a connection simultaneously?
Think about how pools manage limited resources.
When the pool is full, new requests wait for a connection to be returned before proceeding.
Choose the code that properly configures a connection pool with max 10 connections using SQLAlchemy in Flask.
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' # Configure pool here db = SQLAlchemy(app)
Look for the official SQLAlchemy pool size config key.
The correct config key to set the pool size is SQLALCHEMY_POOL_SIZE.
Given this Flask app snippet, why might a 'TimeoutError' occur?
from flask import Flask from flask_sqlalchemy import SQLAlchemy app = Flask(__name__) app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///test.db' app.config['SQLALCHEMY_POOL_SIZE'] = 2 app.config['SQLALCHEMY_POOL_TIMEOUT'] = 1 db = SQLAlchemy(app) @app.route('/') def index(): conn1 = db.engine.connect() conn2 = db.engine.connect() conn3 = db.engine.connect() # This line causes TimeoutError return 'Hello'
Check the pool size and how many connections are requested.
With pool size 2, the third connection waits but times out after 1 second because no connection is free.
Assuming a Flask app with SQLAlchemy connection pool size 3, what is the number of active connections after these steps?
- Request 1 opens a connection and holds it.
- Request 2 opens a connection and holds it.
- Request 3 opens a connection and holds it.
- Request 4 tries to open a connection but waits.
- Request 1 releases its connection.
- Request 4 acquires the released connection.
Remember the pool size limits simultaneous active connections.
The pool size is 3, so only 3 connections can be active at once. Request 4 waits until one is released, then uses it, keeping active connections at 3.