开发者

Where should I place the one-time operation operation in the Django framework?

I want to perform some one-time operations such as to start a background thread and populate a cache every 30 minutes as initialize action when the Django server is started, so it will not block user from visiting the website. Where should I place all this code in Django?

  • Put them into the setting.py file does not work. It seems it will cause a circular dependency.
  • Put them into the __init__.py file does not work.开发者_如何学编程 Django server call it many times (What is the reason?)


I just create standalone scripts and schedule them with cron. Admittedly it's a bit low-tech, but It Just Works. Just place this at the top of a script in your projects top-level directory and call as needed.

#!/usr/bin/env python
from django.core.management import setup_environ
import settings
setup_environ(settings)
from django.db import transaction

# random interesting things
# If you change the database, make sure you use this next line
transaction.commit_unless_managed()


We put one-time startup scripts in the top-level urls.py. This is often where your admin bindings go -- they're one-time startup, also.

Some folks like to put these things in settings.py but that seems to conflate settings (which don't do much) with the rest of the site's code (which does stuff).


For one operation in startserver, you can use customs commands or if you want a periodic task or a queue of taske you can use celery


__init__.py will be called every time the app is imported. So if you're using mod_wsgi with Apache for instance with the prefork method, then every new process created is effectively 'starting' the project thus importing __init__.py. It sounds like your best method would be to create a new management command, and then cron that up to run every so often if that's an option. Either that, or run that management command before starting the server. You could write up a quick script that runs that management command and then starts the server for instance.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜