Created
May 25, 2018 13:46
-
-
Save rbarrois/044b2d9f7052a6542f7a3d79695d64c6 to your computer and use it in GitHub Desktop.
Django uWSGI warmup
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- 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