Skip to content

Instantly share code, notes, and snippets.

@max-arnold
Forked from rbarrois/wsgi.py
Created July 7, 2018 04:47
Show Gist options
  • Select an option

  • Save max-arnold/fac525b7ade499a76a0c3df25e183bf8 to your computer and use it in GitHub Desktop.

Select an option

Save max-arnold/fac525b7ade499a76a0c3df25e183bf8 to your computer and use it in GitHub Desktop.

Revisions

  1. @rbarrois rbarrois created this gist May 25, 2018.
    59 changes: 59 additions & 0 deletions wsgi.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,59 @@
    # -*- coding: utf-8 -*-

    import io
    import os
    import sys
    import time
    import wsgiref.util

    import uwsgidecorators


    DJANGO_WARMUP_URL = os.environ.get('DJANGO_WARMUP_URL', '')

    app = None


    @uwsgidecorators.postfork
    def setup_postfork():
    """Ensure each worker is warm *after* fork as well."""
    # Warmup as well
    warmup_django()


    def warmup_django(close_connections=False):
    from django.conf import settings
    if settings.ALLOWED_HOSTS:
    host = settings.ALLOWED_HOSTS[0].replace('*', 'warmup')
    else:
    host = 'localhost'
    env = {
    'REQUEST_METHOD': 'GET',
    'PATH_INFO': DJANGO_WARMUP_URL,
    'SERVER_NAME': host,
    'wsgi.error': sys.stderr,
    }
    # Setup the whole wsgi standard headers we do not care about.
    wsgiref.util.setup_testing_defaults(env)

    def start_response(status, response_headers, exc_info=None):
    assert status == "200 OK"
    fake_socket = io.BytesIO()
    return fake_socket

    global app
    app(env, start_response)

    if close_connections:
    # Close connections before forking
    from django.db import connections
    for conn in connections.all():
    conn.close()


    def get_wsgi_application():
    from django.core import wsgi
    global app = wsgi.get_wsgi_application()
    if DJANGO_WARMUP_URL:
    warmup_django(close_connections=True)
    return app