Giter Club home page Giter Club logo

django-speedinfo's Introduction

django-speedinfo

Build Status Coverage Status

django-speedinfo is a live profiling tool for Django projects to find the most high loaded views for the next optimization. django-speedinfo counts number of calls, cache hits, SQL queries, measures average and total call time and more for each of your views. Detailed report and profiler controls are available in Django admin.

Speedinfo admin screenshot

Prerequisites

  • Python 2.7, 3.6+
  • Django 1.8+

Installation

pip install django-speedinfo

Upgrading from 1.x

Old profiling data will be unavailable after upgrading. Don't forget to export the data in advance.

  • Setup one of the storage backends as shown in the section 4 of Setup below.
  • SPEEDINFO_PROFILING_CONDITIONS is empty by default. If you use SPEEDINFO_EXCLUDE_URLS in your project you need to initialize the list of conditions explicitly: SPEEDINFO_PROFILING_CONDITIONS = ["speedinfo.conditions.exclude_urls.ExcludeURLCondition"]
  • SPEEDINFO_REPORT_COLUMNS and SPEEDINFO_REPORT_COLUMNS_FORMAT were removed, use SPEEDINFO_ADMIN_COLUMNS instead. Every entry in SPEEDINFO_ADMIN_COLUMNS list is a tuple (column name, value format, attribute name). See Customize admin columns for details. To add extra columns follow the instruction in the section Extra admin columns below.
  • speedinfo.settings module renamed to speedinfo.conf
  • Base condition class was renamed from Condition to AbstractCondition

Setup

  1. Add speedinfo to INSTALLED_APPS.
  2. Add speedinfo.middleware.ProfilerMiddleware to the end of MIDDLEWARE (or MIDDLEWARE_CLASSES for Django < 1.10) list, but before django.middleware.cache.FetchFromCacheMiddleware (if used):
    MIDDLEWARE = [
        ...,
        "speedinfo.middleware.ProfilerMiddleware",
        "django.middleware.cache.FetchFromCacheMiddleware",
    ]
    
  3. Setup any cache backend (except local-memory and dummy caching) using our proxy cache backend. django-speedinfo needs the cache to store profiler state between requests and to intercept calls to cache:
    CACHES = {
        "default": {
            "BACKEND": "speedinfo.backends.proxy_cache",
            "CACHE_BACKEND": "django.core.cache.backends.filebased.FileBasedCache",
            "LOCATION": "/var/tmp/django_cache",
        }
    }
    
  4. Setup storage for profiling data. django-speedinfo comes with two storages to choose from:
    • Database storage
      1. Add speedinfo.storage.database to INSTALLED_APPS.
      2. Add SPEEDINFO_STORAGE = "speedinfo.storage.database.storage.DatabaseStorage" to project settings.
      3. Run python manage.py migrate.
    • Cache storage
      1. Add SPEEDINFO_STORAGE = "speedinfo.storage.cache.storage.CacheStorage" to project settings.
      2. Optionally you may define a separate cache in CACHES to store profiling data. To use it in CacheStorage assign SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS to the appropriate cache alias. Example:
        CACHES = {
            "default": {
                "BACKEND": "speedinfo.backends.proxy_cache",
                "CACHE_BACKEND": "django.core.cache.backends.db.DatabaseCache",
                "LOCATION": "cache_table",
            },
            "speedinfo-storage": {
                "BACKEND": "django.core.cache.backends.memcached.MemcachedCache",
                "LOCATION": "127.0.0.1:11211",
            },
        })
        
        SPEEDINFO_CACHE_STORAGE_CACHE_ALIAS = "speedinfo-storage"
        
  5. Run python manage.py collectstatic.

Usage

Open Views profiler in Django admin. Click the Turn on / Turn off button to control profiler state. Press Reset button to delete all profiling data.

Advanced features

Custom page caching

django-speedinfo automatically detects when Django use per-site caching via UpdateCacheMiddleware and FetchFromCacheMiddleware middlewares or per-view caching via cache_page decorator and counts cache hit when retrieving pages from the cache.

If you implement your own caching logic and want to mark the view response as obtained from the cache, add specified attribute to the HttpResponse object as shown below:

from django.views import View
from from speedinfo.conf import speedinfo_settings

class CachedView(View):
    def get(self, request, *args, **kwargs):
        # ...
        # Assume that `response` was taken from the cache
        setattr(response, speedinfo_settings.SPEEDINFO_CACHED_RESPONSE_ATTR_NAME, True)
        return response

The default value of SPEEDINFO_CACHED_RESPONSE_ATTR_NAME is _is_cached. But you can override it if the attribute name is conflicts with your application logic.

Customize admin columns

SPEEDINFO_ADMIN_COLUMNS allows to control visibility and appearance of Django admin profiler columns. Every entry in the SPEEDINFO_ADMIN_COLUMNS list is a tuple of (column name, value format, ViewProfiler attribute name). Default value:

SPEEDINFO_ADMIN_COLUMNS = (
    ("View name", "{}", "view_name"),
    ("HTTP method", "{}", "method"),
    ("Anonymous calls", "{:.1f}%", "anon_calls_ratio"),
    ("Cache hits", "{:.1f}%", "cache_hits_ratio"),
    ("SQL queries per call", "{}", "sql_count_per_call"),
    ("SQL time", "{:.1f}%", "sql_time_ratio"),
    ("Total calls", "{}", "total_calls"),
    ("Time per call", "{:.8f}", "time_per_call"),
    ("Total time", "{:.4f}", "total_time"),
)

Extra admin columns

To add additional data to a storage and columns to admin follow the instruction:

  1. Create custom storage backend which will hold or calculate additional fields.
  2. Implement storage fetch_all() method that will return the list of the ViewProfiler instances initialized with the extra fields. Example:
    def fetch_all(self, ordering=None):
        ...
        return [
            ViewProfiler(view_name="...", method="...", ..., extra_field="...")
            ...
        ]
    
  3. Implement sorting by extra fields in fetch_all() method.
  4. Add extra fields to SPEEDINFO_ADMIN_COLUMNS as described in the section Customize admin columns.

Profiling conditions

SPEEDINFO_PROFILING_CONDITIONS allows to declare a list of condition classes to filter profiling views by some rules. By default SPEEDINFO_PROFILING_CONDITIONS is empty. django-speedinfo comes with one build-in condition - ExcludeURLCondition. It allows to exclude some urls from profiling by adding them to the SPEEDINFO_EXCLUDE_URLS list. Each entry in SPEEDINFO_EXCLUDE_URLS is a regex compatible expression to test requested url. Usage example:

SPEEDINFO_PROFILING_CONDITIONS = [
    "speedinfo.conditions.exclude_urls.ExcludeURLCondition",
]

SPEEDINFO_EXCLUDE_URLS = [
    r"/admin/",
    r"/news/$",
    r"/movie/\d+/$",
]

To define your own condition class, you must inherit from the base class speedinfo.conditions.base.AbstractCondition and implement all abstract methods. See ExcludeURLCondition source code for implementation example. Then add full path to your class to SPEEDINFO_PROFILING_CONDITIONS list as shown above. Conditions in mentioned list are executed in a top-down order. The first condition returning False interrupts the further check.

Custom storage backend

django-speedinfo comes with DatabaseStorage and CacheStorage. But you may want to write your own storage (e.g. for MongoDB, Redis or even file-based). First create the storage class based on speedinfo.storage.base.AbstractStorage and implement all abstract methods. See speedinfo.storage.cache.storage and speedinfo.storage.database.storage as an examples. Then add path to your custom storage class to the project settings SPEEDINFO_STORAGE = "path.to.module.CustomStorage". Use our tests to make sure that everything works as intended (you need to clone repository to get access to the tests package):

from django.test import TestCase, override_settings
from tests.test_storage import StorageTestCase

@override_settings(
    SPEEDINFO_STORAGE="path.to.module.CustomStorage",
    SPEEDINFO_TESTS=True,
)
class CustomStorageTestCase(StorageTestCase, TestCase):
    pass

Notice

The number of SQL queries measured by django-speedinfo may differ from the values of django-debug-toolbar for the same view. It happens because django-speedinfo shows the average number of SQL queries for each view. Also profiler doesn't take into account SQL queries made in the preceding middlewares.

django-speedinfo's People

Contributors

catcombo avatar igorcode avatar victorfabref avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar

django-speedinfo's Issues

'bool' object is not callable in Django 2.0.2

Internal Server Error: /admin/
Traceback (most recent call last):
File "/Users/juli/dev/leansew/env/lib/python3.6/site-packages/django/core/handlers/exception.py", line 35, in inner
response = get_response(request)
File "/Users/juli/dev/leansew/env/lib/python3.6/site-packages/speedinfo/middleware.py", line 112, in call
return self.process_response(request, response)
File "/Users/juli/dev/leansew/env/lib/python3.6/site-packages/speedinfo/middleware.py", line 90, in process_response
is_anon_call = request.user.is_anonymous()
TypeError: 'bool' object is not callable

Admin view: sorting on all columns

While not (easily) directly supported in the DB, ordering of calculated fields could be also provided.

This would allow to sort on e.g. "SQL time" also.

Do you think this is useful?

Adding custom fields in admin panel?

What options are available for users if they have to add custom fields in the admin? For example, the percentile of total time.

One option is users can register the model by themselves. speedinfo has to ignore the registration if the model is already registered.

Use url path instead of view name?

@catcombo I have been testing out speedinfo with several projects and it is working well. Thank you for your efforts.

Any reasons to use view_name instead of URL paths to collect statistics?

One issue with view names is, resolve can't give full function name.
For example if there is a function at core.viewsets.BookViewSet.dashboard, view name will be just core.viewsets.BookViewSet. All the methods in the view set will have same view name. This results in combining stats of all views inside a model view set.

Another issue with view names is, when profiling views in admin, it will always show same view names like django.contrib.admin.options, django.contrib.admin.options.changelist_view
irrespective of the model a user is visiting.

I have made a temporary fix to test it out 7bfc2c3

Setup issues

I have installed speedinfo on a test project. Initially it was throwing an error

Traceback (most recent call last):
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 112, in inner_run
    autoreload.raise_last_exception()
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/utils/autoreload.py", line 248, in raise_last_exception
    raise _exception[1]
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/core/management/__init__.py", line 327, in execute
    autoreload.check_errors(django.setup)()
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper
    fn(*args, **kwargs)
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/__init__.py", line 24, in setup
    apps.populate(settings.INSTALLED_APPS)
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/apps/registry.py", line 120, in populate
    app_config.ready()
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/contrib/admin/apps.py", line 23, in ready
    self.module.autodiscover()
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/contrib/admin/__init__.py", line 26, in autodiscover
    autodiscover_modules('admin', register_to=site)
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/utils/module_loading.py", line 47, in autodiscover_modules
    import_module('%s.%s' % (app_config.name, module_to_search))
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/importlib/__init__.py", line 127, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1006, in _gcd_import
  File "<frozen importlib._bootstrap>", line 983, in _find_and_load
  File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 677, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 728, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/speedinfo/admin.py", line 132, in <module>
    admin.site.register(ViewProfiler, ViewProfilerAdmin)
  File "/Users/curatech/.virtualenvs/library/lib/python3.7/site-packages/django/contrib/admin/sites.py", line 109, in register
    raise AlreadyRegistered('The model %s is already registered' % model.__name__)
django.contrib.admin.sites.AlreadyRegistered: The model ViewProfiler is already registered

To prevent this, I have unregistered model.

from speedinfo.models import ViewProfiler

admin.site.unregister(ViewProfiler)

After this, setup was completed. I have browsed several pages on the app with toggle on and off but nothing is showing up in admin panel of speedinfo. Should I add any additional code to track the views?

Screen Shot 2019-06-12 at 10 13 47 PM

Store Content-Type?

Especially with DRF it is relevant if a request's response is of Content-Type text/html, text/json etc.

I think it would be nice to store this information (without the charset, i.e. everything up until ";").

What do you think?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.