Login

Make runfcgi fail when database connection is open before fork

Author:
mpasternacki
Posted:
March 11, 2011
Language:
Python
Version:
Not specified
Score:
0 (after 0 ratings)

FastCGI handler in prefork mode first imports every application, then forks. If any application during import opens connection to database, open connection is inherited by all of child processes; open db connection cannot be shared between processes, and if one process sends a request, another can receive a reply; also, if one process closes it, others have a desynchronized database handle.

See: http://stackoverflow.com/questions/1573579/psycopg2-disconnects-from-server http://stackoverflow.com/questions/393637/django-fastcgi-randomly-raising-operationalerror http://code.djangoproject.com/ticket/13215 http://groups.google.com/group/django-users/browse_thread/thread/2c7421cdb9b99e48

If you put this snippet in your project-level init.py, then running manage.py runfcgi will fail loudly if the database connection is open in the parent process. This will happen only when you provide debug=true option to runfcgi to avoid monkey-patching code that runs in production mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
# monkey-patch flup to fail loudly if database connection is open when
# preforked child starts - but ONLY when debug=true, so that we don't
# use monkey-patch on production.
import sys
if 'runfcgi' in sys.argv and 'debug=true' in sys.argv:
    from flup.server.preforkserver import PreforkServer
    def _spawnChild(self, sock):
        from django.db import connection
        if connection.connection is not None:
            raise Exception('''Django database connection is open. This MAY NOT happen.''')
        return self._spawnChild_orig(sock)
    PreforkServer._spawnChild_orig = PreforkServer._spawnChild
    PreforkServer._spawnChild = _spawnChild

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 2 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 2 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 9 months, 2 weeks ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 10 months, 1 week ago
  5. Help text hyperlinks by sa2812 11 months ago

Comments

Please login first before commenting.