Django multiprocessing and database connections

前端 未结 9 847
挽巷
挽巷 2020-11-28 03:16

Background:

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 m

9条回答
  •  离开以前
    2020-11-28 04:06

    For Python 3 and Django 1.9 this is what worked for me:

    import multiprocessing
    import django
    django.setup() # Must call setup
    
    def db_worker():
        for name, info in django.db.connections.databases.items(): # Close the DB connections
            django.db.connection.close()
        # Execute parallel code here
    
    if __name__ == '__main__':
        multiprocessing.Process(target=db_worker)
    

    Note that without the django.setup() I could not get this to work. I am guessing something needs to be initialized again for multiprocessing.

提交回复
热议问题