From 4b2c04317c258c2a67aed4481c87a3b5a6880ce6 Mon Sep 17 00:00:00 2001 From: benoitc Date: Sun, 6 Mar 2011 09:59:15 +0100 Subject: [PATCH] Apply patch from Chris Lamb with minor revision. Validate models before allowing connections via gunicorn_django This prevents issues where the site is accepting connections but not all of the models have loaded yet. If your model importing has side effects (monkey-patching, etc) this can results in errors about missing attributes or features simply because the code that enables those features as not been run yet. This issue does not affect the "run_gunicorn" management command as that performs it's own model validation before allowing connections, so we are simply making this consistent here. Signed-off-by: Chris Lamb --- gunicorn/app/djangoapp.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/gunicorn/app/djangoapp.py b/gunicorn/app/djangoapp.py index a35c84a0..e8cd81b4 100644 --- a/gunicorn/app/djangoapp.py +++ b/gunicorn/app/djangoapp.py @@ -69,12 +69,31 @@ class DjangoApplication(Application): sys.stderr.flush() sys.exit(1) + def validate(self): + """ Validate models. This also ensures that all models are + imported in case of import-time side effects.""" + from django.core.management.base import CommandError + from django.core.management.validation import get_validation_errors + try: + from cStringIO import StringIO + except ImportError: + from StringIO import StringIO + + s = StringIO() + if get_validation_errors(s): + s.seek(0) + error = s.read() + sys.stderr.write("One or more models did not validate:\n%s" % error) + sys.stderr.flush() + sys.exit(1) + def load(self): from django.conf import ENVIRONMENT_VARIABLE from django.core.handlers.wsgi import WSGIHandler os.environ[ENVIRONMENT_VARIABLE] = self.settings_modname # setup environ self.setup_environ() + self.validate() return WSGIHandler() class DjangoApplicationCommand(Application):