Instantly share code, notes, and snippets.

Embed
What would you like to do?
Django uWSGI warmup
# -*- 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment