一、背景
之前的一个老项目,需求是服务器启动的时候检查数据库视图是否创建,如果没有就进行创建,这个函数之前是在view.py或者在url.py中调用,网上查资料大部分也是这样介绍的,此方式如果使用django自带的服务也没啥问题,但是如果使用uwsgi等多进程服务就会出现问题,这个函数会根据进程数量重复执行。
二、解决方式
方式一:重写AppConfig.ready()
# demo1
from django.apps import AppConfig
from django.db.models.signals import pre_save
class RockNRollConfig(AppConfig):
# ...
def ready(self):
# importing model classes
from .models import MyModel # or...
MyModel = self.get_model('MyModel')
# registering signals with the model's string label
pre_save.connect(receiver, sender='app_label.MyModel')
# demo2
# my_app/apps.py
from django.apps import AppConfig
class MyAppConfig(AppConfig):
name = 'My App'
def ready(self):
# put your startup code here
方式二:自定义启动命令
# 新建文件
yourapp/management/commands/startup.py
from django.core.management.base import BaseCommand, CommandError
class Command(BaseCommand):
help = 'My custom startup command'
def handle(self, *args, **kwargs):
try:
# put startup code here
except:
raise CommandError('Initalization failed.')
# 执行命令
python manage.py startup
参考文章:
aweafvdfa
csdf
rqasfd