Package: nplusone-TrialSpark
nplusone is a library for detecting the n+1 queries problem in Python ORMs, including SQLAlchemy, Peewee, and the Django ORM.The ProblemMany 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 aJOINcan 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.nplusoneis an ORM profiling tool to help diagnose and improve poor performance caused by inappropriate lazy loading.nplusonemonitors 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.nplusonealso 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.Installationpip install -U nplusonenplusone supports Python >= 2.7 or >= 3.3.UsageNote:nplusoneshould only be used for development and should not be deployed to production environments.DjangoNote:nplusonesupports Django >= 1.8.AddnplusonetoINSTALLED_APPS:INSTALLED_APPS = (
    ...
    'nplusone.ext.django',
)AddNPlusOneMiddleware:MIDDLEWARE = (
    'nplusone.ext.django.NPlusOneMiddleware',
    ...
)Optionally configure logging settings:NPLUSONE_LOGGER = logging.getLogger('nplusone')
NPLUSONE_LOG_LEVEL = logging.WARNConfigure logging handlers:LOGGING = {
    'version': 1,
    'handlers': {
        'console': {
            'class': 'logging.StreamHandler',
        },
    },
    'loggers': {
        'nplusone': {
            'handlers': ['console'],
            'level': 'WARN',
        },
    },
}When your app loads data lazily,nplusonewill emit a log message:Potential n+1 query detected on `<model>.<field>`Consider usingselect_relatedorprefetch_relatedin this case.When your app eagerly loads related data without accessing it,nplusonewill log a warning:Potential unnecessary eager load detected on `<model>.<field>`Flask-SQLAlchemyWrap application withNPlusOne: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,nplusonewill emit a log message:Potential n+1 query detected on `<model>.<field>`Consider usingsubqueryloadorjoinedloadin this case; see SQLAlchemy’s guide torelationship loadingfor complete documentation.When your app eagerly loads related data without accessing it,nplusonewill log a warning:Potential unnecessary eager load detected on `<model>.<field>`WSGIFor other frameworks that follow the WSGI specification, wrap your application withNPlusOneMiddleware. You must also import the relevantnplusoneextension for your ORM:import bottle
from nplusone.ext.wsgi import NPlusOneMiddleware
import nplusone.ext.sqlalchemy

app = NPlusOneMiddleware(bottle.app())GenericThe integrations above are coupled to the request-response cycle. To usenplusoneoutside the context of an HTTP request, use theProfilercontext manager: You must also import the relevantnplusoneextension for your ORM:from nplusone.core import profiler
import nplusone.ext.sqlalchemy

with profiler.Profiler():
    ...Customizing notificationsBy default,nplusonelogs all potentially unnecessary queries using a logger named “nplusone”. When theNPLUSONE_RAISEconfiguration option is set,nplusonewill also raise anNPlusOneError. 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'] = TrueThe exception type can also be specified, if desired, using theNPLUSONE_ERRORoption.Ignoring notificationsTo ignore notifications fromnplusoneglobally, configure the whitelist using theNPLUSONE_WHITELISToption:# 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'}
]You can whitelist models by exact name or byfnmatchpatterns:# Django config
NPLUSONE_WHITELIST = [
    {'model': 'myapp.*'}
]To suppress notifications locally, use theignorecontext manager:from nplusone.core import signals

with signals.ignore(signals.lazy_load):
    # lazy-load rows
    # ...LicenseMIT licensed. See the bundledLICENSEfile for more details.