Execute code when Django starts ONCE only?

前端 未结 7 1487
终归单人心
终归单人心 2020-11-22 13:55

I\'m writing a Django Middleware class that I want to execute only once at startup, to initialise some other arbritary code. I\'ve followed the very nice solution posted by

7条回答
  •  情书的邮戳
    2020-11-22 14:45

    This question is well-answered in the blog post Entry point hook for Django projects, which will work for Django >= 1.4.

    Basically, you can use /wsgi.py to do that, and it will be run only once, when the server starts, but not when you run commands or import a particular module.

    import os
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "{{ project_name }}.settings")
    
    # Run startup code!
    ....
    
    from django.core.wsgi import get_wsgi_application
    application = get_wsgi_application()
    

提交回复
热议问题