This is a pre-production deployment of Warehouse. Changes made here affect the production instance of PyPI (pypi.python.org).
Help us improve Python packaging - Donate today!

Detecting the n+1 queries problem in Python

Project Description
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

Description: ========
nplusone
========

.. image:: https://img.shields.io/pypi/v/nplusone.svg
:target: http://badge.fury.io/py/nplusone
:alt: Latest version

.. image:: https://img.shields.io/travis/jmcarp/nplusone/master.svg
:target: https://travis-ci.org/jmcarp/nplusone
:alt: Travis-CI

.. image:: https://img.shields.io/codecov/c/github/jmcarp/nplusone/master.svg
:target: https://codecov.io/github/jmcarp/nplusone
:alt: Code coverage

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.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 <https://docs.djangoproject.com/en/1.8/ref/models/querysets/#select-related>`_ or `prefetch_related <https://docs.djangoproject.com/en/1.8/ref/models/querysets/#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 <http://docs.sqlalchemy.org/en/latest/orm/loading_relationships.html>`_ 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 notifications
**********************

To ignore notifications from ``nplusone`` globally, configure the whitelist using the `NPLUSONE_WHITELIST` option: ::

# Django config
NPLUSONE_WHITELIST = [
{'label': 'n_plus_one', 'model': 'myapp.MyModel'},
]

# Flask-SQLAlchemy config
app.config['NPLUSONE_WHITELIST'] = [
{'label': 'unused_eager_load', 'model': 'MyModel', 'field': 'my_field'}
]

To suppress notifications locally, 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 <https://github.com/jmcarp/nplusone/blob/master/LICENSE>`_ file for more details.

Keywords: nplusone
Platform: UNKNOWN
Classifier: Development Status :: 2 - Pre-Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Natural Language :: English
Classifier: Programming Language :: Python :: 2
Classifier: Programming Language :: Python :: 2.7
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.3
Classifier: Programming Language :: Python :: 3.4
Release History

Release History

This version
History Node

0.8.0

History Node

0.7.3

History Node

0.7.2

History Node

0.7.1

History Node

0.7.0

History Node

0.6.1

History Node

0.6.0

History Node

0.5.0

History Node

0.4.0

History Node

0.3.0

History Node

0.2.1

History Node

0.2.0

History Node

0.1.0

Download Files

Download Files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

File Name & Checksum SHA256 Checksum Help Version File Type Upload Date
nplusone-0.8.0-py2.py3-none-any.whl (18.1 kB) Copy SHA256 Checksum SHA256 py2.py3 Wheel Apr 10, 2017
nplusone-0.8.0.tar.gz (12.9 kB) Copy SHA256 Checksum SHA256 Source Apr 10, 2017

Supported By

WebFaction WebFaction Technical Writing Elastic Elastic Search Pingdom Pingdom Monitoring Dyn Dyn DNS Sentry Sentry Error Logging CloudAMQP CloudAMQP RabbitMQ Heroku Heroku PaaS Kabu Creative Kabu Creative UX & Design Fastly Fastly CDN DigiCert DigiCert EV Certificate Rackspace Rackspace Cloud Servers DreamHost DreamHost Log Hosting