Detecting the n+1 queries problem in Python
Project description
nplusone is a library for detecting the n+1 queries problem in Python ORMs, including SQLAlchemy, Peewee, and the Django ORM.
The Problem
Many object-relational mapping (ORM) libraries default to lazy loading for relationships. This pattern can be efficient when related rows are rarely accessed, but quickly becomes inefficient as relationships are accessed more frequently. In these cases, loading related rows eagerly using a JOIN can be vastly more performant. Unfortunately, understanding when to use lazy versus eager loading can be challenging: you might not notice the problem until your app has slowed to a crawl.
nplusone is an ORM profiling tool to help diagnose and improve poor performance caused by inappropriate lazy loading. nplusone monitors applications using Django or SQLAlchemy and sends notifications when potentially expensive lazy loads are emitted. It can identify the offending relationship attribute and specific lines of code behind the problem, and recommend fixes for better performance.
nplusone also detects inappropriate eager loading for Flask-SQLAlchemy and the Django ORM, emitting a warning when related data are eagerly loaded but never accessed within the current request.
Installation
pip install -U nplusone
nplusone supports Python >= 2.7 or >= 3.3.
Usage
Note: nplusone should only be used for development and should not be deployed to production environments.
Django
Note: nplusone supports Django 1.7, 1.8, and 1.9.
Add nplusone to INSTALLED_APPS:
INSTALLED_APPS = ( ... 'nplusone.ext.django', )
Add NPlusOneMiddleware:
MIDDLEWARE_CLASSES = ( ... 'nplusone.ext.django.NPlusOneMiddleware', )
Optionally configure logging settings:
NPLUSONE_LOGGER = logging.getLogger('nplusone') NPLUSONE_LOG_LEVEL = logging.WARN
Configure logging handlers:
LOGGING = { 'version': 1, 'handlers': { 'console': { 'class': 'logging.StreamHandler', }, }, 'loggers': { 'nplusone': { 'handlers': ['console'], 'level': 'WARN', }, }, }
When your app loads data lazily, nplusone will emit a log message:
Potential n+1 query detected on `<model>.<field>`
Consider using select_related or prefetch_related in this case.
When your app eagerly loads related data without accessing it, nplusone will log a warning:
Potential unnecessary eager load detected on `<model>.<field>`
Flask-SQLAlchemy
Wrap application with NPlusOne:
from flask import Flask from nplusone.ext.flask_sqlalchemy import NPlusOne app = Flask(__name__) NPlusOne(app)
Optionally configure logging settings:
app = Flask(__name__) app.config['NPLUSONE_LOGGER'] = logging.getLogger('app.nplusone') app.config['NPLUSONE_LOG_LEVEL'] = logging.ERROR NPlusOne(app)
When your app loads data lazily, nplusone will emit a log message:
Potential n+1 query detected on `<model>.<field>`
Consider using subqueryload or joinedload in this case; see SQLAlchemy’s guide to relationship loading for complete documentation.
When your app eagerly loads related data without accessing it, nplusone will log a warning:
Potential unnecessary eager load detected on `<model>.<field>`
Customizing notifications
By default, nplusone logs all potentially unnecessary queries using a logger named “nplusone”. When the NPLUSONE_RAISE configuration option is set, nplusone will also raise an NPlusOneError. This can be used to force all automated tests involving unnecessary queries to fail.
# Django config NPLUSONE_RAISE = True # Flask config app.config['NPLUSONE_RAISE'] = True
The exception type can also be specified, if desired, using the NPLUSONE_ERROR option.
Ignoring Warnings
To suppress warnings thrown by intentional lazy loading, use the ignore context manager:
from nplusone.core import signals with signals.ignore(signals.lazy_load): # lazy-load rows # ...
License
MIT licensed. See the bundled LICENSE file for more details.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
File details
Details for the file nplusone-0.4.0.tar.gz
.
File metadata
- Download URL: nplusone-0.4.0.tar.gz
- Upload date:
- Size: 10.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | b293f68192dd6e65f41f0c138dd4236d3eff54f673bf1a0f9de944eb837ad3d9 |
|
MD5 | 6dab180bc1fb9c759a4122145ec1145a |
|
BLAKE2b-256 | 0da8e5dd62751a8ddb485b180186bfd31fbb48dd53d89c5745fefefd5d33cd43 |
File details
Details for the file nplusone-0.4.0-py2.py3-none-any.whl
.
File metadata
- Download URL: nplusone-0.4.0-py2.py3-none-any.whl
- Upload date:
- Size: 14.9 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
File hashes
Algorithm | Hash digest | |
---|---|---|
SHA256 | d71add646c56b98d35f1659568a6a4ac5b6858e6949f37d5186e9b9a240e778f |
|
MD5 | 2629718f239f2854d94e4df71d35bb0e |
|
BLAKE2b-256 | 1e32301dbc2dce31c3adb9c2a0b9b0c146e1a93b149ad36a90573db29fbfbdd4 |