A drop-in replacement for Django's runserver.

Overview

About

A drop in replacement for Django's built-in runserver command. Features include:

  • An extendable interface for handling things such as real-time logging.
  • Integration with the werkzeug interactive debugger.
  • Threaded (default) and multi-process development servers.
  • Ability to specify a WSGI application as your target environment.

Note

django-devserver works on Django 1.3 and newer

Installation

To install the latest stable version:

pip install git+git://github.com/dcramer/django-devserver#egg=django-devserver

django-devserver has some optional dependancies, which we highly recommend installing.

  • pip install sqlparse -- pretty SQL formatting
  • pip install werkzeug -- interactive debugger
  • pip install guppy -- tracks memory usage (required for MemoryUseModule)
  • pip install line_profiler -- does line-by-line profiling (required for LineProfilerModule)

You will need to include devserver in your INSTALLED_APPS:

INSTALLED_APPS = (
    ...
    'devserver',
)

If you're using django.contrib.staticfiles or any other apps with management command runserver, make sure to put devserver above any of them (or below, for Django<1.7). Otherwise devserver will log an error, but it will fail to work properly.

Usage

Once installed, using the new runserver replacement is easy. You must specify verbosity of 0 to disable real-time log output:

python manage.py runserver

Note: This will force settings.DEBUG to True.

By default, devserver would bind itself to 127.0.0.1:8000. To change this default, DEVSERVER_DEFAULT_ADDR and DEVSERVER_DEFAULT_PORT settings are available.

Additional CLI Options

--werkzeug Tells Django to use the Werkzeug interactive debugger, instead of it's own.
--forked Use a forking (multi-process) web server instead of threaded.
--dozer Enable the dozer memory debugging middleware (at /_dozer)
--wsgi-app Load the specified WSGI app as the server endpoint.

Please see python manage.py runserver --help for more information additional options.

Note: You may also use devserver's middleware outside of the management command:

MIDDLEWARE_CLASSES = (
    'devserver.middleware.DevServerMiddleware',
)

Configuration

The following options may be configured via your settings.py:

DEVSERVER_ARGS = []
Additional command line arguments to pass to the runserver command (as defaults).
DEVSERVER_DEFAULT_ADDR = '127.0.0.1'
The default address to bind to.
DEVSERVER_DEFAULT_PORT = '8000'
The default port to bind to.
DEVSERVER_WSGI_MIDDLEWARE
A list of additional WSGI middleware to apply to the runserver command.
DEVSERVER_MODULES = []
A list of devserver modules to load.
DEVSERVER_IGNORED_PREFIXES = ['/media', '/uploads']
A list of prefixes to surpress and skip process on. By default, ADMIN_MEDIA_PREFIX, MEDIA_URL and STATIC_URL (for Django >= 1.3) will be ignored (assuming MEDIA_URL and STATIC_URL is relative)

Modules

django-devserver includes several modules by default, but is also extendable by 3rd party modules. This is done via the DEVSERVER_MODULES setting:

DEVSERVER_MODULES = (
    'devserver.modules.sql.SQLRealTimeModule',
    'devserver.modules.sql.SQLSummaryModule',
    'devserver.modules.profile.ProfileSummaryModule',

    # Modules not enabled by default
    'devserver.modules.ajax.AjaxDumpModule',
    'devserver.modules.profile.MemoryUseModule',
    'devserver.modules.cache.CacheSummaryModule',
    'devserver.modules.profile.LineProfilerModule',
)

devserver.modules.sql.SQLRealTimeModule

Outputs queries as they happen to the terminal, including time taken.

Disable SQL query truncation (used in SQLRealTimeModule) with the DEVSERVER_TRUNCATE_SQL setting:

DEVSERVER_TRUNCATE_SQL = False

Filter SQL queries with the DEVSERVER_FILTER_SQL setting:

DEVSERVER_FILTER_SQL = (
        re.compile('djkombu_\w+'),  # Filter all queries related to Celery
)

devserver.modules.sql.SQLSummaryModule

Outputs a summary of your SQL usage.

devserver.modules.profile.ProfileSummaryModule

Outputs a summary of the request performance.

devserver.modules.profile.MemoryUseModule

Outputs a notice when memory use is increased (at the end of a request cycle).

devserver.modules.profile.LineProfilerModule

Profiles view methods on a line by line basis. There are 2 ways to profile your view functions, by setting setting.DEVSERVER_AUTO_PROFILE = True or by decorating the view functions you want profiled with devserver.modules.profile.devserver_profile. The decoration takes an optional argument follow which is a sequence of functions that are called by your view function that you would also like profiled.

An example of a decorated function:

@devserver_profile(follow=[foo, bar])
def home(request):
    result['foo'] = foo()
    result['bar'] = bar()

When using the decorator, we recommend that rather than import the decoration directly from devserver that you have code somewhere in your project like:

try:
    if 'devserver' not in settings.INSTALLED_APPS:
        raise ImportError
    from devserver.modules.profile import devserver_profile
except ImportError:
    from functools import wraps
    class devserver_profile(object):
        def __init__(self, *args, **kwargs):
            pass
        def __call__(self, func):
            def nothing(*args, **kwargs):
                return func(*args, **kwargs)
            return wraps(func)(nothing)

By importing the decoration using this method, devserver_profile will be a pass through decoration if you aren't using devserver (eg in production)

devserver.modules.cache.CacheSummaryModule

Outputs a summary of your cache calls at the end of the request.

devserver.modules.ajax.AjaxDumpModule

Outputs the content of any AJAX responses

Change the maximum response length to dump with the DEVSERVER_AJAX_CONTENT_LENGTH setting:

DEVSERVER_AJAX_CONTENT_LENGTH = 300

devserver.modules.request.SessionInfoModule

Outputs information about the current session and user.

Building Modules

Building modules in devserver is quite simple. In fact, it resembles the middleware API almost identically.

Let's take a sample module, which simple tells us when a request has started, and when it has finished:

from devserver.modules import DevServerModule

class UselessModule(DevServerModule):
    logger_name = 'useless'

    def process_request(self, request):
        self.logger.info('Request started')

    def process_response(self, request, response):
        self.logger.info('Request ended')

There are additional arguments which may be sent to logger methods, such as duration:

# duration is in milliseconds
self.logger.info('message', duration=13.134)
Comments
  • Django >= 1.7 compatibility for requires_system_checks

    Django >= 1.7 compatibility for requires_system_checks

    Hi @dcramer,

    Devserver will fail to start up on Django 1.7 with the error:

    django.core.exceptions.ImproperlyConfigured: Command Command defines both "requires_model_validation" and "requires_system_checks", which is illegal. Use only "requires_system_checks".
    

    The django-devserver runserver management command inherits from the django core runserver management command which set requires_system_checks = False. The django-devserver runserver management command then sets requires_model_validation = False.

    This pull request ensures only the appropriate attribute is set to False, so is backwards compatible with Django < 1.7.

    The implementation is only suggested. If you have another way you'd prefer to do it that's fine, this was just a convenient way to illustrate the issue.

    opened by nealtodd 13
  • Line profiling module

    Line profiling module

    Integrates Robert Kern's line_profiler (http://pypi.python.org/pypi/line_profiler)

    Uses similar style to the memory profiler to only activate if line_profiler is installed. Annotate the functions you want to profile with the decorator: devserver.modules.profile.devserver_profile and you get nifty output like:

    [profile] Timer unit: 1e-06 s
    
          File: /Users/dmclain/comal/colorado/views.py
          Function: damage at line 21
          Total time: 3.50469 s
    
          Line #      Hits         Time  Per Hit   % Time  Line Contents
          ==============================================================
              21                                           def damage(obj):
              22       437         2505      5.7      0.1      obj.name = obj.name + ' '
              23       437      3502190   8014.2     99.9      obj.save()
    
          File: /Users/dmclain/comal/colorado/views.py
          Function: undo_damage at line 25
          Total time: 3.49118 s
    
          Line #      Hits         Time  Per Hit   % Time  Line Contents
          ==============================================================
              25                                           def undo_damage(obj):
              26       437         2355      5.4      0.1      obj.name = obj.name.strip()
              27       437      3488826   7983.6     99.9      obj.save()
    
          File: /Users/dmclain/comal/colorado/views.py
          Function: home at line 29
          Total time: 7.19363 s
    
          Line #      Hits         Time  Per Hit   % Time  Line Contents
          ==============================================================
              29                                           @rendered_with("dashboard.html")
              30                                           @devserver_profile(follow=[damage, undo_damage])
              31                                           def home(request):
              32         1          140    140.0      0.0      facilities = fac_models.Facility.objects.all()
              33         8        12004   1500.5      0.2      for f in facilities:
              34         7        55571   7938.7      0.8          damage(f)
              35         7        55132   7876.0      0.8          undo_damage(f)
              36         1          637    637.0      0.0      rooms = fac_models.Room.objects.all()
              37       431       169929    394.3      2.4      for r in rooms:
              38       430      3456321   8038.0     48.0          damage(r)
              39       430      3443896   8009.1     47.9          undo_damage(r)
              40         1            4      4.0      0.0      return locals()
    
    opened by dmclain 8
  • Django 1.8.2 runserver not replaced

    Django 1.8.2 runserver not replaced

    Hi, sorry I have a problem with your application on Django 1.8.2/3. when I run ./manage.py runserver, it doesn't take your command but the original one instead. I can't understand why.

    I installed django-devserver with pip,

    then in settings.py:

    added 'devserver' to INSTALLED_APPS, added 'devserver.middleware.DevServerMiddleware' to MIDDLEWARE_CLASSES added some options: DEVSERVER_DEFAULT_ADDR = '0.0.0.0' DEVSERVER_DEFAULT_PORT = '8888'

    when I run ./manage.py runserver it doesn't take the new address and port and the help message suggests that it is the original runserver...

    Any suggestion? Thank You

    opened by qlimax86 6
  • AdminMediaHandler deprecated in django 1.4

    AdminMediaHandler deprecated in django 1.4

    For django 1.4, AdminMediaHandler has been replaced by StaticFilesHandler with the same signature.

    See this fix for gunicorn.

    Works OOTB if implemented in devserver.

    --- a/devserver/management/commands/runserver.py
    +++ b/devserver/management/commands/runserver.py
    @@ -1,7 +1,8 @@
     from django.conf import settings
     from django.core.management.base import BaseCommand, CommandError, handle_default_options
    -from django.core.servers.basehttp import AdminMediaHandler, WSGIServerException, \
    +from django.core.servers.basehttp import WSGIServerException, \
                                              WSGIServer
    +from django.contrib.staticfiles.handlers import StaticFilesHandler
     from django.core.handlers.wsgi import WSGIHandler
    
     import os
    @@ -163,7 +164,7 @@ class Command(BaseCommand):
                     from django.contrib.staticfiles.handlers import StaticFilesHandler
                     app = StaticFilesHandler(app)
                 else:
    -                app = AdminMediaHandler(app, admin_media_path)
    +                app = StaticFilesHandler(app, admin_media_path)
    
                 if options['use_dozer']:
                     from dozer import Dozer
    diff --git a/devserver/testcases.py b/devserver/testcases.py
    index c18ebc7..f499b96 100644
    --- a/devserver/testcases.py
    +++ b/devserver/testcases.py
    @@ -3,8 +3,9 @@ import SocketServer
     from django.conf import settings
     from django.core.handlers.wsgi import WSGIHandler
     from django.core.management import call_command
    -from django.core.servers.basehttp import StoppableWSGIServer, AdminMediaHandler, WSGIServerException
    +from django.core.servers.basehttp import StoppableWSGIServer, WSGIServerException
     from django.test.testcases import TestServerThread
    +from django.contrib.staticfiles.handlers import StaticFilesHandler
    
    opened by jhaynes 6
  • DEVSERVER_IGNORED_PREFIXES is ignored

    DEVSERVER_IGNORED_PREFIXES is ignored

    By default the devserver should not show output lines for static files or url prefixes defined in DEVSERVER_IGNORED_PREFIXES according to documentation. This is my setup and results:

    pip freeze:

    Django==1.8.3 Werkzeug==0.10.4 argparse==1.2.1 click==4.0 django-devserver==0.8.0 doitlive==2.3.1 guppy==0.1.10 ipython==3.2.1 line-profiler==1.0 psycopg2==2.6.1 sqlparse==0.1.15 wsgiref==0.1.2

    Relevant settings.py section:

    INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'devserver', )

    MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'devserver.middleware.DevServerMiddleware', )

    DEVSERVER_MODULES = ( 'devserver.modules.sql.SQLRealTimeModule', 'devserver.modules.sql.SQLSummaryModule', 'devserver.modules.profile.ProfileSummaryModule', 'devserver.modules.ajax.AjaxDumpModule', 'devserver.modules.profile.MemoryUseModule', 'devserver.modules.cache.CacheSummaryModule', 'devserver.modules.profile.LineProfilerModule', 'devserver.modules.sql.SQLRealTimeModule',

    )

    DEVSERVER_TRUNCATE_SQL = False

    DEVSERVER_IGNORED_PREFIXES = ['/static/',]

    Sample output from python manage.py runserver:

    Django version 1.8.3, using settings 'masterclass.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. sql 5 queries with 0 duplicates [profile] Total time to render was 0.22s [profile] 3.2 MB allocated, 26.8 KB deallocated, heap size is 20.4 MB [cache] 0 calls made with a 100% hit percentage (0 misses) [15/Jul/2015 10:51:02]"GET /admin/auth/user/ HTTP/1.1" 200 6612 [15/Jul/2015 10:51:03]"GET /static/admin/css/base.css HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/css/changelists.css HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/js/admin/RelatedObjectLookups.js HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/js/core.js HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/js/jquery.js HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/js/jquery.init.js HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/js/actions.js HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/img/icon_searchbox.png HTTP/1.1" 304 0 [15/Jul/2015 10:51:03]"GET /static/admin/img/icon-yes.gif HTTP/1.1" 304 0 sql 2 queries with 0 duplicates [profile] Total time to render was 0.11s [profile] 128.7 KB allocated, 149.0 KB deallocated, heap size is 20.4 MB [cache] 0 calls made with a 100% hit percentage (0 misses) [15/Jul/2015 10:51:03]"GET /admin/jsi18n/ HTTP/1.1" 200 2372

    opened by beltiras 5
  • Drop in replacement may fail in Django 1.7 with django.contrib.staticfiles

    Drop in replacement may fail in Django 1.7 with django.contrib.staticfiles

    In Django 1.7, if django.contrib.staticfiles is in INSTALLED_APPS and django.contrib.staticfiles comes before devserver in INSTALLED_APPS then staticfile's sub-classed runserver management command is used instead of django-devserver's runserver management command.

    This breaks the drop-in replacement nature of devserver.

    Putting devserver ahead of django.contrib.staticfiles results in django-devserver's runserver being used.

    Might not be anything that can be done about that other than a note in the README about the ordering in INSTALLED_APPS.

    opened by nealtodd 5
  • KeyError: 'time' on the first request and KeyError: 'duration' on the subsequent requests

    KeyError: 'time' on the first request and KeyError: 'duration' on the subsequent requests

    I receive the same exception as the user in issue #1 on the first request:

    Traceback (most recent call last):
    
      File "E:\Other\Software\Django\django\core\servers\basehttp.py", line 279, in run
        self.result = application(self.environ, self.start_response)
    
      File "E:\Other\Software\Django\django\core\servers\basehttp.py", line 651, in __call__
        return self.application(environ, start_response)
    
      File "C:\Python26\lib\site-packages\devserver\handlers.py", line 200, in __call__
        DevServerMiddleware().process_complete(request)
    
      File "C:\Python26\lib\site-packages\devserver\handlers.py", line 141, in process_complete
        mod.process_complete(request)
    
      File "C:\Python26\lib\site-packages\devserver\modules\sql.py", line 131, in process_complete
        ), duration=sum(float(c['time']) for c in connection.queries))
    
      File "C:\Python26\lib\site-packages\devserver\modules\sql.py", line 131, in <genexpr>
        ), duration=sum(float(c['time']) for c in connection.queries))
    
    KeyError: 'time'
    

    and this one on all the subsequent requests if I'm using it in combination with debug-toolbar:

    Traceback (most recent call last):
    
      File "E:\Other\Software\Django\django\core\servers\basehttp.py", line 279, in run
        self.result = application(self.environ, self.start_response)
    
      File "E:\Other\Software\Django\django\core\servers\basehttp.py", line 651, in __call__
        return self.application(environ, start_response)
    
      File "C:\Python26\lib\site-packages\devserver\handlers.py", line 182, in __call__
        response = middleware_method(request, response)
    
      File "C:\Python26\lib\site-packages\django_debug_toolbar-0.8.1-py2.6.egg\debug_toolbar\middleware.py", line 91, in process_response
        response.content = replace_insensitive(smart_unicode(response.content), u'</body>', smart_unicode(self.debug_toolbars[request].render_toolbar() + u'</body>'))
    
      File "C:\Python26\lib\site-packages\django_debug_toolbar-0.8.1-py2.6.egg\debug_toolbar\toolbar\loader.py", line 72, in render_toolbar
        'BASE_URL': self.request.META.get('SCRIPT_NAME', ''),
    
      File "E:\Other\Software\Django\django\template\loader.py", line 173, in render_to_string
        return t.render(context_instance)
    
      File "E:\Other\Software\Django\django\test\utils.py", line 29, in instrumented_test_render
        return self.nodelist.render(context)
    
      File "E:\Other\Software\Django\django\template\__init__.py", line 787, in render
        bits.append(self.render_node(node, context))
    
      File "E:\Other\Software\Django\django\template\debug.py", line 82, in render_node
        raise wrapped
    
    TemplateSyntaxError: Caught an exception while rendering: duration
    
    Original Traceback (most recent call last):
      File "E:\Other\Software\Django\django\template\debug.py", line 72, in render_node
        result = node.render(context)
      File "E:\Other\Software\Django\django\template\defaulttags.py", line 176, in render
        nodelist.append(node.render(context))
      File "E:\Other\Software\Django\django\template\defaulttags.py", line 428, in render
        val = self.var.resolve(context)
      File "E:\Other\Software\Django\django\template\__init__.py", line 554, in resolve
        obj = self.var.resolve(context)
      File "E:\Other\Software\Django\django\template\__init__.py", line 695, in resolve
        value = self._resolve_lookup(context)
      File "E:\Other\Software\Django\django\template\__init__.py", line 730, in _resolve_lookup
        current = current()
      File "C:\Python26\lib\site-packages\django_debug_toolbar-0.8.1-py2.6.egg\debug_toolbar\panels\sql.py", line 150, in nav_subtitle
        self._sql_time = sum([q['duration'] for q in self._queries])
    KeyError: 'duration'
    
    opened by Kami 5
  • Inifinite recursion in sql module

    Inifinite recursion in sql module

    Running django application through devserver (django 1.6rc, devserver 0.7.0) causes infinite recursion error on line 77 devserver/modules/sql.py return super(DatabaseStatTracker, self).execute(sql, params)

    opened by sicarrots 4
  • Handle removal of WSGIServerException in Django 1.6

    Handle removal of WSGIServerException in Django 1.6

    WSGIServerException was replaced with socket.error in Django 1.6. See https://github.com/django/django/commit/56201fe5a85ead96f00d8ad2eda5cfd2bc4cb4b0

    This patch fixes the resulting ImportError and preserves compatibility with older Django versions.

    opened by mkai 4
  • Strongly outdated CHANGES File

    Strongly outdated CHANGES File

    I just noticed that the CHANGES File was not updated since version 0.3.1, which was 2 years ago.

    With a up to date CHANGES File it is easier possible to follow changes like the removeal of WSGIServerException and the bugfix done here: #86.

    Would it be possible to get it up to date?

    opened by DebVortex 3
  • Realtime SQL Hangs on bulk_create

    Realtime SQL Hangs on bulk_create

    whenn running a large bulk create while having sql realtime enabled, the python process did take 100% cpu and no query was sent out

    the issue disappeared with disableing the sql display

    opened by RonnyPfannschmidt 3
  • Fix syntaxError and make it compatible with python3

    Fix syntaxError and make it compatible with python3

    Fix #109

    File "/home/js/.virtualenvs/ppm/lib64/python3.4/site-packages/devserver/models.py", line 20
        raise exceptions.ImproperlyConfigured, '%s isn\'t a devserver module' % path
                                             ^
    SyntaxError: invalid syntax
    
    opened by shihokambara 0
  • maximum recursion depth exceeded on Django 1.10

    maximum recursion depth exceeded on Django 1.10

    This is my python packages:

    Django==1.10.1 django-braces==1.9.0 django-cors-middleware==1.3.1 django-devserver==0.8.0 django-oauth-toolkit==0.10.0 djangorestframework==3.4.6 drfdocs==0.0.11 guppy==0.1.10 line-profiler==1.0 Markdown==2.6.6 oauthlib==1.0.3 Pillow==3.3.1 psycopg2==2.6.2 requests==2.11.1 six==1.10.0 sqlparse==0.2.1 Werkzeug==0.11.11

    I configured multiple settings file which results to: settings - init.py - base.py - local.py

    This is my base.py

    """
    Django settings for xxx_api project.
    
    Generated by 'django-admin startproject' using Django 1.10.1.
    
    For more information on this file, see
    https://docs.djangoproject.com/en/1.10/topics/settings/
    
    For the full list of settings and their values, see
    https://docs.djangoproject.com/en/1.10/ref/settings/
    """
    
    import os
    
    # Build paths inside the project like this: os.path.join(BASE_DIR, ...)
    # BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    
    
    # Quick-start development settings - unsuitable for production
    # See https://docs.djangoproject.com/en/1.10/howto/deployment/checklist/
    
    # SECURITY WARNING: keep the secret key used in production secret!
    SECRET_KEY = ')@kqdcf)0l@l37m@r(_ng3-loe%5j@0g!-h@uju0qek@%m&r7l'
    
    # SECURITY WARNING: don't run with debug turned on in production!
    DEBUG = True
    
    ALLOWED_HOSTS = []
    
    
    # Application definition
    
    INSTALLED_APPS = [
        'django.contrib.admin',
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.messages',
        'django.contrib.staticfiles',
    ]
    
    MANUALLY_BUILT_APPS = [
        'api',
        'core',
        'core.conversations',
        'core.reports',
        'core.groups',
        'core.accounts',
        'system_admin',
        'assessor',
        'workplace_supervisor',
        'students',
        'functional_tests',
    ]
    INSTALLED_APPS += MANUALLY_BUILT_APPS
    
    THIRD_PARTY_APPS = [
        'corsheaders',
        'rest_framework', # Restful API library for Django
        'oauth2_provider', # Oauth2 library especially made for django with django rest framework integration
        'rest_framework_docs', # Library for creating API Documentation
        'markdown',
    ]
    INSTALLED_APPS += THIRD_PARTY_APPS
    
    MIDDLEWARE_CLASSES = [
        'corsheaders.middleware.CorsMiddleware',
        'django.contrib.sessions.middleware.SessionMiddleware',
        'django.middleware.common.CommonMiddleware',
        'django.middleware.csrf.CsrfViewMiddleware',
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
        'django.contrib.messages.middleware.MessageMiddleware',
        'django.middleware.clickjacking.XFrameOptionsMiddleware',
        'django.middleware.security.SecurityMiddleware',
    ]
    
    ROOT_URLCONF = 'xxx_api.urls'
    
    TEMPLATES = [
        {
            'BACKEND': 'django.template.backends.django.DjangoTemplates',
            'DIRS': [],
            'APP_DIRS': True,
            'OPTIONS': {
                'context_processors': [
                    'django.template.context_processors.debug',
                    'django.template.context_processors.request',
                    'django.contrib.auth.context_processors.auth',
                    'django.contrib.messages.context_processors.messages',
                ],
            },
        },
    ]
    
    WSGI_APPLICATION = 'xxx_api.wsgi.application'
    
    
    # Database
    # https://docs.djangoproject.com/en/1.10/ref/settings/#databases
    
    DATABASES = {
        "default": {
            "ENGINE": "django.db.backends.postgresql_psycopg2",
            "NAME": "xxx",
            "USER": "xxx",
            "PASSWORD": "xxxxxxxx",
            "HOST": "xxx",
            "PORT": "5432"
        }
    }
    
    if os.environ.get('BITBUCKETPIPELINES', '0') == '1':
        DATABASES = {
            "default": {
                "ENGINE": "django.db.backends.postgresql_psycopg2",
                "NAME": "xxx",
                "USER": "root",
                "PASSWORD": "pass1234",
                "HOST": "127.0.0.1",
                "PORT": "5432"
            }
        }
    # Password validation
    # https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
    
    
    # Password validation
    # https://docs.djangoproject.com/en/1.10/ref/settings/#auth-password-validators
    
    AUTH_PASSWORD_VALIDATORS = [
        {
            'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
        },
        {
            'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
        },
    ]
    
    
    # Internationalization
    # https://docs.djangoproject.com/en/1.10/topics/i18n/
    
    LANGUAGE_CODE = 'en-us'
    
    TIME_ZONE = 'UTC'
    
    USE_I18N = False # Set to False to import optimizations
    
    USE_L10N = True
    
    USE_TZ = True
    
    # Source: fideloper.com/api-etag-conditional-get
    # Use "If-None-Match" header with Etag
    # Work with client on this carefully
    USE_ETAGS = True # For caching mechanism
    
    # Static files (CSS, JavaScript, Images)
    # https://docs.djangoproject.com/en/1.10/howto/static-files/
    
    STATIC_URL = '/static/'
    
    MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
    MEDIA_URL = '/media/'
    
    # START Django Rest Framework settings
    REST_FRAMEWORK = {
        'DEFAULT_PERMISSION_CLASSES': (
            'rest_framework.permissions.IsAuthenticated',
        ),
        'DEFAULT_AUTHENTICATION_CLASSES': (
            'oauth2_provider.ext.rest_framework.OAuth2Authentication',
        ),
        # Disables the Admin UI of the Django Rest Framework
        # Source: http://stackoverflow.com/questions/11898065/how-to-disable-admin-style-browsable-interface-of-django-rest-framework
        'DEFAULT_RENDERER_CLASSES': (
            'rest_framework.renderers.JSONRenderer',
        )
    }
    # END Django Rest Framework settings
    
    CORS_ORIGIN_ALLOW_ALL = True
    
    OAUTH2_PROVIDER = {
        "ACCESS_TOKEN_EXPIRE_SECONDS": 7776000 # 3 months
    }
    

    This is my local.py

    from .base import *
    
    DATABASES = {
        'default': {
            'ENGINE': 'django.db.backends.postgresql_psycopg2',
            'NAME': 'xxx',
            'USER': 'deanarmada',
            'PASSWORD': 'd3@narmada13',
            'HOST': 'localhost',
            'PORT': '',
        }
    }
    
    LOCAL_APPS = [
      'devserver', 
    ]
    INSTALLED_APPS += LOCAL_APPS
    
    LOCAL_MIDDLEWARES = [
      'devserver.middleware.DevServerMiddleware',
    ]
    MIDDLEWARE_CLASSES += LOCAL_MIDDLEWARES
    
    # Extra DEVSERVER logging
    DEVSERVER_MODULES = (
        'devserver.modules.sql.SQLRealTimeModule',
        'devserver.modules.sql.SQLSummaryModule',
        'devserver.modules.profile.ProfileSummaryModule',
    
        # Modules not enabled by default
        'devserver.modules.ajax.AjaxDumpModule',
        'devserver.modules.profile.MemoryUseModule',
        'devserver.modules.cache.CacheSummaryModule',
        'devserver.modules.profile.LineProfilerModule',
    )
    
    DEVSERVER_AUTO_PROFILE = True # profiles all views without the need of function decorator
    

    It is just fine when I do a runserver but when I do a request this is what shows in the log:

      File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/logging/__init__.py", line 1364, in isEnabledFor
        return level >= self.getEffectiveLevel()
    RuntimeError: maximum recursion depth exceeded
        [sql] SELECT ...
          FROM "auth_user"
          WHERE "auth_user"."username" = dean LIMIT 21
        [sql] SELECT ...
          FROM "auth_user" LIMIT 21
        [sql] SELECT ...
          FROM "auth_user"
          WHERE "auth_user"."username" = dean LIMIT 21
        [sql] SELECT ...
          FROM "auth_user"
          WHERE "auth_user"."username" = dean LIMIT 21
        [sql] SELECT ...
          FROM "auth_user"
          WHERE "auth_user"."username" = dean LIMIT 21
        [sql] (82914ms) 5699 queries with 5698 duplicates
        [profile] Total time to render was 2.42s
        [profile] 10.6 MB allocated, 44.6 KB deallocated, heap size is 30.5 MB
        [cache] 0 calls made with a 100% hit percentage (0 misses)
        [profile] Timer unit: 1e-06 s
    
              Total time: 0.032768 s
              File: /Users/deanarmada/.virtualenvs/api/lib/python2.7/site-packages/django/views/decorators/csrf.py
              Function: wrapped_view at line 57
    
              Line #      Hits         Time  Per Hit   % Time  Line Contents
              ==============================================================
                  57                                               def wrapped_view(*args, **kwargs):
                  58         1        32768  32768.0    100.0          return view_func(*args, **kwargs)
    
    
    opened by Dean-Christian-Armada 2
  • devserver/modules/sql.py:15: The django.db.backends.util module has been renamed.

    devserver/modules/sql.py:15: The django.db.backends.util module has been renamed.

    /usr/local/lib/python2.7/dist-packages/devserver/modules/sql.py:15: RemovedInDjango19Warning: The django.db.backends.util module has been renamed. Use django.db.backends.utils instead. from django.db.backends import util

    opened by linghu-chong 3
Owner
David Cramer
founder/cto @getsentry
David Cramer
pdb++, a drop-in replacement for pdb (the Python debugger)

pdb++, a drop-in replacement for pdb What is it? This module is an extension of the pdb module of the standard library. It is meant to be fully compat

null 1k Dec 24, 2022
pdb++, a drop-in replacement for pdb (the Python debugger)

pdb++, a drop-in replacement for pdb What is it? This module is an extension of the pdb module of the standard library. It is meant to be fully compat

null 1k Jan 2, 2023
Middleware that Prints the number of DB queries to the runserver console.

Django Querycount Inspired by this post by David Szotten, this project gives you a middleware that prints DB query counts in Django's runserver consol

Brad Montgomery 332 Dec 23, 2022
A drop-in replacement for Django's runserver.

About A drop in replacement for Django's built-in runserver command. Features include: An extendable interface for handling things such as real-time l

David Cramer 1.3k Dec 15, 2022
A drop-in replacement for Django's runserver.

About A drop in replacement for Django's built-in runserver command. Features include: An extendable interface for handling things such as real-time l

David Cramer 1.3k Dec 15, 2022
Drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.

Xadmin Drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap. Liv

差沙 4.7k Dec 31, 2022
pdb++, a drop-in replacement for pdb (the Python debugger)

pdb++, a drop-in replacement for pdb What is it? This module is an extension of the pdb module of the standard library. It is meant to be fully compat

null 1k Dec 24, 2022
Python implementation of cover trees, near-drop-in replacement for scipy.spatial.kdtree

This is a Python implementation of cover trees, a data structure for finding nearest neighbors in a general metric space (e.g., a 3D box with periodic

Patrick Varilly 28 Nov 25, 2022
Drop-in Replacement of pychallonge

pychal Pychal is a drop-in replacement of pychallonge with some extra features and support for new Python versions. Pychal provides python bindings fo

ZED 29 Nov 28, 2022
A drop-in replacement for argparse that allows options to also be set via config files and/or environment variables.

ConfigArgParse Overview Applications with more than a handful of user-settable options are best configured through a combination of command line args,

null 634 Dec 22, 2022
pdb++, a drop-in replacement for pdb (the Python debugger)

pdb++, a drop-in replacement for pdb What is it? This module is an extension of the pdb module of the standard library. It is meant to be fully compat

null 1k Jan 2, 2023
An Aspiring Drop-In Replacement for NumPy at Scale

Legate NumPy is a Legate library that aims to provide a distributed and accelerated drop-in replacement for the NumPy API on top of the Legion runtime. Using Legate NumPy you do things like run the final example of the Python CFD course completely unmodified on 2048 A100 GPUs in a DGX SuperPOD and achieve good weak scaling.

Legate 502 Jan 3, 2023
Drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap.

Xadmin Drop-in replacement of Django admin comes with lots of goodies, fully extensible with plugin support, pretty UI based on Twitter Bootstrap. Liv

差沙 4.7k Dec 31, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for quickly creating new images from the one assigned to the field.

django-versatileimagefield A drop-in replacement for django's ImageField that provides a flexible, intuitive and easily-extensible interface for creat

Jonathan Ellenberger 490 Dec 13, 2022
A simple plugin to attach a debugger in Django on runserver command.

django-debugger A simple plugin to attach a debugger in Django during runserver Installation pip install django-debugger Usage Prepend django_debugger

Sajal Shrestha 11 Nov 15, 2021
Middleware that Prints the number of DB queries to the runserver console.

Django Querycount Inspired by this post by David Szotten, this project gives you a middleware that prints DB query counts in Django's runserver consol

Brad Montgomery 332 Dec 23, 2022
Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js

pivottablejs: the Python module Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js Installation pip install pivot

Nicolas Kruchten 512 Dec 26, 2022
Drop-in MessagePack support for ASGI applications and frameworks

msgpack-asgi msgpack-asgi allows you to add automatic MessagePack content negotiation to ASGI applications (Starlette, FastAPI, Quart, etc.), with a s

Florimond Manca 128 Jan 2, 2023
Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js

pivottablejs: the Python module Drag’n’drop Pivot Tables and Charts for Jupyter/IPython Notebook, care of PivotTable.js Installation pip install pivot

Nicolas Kruchten 419 Feb 11, 2021