Django does not pool its SQL connections. Every single web request is served with one new connection to the DBMS. If the web server and DB server are far apart, the cost of establishing new connection could be expensive.
Fortunately, it is easy to take advantage of SQL Alchemy's excellent pooling support in Django. What one needs to do is simply to call sqlalchemy.pool.manage
on the Database
name in the Django DB backend base
module.
For example, the MySQL backend could be made to use connection pooling with these three lines:
from django.db.backends.mysql import base
from sqlalchemy import pool
base.Database = pool.manage(base.Database)
Extra parameters can be passed to manage to tune the pool.
This monkey patching should (or rather must) be done before any call to Django ORM. If you, for instance, use gunicorn_django
to serve your application, you can place those lines in its configuration file. Alternatively, you can also stash them in your application's settings.py
file.
No comments:
Post a Comment