在Django 1.7中启动时执行代码 [英] Executing code on startup in Django 1.7

查看:126
本文介绍了在Django 1.7中启动时执行代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

似乎Django允许在启动时执行代码 - 当应用程序启动时,然而,它不清楚,我应该在哪里放置代码。那么如何在Django 1.7中启动时执行代码?

It seems Django allows to execute the code on startup - when the app starts, however, it's not clear and where I should put the code. So how can I execute the code on startup in Django 1.7?

推荐答案

对于Django> = 1.7,你可以使用 AppConfig.ready()回调:

For Django>=1.7 you can use the AppConfig.ready() callback:

https://docs.djangoproject.com/en/dev/ref/applications/#django.apps.AppConfig.ready

对于以前的版本,请参阅此答案

For previous versions, see this answer.

如果您正在使用 AppConfig.ready()方法:

1)创建一个 myapp / apps.py 模块并对AppConfig进行子类化。例如:

1) Create a myapp/apps.py module and subclass the AppConfig. For example:

from django.apps import AppConfig

class MyAppConfig(AppConfig):
    def ready(self):
    ...

2)编辑 myapp / __ init __。py 并注册您的应用配置:

2) Edit myapp/__init__.py and register your app config:

default_app_config = 'myapp.apps.MyAppConfig'

请参阅 https://docs.djangoproject.com/en/1.7/ref/applications/#configuring-applications 了解详情。

这篇关于在Django 1.7中启动时执行代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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