• Stars
    star
    4,380
  • Rank 9,801 (Top 0.2 %)
  • Language
    Python
  • License
    MIT License
  • Created over 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Silky smooth profiling for Django

Silk

GitHub Actions GitHub Actions PyPI Download PyPI Python Versions Supported Django versions Jazzband

Silk is a live profiling and inspection tool for the Django framework. Silk intercepts and stores HTTP requests and database queries before presenting them in a user interface for further inspection:

Contents

Requirements

Silk has been tested with:

  • Django: 3.2, 4.0, 4.1
  • Python: 3.7, 3.8, 3.9, 3.10, 3.11

Installation

Via pip into a virtualenv:

pip install django-silk

In settings.py add the following:

MIDDLEWARE = [
    ...
    'silk.middleware.SilkyMiddleware',
    ...
]

INSTALLED_APPS = (
    ...
    'silk'
)

Note: The middleware placement is sensitive. If the middleware before silk.middleware.SilkyMiddleware returns from process_request then SilkyMiddleware will never get the chance to execute. Therefore you must ensure that any middleware placed before never returns anything from process_request. See the django docs for more information on this.

Note: If you are using django.middleware.gzip.GZipMiddleware, place that before silk.middleware.SilkyMiddleware, otherwise you will get an encoding error.

If you want to use custom middleware, for example you developed the subclass of silk.middleware.SilkyMiddleware, so you can use this combination of settings:

# Specify the path where is the custom middleware placed
SILKY_MIDDLEWARE_CLASS = 'path.to.your.middleware.MyCustomSilkyMiddleware'

# Use this variable in list of middleware
MIDDLEWARE = [
    ...
    SILKY_MIDDLEWARE_CLASS,
    ...
]

To enable access to the user interface add the following to your urls.py:

urlpatterns += [path('silk/', include('silk.urls', namespace='silk'))]

before running migrate:

python manage.py migrate

python manage.py collectstatic

Silk will automatically begin interception of requests and you can proceed to add profiling if required. The UI can be reached at /silk/

Alternative Installation

Via github tags:

pip install https://github.com/jazzband/silk/archive/<version>.tar.gz

You can install from master using the following, but please be aware that the version in master may not be working for all versions specified in requirements

pip install -e git+https://github.com/jazzband/django-silk.git#egg=django-silk

Features

Silk primarily consists of:

  • Middleware for intercepting Requests/Responses
  • A wrapper around SQL execution for profiling of database queries
  • A context manager/decorator for profiling blocks of code and functions either manually or dynamically.
  • A user interface for inspection and visualisation of the above.

Request Inspection

The Silk middleware intercepts and stores requests and responses in the configured database. These requests can then be filtered and inspecting using Silk's UI through the request overview:

It records things like:

  • Time taken
  • Num. queries
  • Time spent on queries
  • Request/Response headers
  • Request/Response bodies

and so on.

Further details on each request are also available by clicking the relevant request:

SQL Inspection

Silk also intercepts SQL queries that are generated by each request. We can get a summary on things like the tables involved, number of joins and execution time (the table can be sorted by clicking on a column header):

Before diving into the stack trace to figure out where this request is coming from:

Profiling

Turn on the SILKY_PYTHON_PROFILER setting to use Python's built-in cProfile profiler. Each request will be separately profiled and the profiler's output will be available on the request's Profiling page in the Silk UI.

SILKY_PYTHON_PROFILER = True

If you would like to also generate a binary .prof file set the following:

SILKY_PYTHON_PROFILER_BINARY = True

When enabled, a graph visualisation generated using gprof2dot and viz.js is shown in the profile detail page:

A custom storage class can be used for the saved generated binary .prof files:

SILKY_STORAGE_CLASS = 'path.to.StorageClass'

The default storage class is silk.storage.ProfilerResultStorage, and when using that you can specify a path of your choosing. You must ensure the specified directory exists.

# If this is not set, MEDIA_ROOT will be used.
SILKY_PYTHON_PROFILER_RESULT_PATH = '/path/to/profiles/'

A download button will become available with a binary .prof file for every request. This file can be used for further analysis using snakeviz or other cProfile tools

To retrieve which endpoint generates a specific profile file it is possible to add a stub of the request path in the file name with the following:

SILKY_PYTHON_PROFILER_EXTENDED_FILE_NAME = True

Silk can also be used to profile specific blocks of code/functions. It provides a decorator and a context manager for this purpose.

For example:

from silk.profiling.profiler import silk_profile


@silk_profile(name='View Blog Post')
def post(request, post_id):
    p = Post.objects.get(pk=post_id)
    return render(request, 'post.html', {
        'post': p
    })

Whenever a blog post is viewed we get an entry within the Silk UI:

Silk profiling not only provides execution time, but also collects SQL queries executed within the block in the same fashion as with requests:

Decorator

The silk decorator can be applied to both functions and methods

from silk.profiling.profiler import silk_profile


# Profile a view function
@silk_profile(name='View Blog Post')
def post(request, post_id):
    p = Post.objects.get(pk=post_id)
    return render(request, 'post.html', {
        'post': p
    })


# Profile a method in a view class
class MyView(View):
    @silk_profile(name='View Blog Post')
    def get(self, request):
        p = Post.objects.get(pk=post_id)
        return render(request, 'post.html', {
            'post': p
        })

Context Manager

Using a context manager means we can add additional context to the name which can be useful for narrowing down slowness to particular database records.

def post(request, post_id):
    with silk_profile(name='View Blog Post #%d' % self.pk):
        p = Post.objects.get(pk=post_id)
        return render(request, 'post.html', {
            'post': p
        })

Dynamic Profiling

One of Silk's more interesting features is dynamic profiling. If for example we wanted to profile a function in a dependency to which we only have read-only access (e.g. system python libraries owned by root) we can add the following to settings.py to apply a decorator at runtime:

SILKY_DYNAMIC_PROFILING = [{
    'module': 'path.to.module',
    'function': 'MyClass.bar'
}]

which is roughly equivalent to:

class MyClass:
    @silk_profile()
    def bar(self):
        pass

The below summarizes the possibilities:

"""
Dynamic function decorator
"""

SILKY_DYNAMIC_PROFILING = [{
    'module': 'path.to.module',
    'function': 'foo'
}]

# ... is roughly equivalent to
@silk_profile()
def foo():
    pass

"""
Dynamic method decorator
"""

SILKY_DYNAMIC_PROFILING = [{
    'module': 'path.to.module',
    'function': 'MyClass.bar'
}]

# ... is roughly equivalent to
class MyClass:

    @silk_profile()
    def bar(self):
        pass

"""
Dynamic code block profiling
"""

SILKY_DYNAMIC_PROFILING = [{
    'module': 'path.to.module',
    'function': 'foo',
    # Line numbers are relative to the function as opposed to the file in which it resides
    'start_line': 1,
    'end_line': 2,
    'name': 'Slow Foo'
}]

# ... is roughly equivalent to
def foo():
    with silk_profile(name='Slow Foo'):
        print (1)
        print (2)
    print(3)
    print(4)

Note that dynamic profiling behaves in a similar fashion to that of the python mock framework in that we modify the function in-place e.g:

""" my.module """
from another.module import foo

# ...do some stuff
foo()
# ...do some other stuff

,we would profile foo by dynamically decorating my.module.foo as opposed to another.module.foo:

SILKY_DYNAMIC_PROFILING = [{
    'module': 'my.module',
    'function': 'foo'
}]

If we were to apply the dynamic profile to the functions source module another.module.foo after it has already been imported, no profiling would be triggered.

Custom Logic for Profiling

Sometimes you may want to dynamically control when the profiler runs. You can write your own logic for when to enable the profiler. To do this add the following to your settings.py:

This setting is mutually exclusive with SILKY_PYTHON_PROFILER and will be used over it if present. It will work with SILKY_DYNAMIC_PROFILING.

def my_custom_logic(request):
    return 'profile_requests' in request.session

SILKY_PYTHON_PROFILER_FUNC = my_custom_logic # profile only session has recording enabled.

You can also use a lambda.

# profile only session has recording enabled.
SILKY_PYTHON_PROFILER_FUNC = lambda request: 'profile_requests' in request.session

Code Generation

Silk currently generates two bits of code per request:

Both are intended for use in replaying the request. The curl command can be used to replay via command-line and the python code can be used within a Django unit test or simply as a standalone script.

Configuration

Authentication/Authorisation

By default anybody can access the Silk user interface by heading to /silk/. To enable your Django auth backend place the following in settings.py:

SILKY_AUTHENTICATION = True  # User must login
SILKY_AUTHORISATION = True  # User must have permissions

If SILKY_AUTHORISATION is True, by default Silk will only authorise users with is_staff attribute set to True.

You can customise this using the following in settings.py:

def my_custom_perms(user):
    return user.is_allowed_to_use_silk

SILKY_PERMISSIONS = my_custom_perms

You can also use a lambda.

SILKY_PERMISSIONS = lambda user: user.is_superuser

Request/Response bodies

By default, Silk will save down the request and response bodies for each request for future viewing no matter how large. If Silk is used in production under heavy volume with large bodies this can have a huge impact on space/time performance. This behaviour can be configured with the following options:

SILKY_MAX_REQUEST_BODY_SIZE = -1  # Silk takes anything <0 as no limit
SILKY_MAX_RESPONSE_BODY_SIZE = 1024  # If response body>1024 bytes, ignore

Meta-Profiling

Sometimes it is useful to be able to see what effect Silk is having on the request/response time. To do this add the following to your settings.py:

SILKY_META = True

Silk will then record how long it takes to save everything down to the database at the end of each request:

Note that in the above screenshot, this means that the request took 29ms (22ms from Django and 7ms from Silk)

Recording a Fraction of Requests

On high-load sites it may be helpful to only record a fraction of the requests that are made. To do this add the following to your settings.py:

Note: This setting is mutually exclusive with SILKY_INTERCEPT_FUNC.

SILKY_INTERCEPT_PERCENT = 50 # log only 50% of requests

Custom Logic for Recording Requests

On high-load sites it may also be helpful to write your own logic for when to intercept requests. To do this add the following to your settings.py:

Note: This setting is mutually exclusive with SILKY_INTERCEPT_PERCENT.

def my_custom_logic(request):
    return 'record_requests' in request.session

SILKY_INTERCEPT_FUNC = my_custom_logic # log only session has recording enabled.

You can also use a lambda.

# log only session has recording enabled.
SILKY_INTERCEPT_FUNC = lambda request: 'record_requests' in request.session

Limiting request/response data

To make sure silky garbage collects old request/response data, a config var can be set to limit the number of request/response rows it stores.

SILKY_MAX_RECORDED_REQUESTS = 10**4

The garbage collection is only run on a percentage of requests to reduce overhead. It can be adjusted with this config:

SILKY_MAX_RECORDED_REQUESTS_CHECK_PERCENT = 10

In case you want decouple silk's garbage collection from your webserver's request processing, set SILKY_MAX_RECORDED_REQUESTS_CHECK_PERCENT=0 and trigger it manually, e.g. in a cron job:

python manage.py silk_request_garbage_collect

Enable query analysis

To enable query analysis when supported by the dbms a config var can be set in order to execute queries with the analyze features.

SILKY_ANALYZE_QUERIES = True

Warning: This setting may cause the database to execute the same query twice, depending on the backend. For instance, EXPLAIN ANALYZE in Postgres will actually execute the query, which may result in unexpected data updates. Set this to True with caution.

To pass additional params for profiling when supported by the dbms (e.g. VERBOSE, FORMAT JSON), you can do this in the following manner.

SILKY_EXPLAIN_FLAGS = {'format':'JSON', 'costs': True}

Masking sensitive data on request body

By default, Silk is filtering values that contains the following keys (they are case insensitive)

SILKY_SENSITIVE_KEYS = {'username', 'api', 'token', 'key', 'secret', 'password', 'signature'}

But sometimes, you might want to have your own sensitive keywords, then above configuration can be modified

SILKY_SENSITIVE_KEYS = {'custom-password'}

Clearing logged data

A management command will wipe out all logged data:

python manage.py silk_clear_request_log

Contributing

Jazzband

This is a Jazzband project. By contributing you agree to abide by the Contributor Code of Conduct and follow the guidelines.

Development Environment

Silk features a project named project that can be used for silk development. It has the silk code symlinked so you can work on the sample project and on the silk package at the same time.

In order to setup local development you should first install all the dependencies for the test project. From the root of the project directory:

pip install -r requirements.txt

You will also need to install silk's dependencies. From the root of the git repository:

pip install -e .

At this point your virtual environment should have everything it needs to run both the sample project and silk successfully.

Before running, you must set the DB_ENGINE and DB_NAME environment variables:

export DB_ENGINE=sqlite3
export DB_NAME=db.sqlite3

For other combinations, check tox.ini.

Now from the root of the sample project apply the migrations

python manage.py migrate

Now from the root of the sample project directory start the django server

python manage.py runserver

Running the tests

cd project
python manage.py test

Happy profiling!

More Repositories

1

django-debug-toolbar

A configurable set of panels that display various debug information about the current request/response.
Python
8,023
star
2

pip-tools

A set of tools to keep your pinned Python dependencies fresh.
Python
7,668
star
3

tablib

Python Module for Tabular Datasets in XLS, CSV, JSON, YAML, &c.
Python
4,586
star
4

djangorestframework-simplejwt

A JSON Web Token authentication plugin for the Django REST Framework.
Python
3,957
star
5

django-taggit

Simple tagging for django
Python
3,307
star
6

django-oauth-toolkit

OAuth2 goodies for the Djangonauts!
Python
3,148
star
7

django-redis

Full featured redis cache backend for Django.
Python
2,860
star
8

django-model-utils

Django model mixins and utilities.
Python
2,638
star
9

Watson

⌚ A wonderful CLI to track your time!
Python
2,450
star
10

django-push-notifications

Send push notifications to mobile devices through GCM or APNS in Django.
Python
2,275
star
11

django-simple-history

Store model history and view/revert changes from admin site.
Python
2,189
star
12

django-widget-tweaks

Tweak the form field rendering in templates, not in python-level form definitions. CSS classes and HTML attributes can be altered.
Python
2,077
star
13

sorl-thumbnail

Thumbnails for Django
Python
1,743
star
14

django-constance

Dynamic Django settings.
Python
1,687
star
15

django-two-factor-auth

Complete Two-Factor Authentication for Django providing the easiest integration into most Django projects.
Python
1,679
star
16

django-polymorphic

Improved Django model inheritance with automatic downcasting
Python
1,648
star
17

django-pipeline

Pipeline is an asset packaging library for Django.
Python
1,508
star
18

dj-database-url

Use Database URLs in your Django Application.
Python
1,471
star
19

django-axes

Keep track of failed login attempts in Django-powered sites.
Python
1,463
star
20

prettytable

Display tabular data in a visually appealing ASCII table format
Python
1,336
star
21

django-tinymce

TinyMCE integration for Django
JavaScript
1,270
star
22

django-analytical

Analytics services for Django projects
Python
1,197
star
23

django-admin2

Extendable, adaptable rewrite of django.contrib.admin
Python
1,185
star
24

django-rest-knox

Authentication Module for django rest auth
Python
1,130
star
25

django-waffle

A feature flipper for Django
Python
1,128
star
26

django-smart-selects

chained and grouped selects for django forms
Python
1,125
star
27

django-auditlog

A Django app that keeps a log of changes made to an object.
Python
1,108
star
28

django-configurations

A helper for organizing Django project settings by relying on well established programming patterns.
Python
1,085
star
29

django-defender

A simple super fast django reusable app that blocks people from brute forcing login attempts
Python
1,035
star
30

django-payments

Universal payment handling for Django.
Python
1,023
star
31

django-hosts

Dynamic and static host resolving for Django. Maps hostnames to URLconfs.
Python
977
star
32

django-dbbackup

Management commands to help backup and restore your project database and media files
Python
959
star
33

geojson

Python bindings and utilities for GeoJSON
Python
913
star
34

django-nose

Django test runner using nose
Python
882
star
35

django-newsletter

An email newsletter application for the Django web application framework, including an extended admin interface, web (un)subscription, dynamic e-mail templates, an archive and HTML email support.
Python
845
star
36

django-floppyforms

Full control of form rendering in the templates.
Python
841
star
37

django-avatar

A Django app for handling user avatars.
Python
806
star
38

django-formtools

A set of high-level abstractions for Django forms
Python
790
star
39

django-user-sessions

Extend Django sessions with a foreign key back to the user, allowing enumerating all user's sessions.
Python
616
star
40

django-admin-sortable

Generic drag-and-drop ordering for objects and tabular inlines in Django Admin
Python
564
star
41

django-invitations

Generic invitations app for Django
Python
557
star
42

django-sortedm2m

A transparent sorted ManyToMany field for django.
Python
511
star
43

django-recurrence

Utility for working with recurring dates in Django.
Python
475
star
44

django-categories

This app attempts to provide a generic category system that multiple apps could use. It uses MPTT for the tree storage and provides a custom admin for better visualization (copied and modified from feinCMS).
Python
458
star
45

django-robots

A Django app for managing robots.txt files following the robots exclusion protocol
Python
457
star
46

wagtailmenus

An app to help you manage and render menus in your Wagtail projects more effectively
Python
394
star
47

django-embed-video

Django app for easy embedding YouTube and Vimeo videos and music from SoundCloud.
Python
383
star
48

django-downloadview

Serve files with Django.
Python
378
star
49

django-eav2

Django EAV 2 - EAV storage for modern Django
Python
343
star
50

jsonmodels

jsonmodels is library to make it easier for you to deal with structures that are converted to, or read from JSON.
Python
335
star
51

django-queued-storage

Provides a proxy for Django storage backends that allows you to upload files locally and eventually serve them remotely
Python
316
star
52

django-permission

[Not maintained] An enhanced permission system which support object permission in Django
Python
302
star
53

django-revproxy

Reverse Proxy view that supports all HTTP methods, Diazo transformations and Single Sign-On.
Python
300
star
54

django-authority

A Django app that provides generic per-object-permissions for Django's auth app and helpers to create custom permission checks.
Python
292
star
55

django-simple-menu

Simple, yet powerful, code-based menus for Django applications
Python
264
star
56

django-dbtemplates

Django template loader for database stored templates with extensible cache backend
JavaScript
252
star
57

django-fsm-log

Automatic logging for Django FSM
Python
242
star
58

django-mongonaut

Built from scratch to replicate some of the Django admin functionality and add some more, to serve as an introspective interface for Django and Mongo.
Python
240
star
59

django-cookie-consent

Reusable application for managing various cookies and visitors consent for their use in Django project.
Python
224
star
60

django-celery-monitor

Celery Monitoring for Django
Python
197
star
61

docopt-ng

Humane command line arguments parser. Now with maintenance, typehints, and complete test coverage.
Python
178
star
62

django-ddp

Django/PostgreSQL implementation of the Meteor server.
Python
167
star
63

icalevents

Python module for iCal URL/file parsing and querying.
Python
156
star
64

django-voting

A generic voting application for Django
Python
99
star
65

django-ical

iCal feeds for Django based on Django's syndication feed framework.
Python
92
star
66

django-redshift-backend

Redshift database backend for Django
Python
83
star
67

django-flatblocks

django-chunks + headerfield + variable chunknames + "inclusion tag" == django-flatblocks
Python
82
star
68

pathlib2

Backport of pathlib aiming to support the full stdlib Python API.
Python
81
star
69

website

Code for the Jazzband website
Python
66
star
70

django-sorter

A helper app for sorting objects in Django templates.
Python
54
star
71

django-discover-jenkins

A streamlined fork of django-jenkins designed to work with the default test command and the discover runner
Python
49
star
72

django-fernet-encrypted-fields

Python
47
star
73

contextlib2

contextlib2 is a backport of the standard library's contextlib module to earlier Python versions.
Python
38
star
74

imaplib2

Fork of Piers Lauder's imaplib2 library for Python.
Python
33
star
75

help

Use this repo to get help from the roadies
27
star
76

django-postgres-utils

Django app providing additional lookups and functions for PostgreSQL
Python
9
star
77

.github

Community health and config files for Jazzband
7
star
78

admin

Some admin files for Jazzband
3
star
79

actions

Various GitHub actions for Jazzband projects
1
star