Ticket #16360: 16360.2.2.diff

File 16360.2.2.diff, 18.0 KB (added by jezdez, 4 years ago)

Latest changes

  • django/conf/global_settings.py

    diff --git a/django/conf/global_settings.py b/django/conf/global_settings.py
    index 7b7531a..73d180c 100644
    412412# Default X-Frame-Options header value
     415# The import name of the WSGI application. If this is `None` the default
     416# 'django.core.handlers.wsgi.application' is used. Otherwise this shall
     417# point to an actual WSGI application.
    416421# MIDDLEWARE #
  • django/conf/project_template/settings.py

    diff --git a/django/conf/project_template/settings.py b/django/conf/project_template/settings.py
    index 3a2243f..59a2d22 100644
    100100ROOT_URLCONF = '{{ project_name }}.urls'
     102# The WSGI application used by Django's runserver etc.
     103WSGI_APPLICATION = '{{ project_name }}.wsgi.application'
    102105TEMPLATE_DIRS = (
    103106    # Put strings here, like "/home/html/django_templates" or "C:/www/django/templates".
    104107    # Always use forward slashes, even on Windows.
  • new file django/conf/project_template/wsgi.py

    diff --git a/django/conf/project_template/wsgi.py b/django/conf/project_template/wsgi.py
    new file mode 100644
    index 0000000..7e37f60
    - +  
     2WSGI config for {{ project_name }} project.
     4This module contains the actual WSGI application to be used by Django's
     5development server and the production environment as the global variable
     6named ``application`` and is enabled by setting the ``WSGI_APPLICATION``
     7setting to '{{ project_name }}.wsgi.application'.
     9Of course usually you would have an actual Django WSGI application here,
     10but it also might make sense to replace the whole Django WSGI application
     11with a custom one that later delegates to the Django one (for instance if
     12you want to combine a Django application with an application of another
     15from django.core.management import setup_settings
     17settings = setup_settings(__name__)
     19# The application object is used by the development server
     20# as well as a WSGI server configured to use this file.
     21from django.core.handlers.wsgi import application
     23# Apply other WSGI middlewares here.
     24# from helloworld.wsgi import HelloWorldApplication
     25# application = HelloWorldApplication(application)
  • django/contrib/staticfiles/handlers.py

    diff --git a/django/contrib/staticfiles/handlers.py b/django/contrib/staticfiles/handlers.py
    index 962b835..d9f6833 100644
    a b class StaticFilesHandler(WSGIHandler): 
    1212    WSGI middleware that intercepts calls to the static files directory, as
    1313    defined by the STATIC_URL setting, and serves those files.
    1414    """
    15     def __init__(self, application, base_dir=None):
     15    def __init__(self, application, base_dir=None, enabled=True):
     16        # If not enabled this directly proxies to the given application.
     17        self.enabled = enabled
    1618        self.application = application
    1719        if base_dir:
    1820            self.base_dir = base_dir
    class StaticFilesHandler(WSGIHandler): 
    6365        return super(StaticFilesHandler, self).get_response(request)
    6567    def __call__(self, environ, start_response):
    66         if not self._should_handle(environ['PATH_INFO']):
    67             return self.application(environ, start_response)
    68         return super(StaticFilesHandler, self).__call__(environ, start_response)
     68        if self.enabled and self._should_handle(environ['PATH_INFO']):
     69            return super(StaticFilesHandler, self).__call__(environ, start_response)
     70        return self.application(environ, start_response)
  • django/contrib/staticfiles/management/commands/runserver.py

    diff --git a/django/contrib/staticfiles/management/commands/runserver.py b/django/contrib/staticfiles/management/commands/runserver.py
    index c6e56d2..d4e332c 100644
    a b class Command(BaseRunserverCommand): 
    2121        handler = super(Command, self).get_handler(*args, **options)
    2222        use_static_handler = options.get('use_static_handler', True)
    2323        insecure_serving = options.get('insecure_serving', False)
    24         if (settings.DEBUG and use_static_handler or
    25                 (use_static_handler and insecure_serving)):
    26             handler = StaticFilesHandler(handler)
    27         return handler
     24        enabled = use_static_handler and (settings.DEBUG or insecure_serving)
     25        return StaticFilesHandler(handler, enabled=enabled)
  • django/core/handlers/base.py

    diff --git a/django/core/handlers/base.py b/django/core/handlers/base.py
    index a6c8044..5364e65 100644
    a b def get_script_name(environ): 
    242242    Returns the equivalent of the HTTP request's SCRIPT_NAME environment
    243243    variable. If Apache mod_rewrite has been used, returns what would have been
    244244    the script name prior to any rewriting (so it's the script name as seen
    245     from the client's perspective), unless DJANGO_USE_POST_REWRITE is set (to
    246     anything).
     245    from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
     246    set (to anything).
    247247    """
    248248    from django.conf import settings
    249249    if settings.FORCE_SCRIPT_NAME is not None:
  • django/core/handlers/wsgi.py

    diff --git a/django/core/handlers/wsgi.py b/django/core/handlers/wsgi.py
    index 56d2ba6..a4e1aa7 100644
    a b  
     2WSGI entrypoints
     7The motivation behind this module is to expose the WSGI application that
     8exists in Django to the actual Django user project. The idea is that you
     9have a documented way to apply WSGI middlewares that are then being used by
     10both the internal WSGI development server as well as any other WSGI server
     11in production.
     13The way it works is that there are a handful of WSGI application objects:
     15-   django.core.handlers.wsgi.WSGIHandler: this is the implementation of the
     16    actual Django WSGI dispatcher and it should be considered an
     17    implementation detail. While users are free to subclass and extend it,
     18    it's not necessarily supported.
     19-   django.core.handlers.wsgi.application: this is the documented WSGI
     20    application which is used by default.
     21-   django.core.handlers.wsgi.django_application: this is the actual WSGI
     22    application that is passed to the servers. It's internally proxying to
     23    the configured WSGI application and will most likely be a (decorated)
     24    version of the `application`.
     26The reason why we have multiple applications here is because of the
     27ability to apply middlewares.  Basically `application` is the WSGI
     28application without any middlewarse applied, `django_application` is a
     29proxy to the base application + all applied middlewares.
     31The middlewares are added according to the WSGI_APPLICATION configuration
     32setting which points to a module that imports the `application` as
     33`application` and can apply middlewares.
     35If the WSGI_APPLICATION setting is ``None`` (which is the case for upgraded
     36applications from before we had exposed WSGI support) instead of the regular
     37application, the `application` is used.
     42The WSGI_APPLICATION configuration setting points to an actual WSGI
     43application.  By default the project generator will configure that a file
     44called `projectname.wsgi` exists and contains a global variable named
     45`application`. The contents look like this::
     47    from django.core.handlers.wsgi import application
     49This can be used to apply WSGI middlewares::
     51    from helloworld.wsgi import HelloWorldApplication
     52    application = HelloWorldApplication(application)
     54Of course usually you would have an actual Django WSGI application there, but
     55it also might make sense to replace the whole Django WSGI application with
     56a custom one that later delegates to the Django one (for instance if you
     57want to combine a Django application with an application of another framework).
     60from __future__ import with_statement
    161import sys
    262from threading import Lock
    except ImportError: 
    868from django import http
    969from django.core import signals
     70from django.core.exceptions import ImproperlyConfigured
    1071from django.core.handlers import base
    1172from django.core.urlresolvers import set_script_prefix
    1273from django.utils import datastructures
    1374from django.utils.encoding import force_unicode, iri_to_uri
     75from django.utils.importlib import import_module
    1476from django.utils.log import getLogger
    1678logger = getLogger('django.request')
    class WSGIRequest(http.HttpRequest): 
    190252    FILES = property(_get_files)
    191253    REQUEST = property(_get_request)
    193256class WSGIHandler(base.BaseHandler):
    194257    initLock = Lock()
    195258    request_class = WSGIRequest
    197260    def __call__(self, environ, start_response):
    198         from django.conf import settings
    200261        # Set up middleware if needed. We couldn't do this earlier, because
    201262        # settings weren't available.
    202263        if self._request_middleware is None:
    class WSGIHandler(base.BaseHandler): 
    242303        start_response(status, response_headers)
    243304        return response
     306application = WSGIHandler()
     309class DjangoWSGIApplication(object):
     310    """
     311    Implements a proxy to the actual WSGI application as configured
     312    by the user in settings.WSGI_APPLICATION which will usually be the
     313    `application`, optionally with middlewares applied.
     314    """
     315    def __init__(self):
     316        self._instance = None
     317        self._instance_lock = Lock()
     319    def _load_application(self):
     320        from django.conf import settings
     321        app_path = getattr(settings, 'WSGI_APPLICATION')
     322        if app_path is None:
     323            return application
     324        try:
     325            module_name, attr = app_path.rsplit('.', 1)
     326            return getattr(import_module(module_name), attr)
     327        except (ImportError, AttributeError), e:
     328            raise ImproperlyConfigured("WSGI application '%s' could not "
     329                                       "be loaded: %s" % (app_path, e))
     331    def __call__(self, environ, start_response):
     332        # Non-atomic check, avoids taking a lock at each call of this method
     333        if self._instance is None:
     334            with self._instance_lock:
     335                # Atomic check, prevents concurrent initialization of self._instance
     336                if self._instance is None
     337                    self._instance = self._load_application()
     338        return self._instance(environ, start_response)
     340# the proxy used in deployment
     341django_application = DjangoWSGIApplication()
  • django/core/management/__init__.py

    diff --git a/django/core/management/__init__.py b/django/core/management/__init__.py
    index 1345eaf..d4b51cc 100644
    a b def setup_environ(settings_mod, original_settings_path=None): 
    392392    # way. For example, if this file (manage.py) lives in a directory
    393393    # "myproject", this code would add "/path/to/myproject" to sys.path.
    394394    if '__init__.py' in settings_mod.__file__:
    395         p = os.path.dirname(settings_mod.__file__)
     395        path = os.path.dirname(settings_mod.__file__)
    396396    else:
    397         p = settings_mod.__file__
    398     project_directory, settings_filename = os.path.split(p)
     397        path = settings_mod.__file__
     398    project_directory, settings_filename = os.path.split(path)
    399399    if project_directory == os.curdir or not project_directory:
    400400        project_directory = os.getcwd()
    401401    project_name = os.path.basename(project_directory)
    def setup_environ(settings_mod, original_settings_path=None): 
    426426    return project_directory
     429def setup_settings(path):
     430    """
     431    Configures the settings first by looking at the environment variable
     432    DJANGO_SETTINGS_MODULE or if that fail tries to find it with the
     433    given module path.
     435    Example:
     437    from django.core.management import setup_settings
     439    setup_settings(__name__)
     440    setup_settings('wsgi')
     441    setup_settings('mysite.wsgi')
     442    """
     443    try:
     444        # Check if DJANGO_SETTINGS_MODULE is already given
     445        settings_module = os.environ['DJANGO_SETTINGS_MODULE']
     446        if not settings_module:
     447            raise KeyError
     448        settings = import_module(settings_module)
     449    except KeyError:
     450        # Or try importing the settings module two levels up,
     451        # so if name is 'mysite.wsgi', it'll try 'mysite.settings'
     452        try:
     453            settings = import_module('settings', path)
     454        except ImportError:
     455            # two levels up because name contains the submodule
     456            settings = import_module('..settings', path)
     457    setup_environ(settings)
     459    # Return the settings module
     460    from django.conf import settings
     461    return settings
    428464def execute_from_command_line(argv=None):
    429465    """
    430466    A simple method that runs a ManagementUtility.
  • django/core/management/commands/runserver.py

    diff --git a/django/core/management/commands/runserver.py b/django/core/management/commands/runserver.py
    index 2e693e7..c84bf30 100644
    a b import sys 
    55import socket
    77from django.core.management.base import BaseCommand, CommandError
    8 from django.core.handlers.wsgi import WSGIHandler
     8from django.core.handlers.wsgi import django_application
    99from django.core.servers.basehttp import AdminMediaHandler, run, WSGIServerException
    1010from django.utils import autoreload
    class BaseRunserverCommand(BaseCommand): 
    3737        """
    3838        Returns the default WSGI handler for the runner.
    3939        """
    40         return WSGIHandler()
     40        return django_application
    4242    def handle(self, addrport='', *args, **options):
    4343        self.use_ipv6 = options.get('use_ipv6')
  • django/core/servers/fastcgi.py

    diff --git a/django/core/servers/fastcgi.py b/django/core/servers/fastcgi.py
    index 9f80d2b..442df44 100644
    a b def runfastcgi(argset=[], **kwargs): 
    139139        return False
    141141    # Prep up and go
    142     from django.core.handlers.wsgi import WSGIHandler
     142    from django.core.handlers.wsgi import django_application
    144144    if options["host"] and options["port"] and not options["socket"]:
    145145        wsgi_opts['bindAddress'] = (options["host"], int(options["port"]))
    def runfastcgi(argset=[], **kwargs): 
    178178        fp.write("%d\n" % os.getpid())
    179179        fp.close()
    181     WSGIServer(WSGIHandler(), **wsgi_opts).run()
     181    WSGIServer(django_application, **wsgi_opts).run()
    183183if __name__ == '__main__':
    184184    runfastcgi(sys.argv[1:])
  • docs/howto/deployment/modwsgi.txt

    diff --git a/docs/howto/deployment/modwsgi.txt b/docs/howto/deployment/modwsgi.txt
    index de3a5b6..90d7ba3 100644
    a b the details about how to use mod_wsgi. You'll probably want to start with the 
    2424Basic configuration
    27 Once you've got mod_wsgi installed and activated, edit your ``httpd.conf`` file
    28 and add::
     27Once you've got mod_wsgi installed and activated, edit your ``httpd.conf``
     28file and add::
    30     WSGIScriptAlias / /path/to/mysite/apache/django.wsgi
     30    WSGIScriptAlias / /path/to/mysite/wsgi.py
    32 The first bit above is the url you want to be serving your application at (``/``
    33 indicates the root url), and the second is the location of a "WSGI file" -- see
    34 below -- on your system, usually inside of your project. This tells Apache
    35 to serve any request below the given URL using the WSGI application defined by that file.
     32The first bit above is the url you want to be serving your application at
     33(``/`` indicates the root url), and the second is the location of a "WSGI
     34file" -- see below -- on your system, usually inside of your project. This
     35tells Apache to serve any request below the given URL using the WSGI
     36application defined by that file.
    3738Next we'll need to actually create this WSGI application, so create the file
    3839mentioned in the second part of ``WSGIScriptAlias`` and add::
    40     import os
    4141    import sys
     42    from django.core.management import setup_settings
    43     os.environ['DJANGO_SETTINGS_MODULE'] = 'mysite.settings'
     44    setup_settings(__name__)
    45     import django.core.handlers.wsgi
    46     application = django.core.handlers.wsgi.WSGIHandler()
     46    # The application object is used by the development server
     47    # as well as a WSGI server configured to use this file.
     48    from django.core.handlers.wsgi import application
    4850If your project is not on your ``PYTHONPATH`` by default you can add::
    If your project is not on your ``PYTHONPATH`` by default you can add:: 
    5153    if path not in sys.path:
    5254        sys.path.append(path)
    54 just below the ``import sys`` line to place your project on the path. Remember to
    55 replace 'mysite.settings' with your correct settings file, and '/path/to/mysite'
    56 with your own project's location.
     56just below the ``import sys`` line to place your project on the path.
     57Remember to replace 'mysite.settings' with your correct settings file,
     58and ``'/path/to/mysite'`` with your own project's location.
    5860.. _serving-files:
  • docs/howto/deployment/uwsgi.txt

    diff --git a/docs/howto/deployment/uwsgi.txt b/docs/howto/deployment/uwsgi.txt
    index 11cb51c..d3e631e 100644
    a b Starting the server 
    112112Example command line for a Web server that understand the uWSGI protocol::
    114114    uwsgi --chdir=/path/to/your/project
    115         --module='django.core.handlers.wsgi:WSGIHandler()' \
     115        --module='wsgi:application' \
    116116        --env DJANGO_SETTINGS_MODULE=settings \
    117117        --master --pidfile=/tmp/project-master.pid \
    118118        --socket= \      # can also be a file
    Example command line for a Web server that understand the uWSGI protocol:: 
    128128Django specific options are:
    130130* ``chdir``: should be the path to your project
    131 * ``module``: uwsgi module to use
     131* ``module``: WSGI module to use, probably the ``wsgi`` module which
     132  :djadmin:`startproject` creates.
    132133* ``pythonpath``: optional path to your project virtualenv
    133134* ``env``: should contain at least ``DJANGO_SETTINGS_MODULE``
Back to Top