title: Django multiprocessing and database connections
body: <p>Background:</p>
  
  <p>I'm working a project which uses Django with a Postgres database.  We're also using mod_wsgi in case that matters, since some of my web searches have made mention of it.  On web form submit, the Django view kicks off a job that will take a substantial amount of time (more than the user would want to wait), so we kick off the job via a system call in the background.  The job that is now running needs to be able to read and write to the database.  Because this job takes so long, we use multiprocessing to run parts of it in parallel.</p>
  
  <p>Problem:</p>
  
  <p>The top level script has a database connection, and when it spawns off child processes, it seems that the parent's connection is available to the children.  Then there's an exception about how SET TRANSACTION ISOLATION LEVEL must be called before a query.  Research has indicated that this is due to trying to use the same database connection in multiple processes.  One thread I found suggested calling connection.close() at the start of the child processes so that Django will automatically create a new connection when it needs one, and therefore each child process will have a unique connection - i.e. not shared.  This didn't work for me, as calling connection.close() in the child process caused the parent process to complain that the connection was lost.</p>
  
  <p>Other Findings:</p>
  
  <p>Some stuff I read seemed to indicate you can't really do this, and that multiprocessing, mod_wsgi, and Django don't play well together.  That just seems hard to believe I guess.</p>
  
  <p>Some suggested using celery, which might be a long term solution, but I am unable to get celery installed at this time, pending some approval processes, so not an option right now.</p>
  
  <p>Found several references on SO and elsewhere about persistent database connections, which I believe to be a different problem.</p>
  
  <p>Also found references to psycopg2.pool and pgpool and something about bouncer. Admittedly, I didn't understand most of what I was reading on those, but it certainly didn't jump out at me as being what I was looking for.</p>
  
  <p>Current "Work-Around":</p>
  
  <p>For now, I've reverted to just running things serially, and it works, but is slower than I'd like.</p>
  
  <p>Any suggestions as to how I can use multiprocessing to run in parallel?  Seems like if I could have the parent and two children all have independent connections to the database, things would be ok, but I can't seem to get that behavior.</p>
  
  <p>Thanks, and sorry for the length!</p>