我应该在Django框架中放置一次性操作? [英] Where should I place the one-time operation operation in the Django framework?

查看:128
本文介绍了我应该在Django框架中放置一次性操作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想执行一些一次性操作,如启动后台线程,并在Django服务器启动时作为初始化操作,每30分钟填充一个缓存,因此它不会阻止用户访问该网站。我应该在Django中放置所有这些代码?

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?


  • 将它们放入setting.py文件不起作用。它似乎会导致循环依赖。

  • 将它们放入 __ init __。py 文件不起作用。 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?)

推荐答案

脚本并安排它们与cron。诚然,这是一个低科技,但它只是工作。只需将其放置在项目顶层目录的脚本的顶部,并根据需要调用。

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()

这篇关于我应该在Django框架中放置一次性操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆