How to avoid AppConfig.ready() method running twice in Django

前端 未结 4 1679
野性不改
野性不改 2020-12-05 06:32

I want to execute some code at startup of Django server but I want it to run only once. Currently when I start the server it\'s executed twice. Documentation says that this

4条回答
  •  有刺的猬
    2020-12-05 06:55

    You need to implement locking. It is not a simple problem and the solution will not feel natural as you are dealing with processes and threads. Be warned there are many answers to the problem of locking, some simpler approaches:

    A file lock: Ensure a single instance of an application in Linux (note that threads share file lock by default so this answer needs to be expanded to account for threads).

    There is also this answer which uses a Python package called tendo that encapsulates the a file lock implementation: https://stackoverflow.com/a/1265445/181907

    Django itself provides an abstracted portable file locking utility in django.core.files.locks.

提交回复
热议问题