首页 > 解决方案 > 在 Django 中将自定义函数放在哪里?

问题描述

在我的models.py 中有这个类。

import time

class Ticket(models.Model):
    username = models.CharField(max_length=50)
    booking_time = time.time()
    expired = models.BooleanField(default=False)

我希望过期的布尔值在 1 小时后变为真,booking_time但我不知道我应该在哪里检查同样的事情(我想在其中创建函数,views.py但只有在我们去的时候才会调用视图到某个 URL,就我而言,我想每小时检查一次)。

标签: pythondjangodjango-modelsdjango-views

解决方案


如果你想在 django 的后台运行脚本之类的东西,你可以在你的 app 文件夹中创建例如 script.py。在该代码中,您甚至可以拥有

def main()
    while True:
       ....

然后你必须去 wsgi.py(在你的项目文件夹中)并导入你的脚本。所以它会像

import os
import threading

from django.core.wsgi import get_wsgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'weather_raspi.settings')


t = threading.Thread(target=main, args=(args)) #here will you give the function as task and arguments into args
t.start() #this line starts the function
application = get_wsgi_application()

这对你来说应该可以正常工作希望你这次能得到它


推荐阅读