在哪里放Django启动代码? [英] Where to put Django startup code?

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

问题描述

我想在服务器启动(开发和生产)上执行这些代码行:

I'd like to have these lines of code executed on server startup (both development and production):

from django.core import management
management.call_command('syncdb', interactive=False)

它在 settings.py 中不起作用,因为它需要设置才能加载。

Putting it in settings.py doesn't work, as it requires the settings to be loaded already.

将它们在外部查看和访问该视图也不起作用,因为有一些使用数据库的中间件,那些将失败,不让我访问视图。

Putting them in a view and accessing that view externally doesn't work either, as there are some middlewares that use the database and those will fail and not let me access the view.

把它们放在一个中间件中可以工作,但每次访问我的应用程序时都会调用它。一个可能的解决方案可能是创建一个完成所有工作的中间件,然后从 MIDDLEWARE_CLASSES 中删除​​它,因此它不再被调用。可以在没有太多猴子修补的情况下执行此操作吗?

Putting them in a middleware would work, but that would get called each time my app is accessed. An possible solution might be to create a middleware that does all the job and then removes itself from MIDDLEWARE_CLASSES so it's not called anymore. Can I do that without too much monkey-patching?

推荐答案

__ init __ ,然后从 __ init __ 中引用 django.core.exceptions.MiddlewareNotUsed ,django将其删除对于所有请求:)。 __ init __ 在启动时被调用,而不是在第一个请求,所以它不会阻止您的第一个用户。

Write middleware that does this in __init__ and afterwards raise django.core.exceptions.MiddlewareNotUsed from the __init__, django will remove it for all requests :). __init__ is called at startup by the way, not at the first request, so it won't block your first user.

有关于添加启动信号的说法,但是不久以后就可以使用(例如,一个主要问题是发送此信号)

There is talk about adding a startup signal, but that won't be available soon (a major problem for example is when this signal should be sent)

相关机票: https://code.djangoproject.com/ticket/13024

更新: Django 1.7包括对此的支持。 (文档,由票)

Update: Django 1.7 includes support for this. (Documentation, as linked by the ticket)

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

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