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

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

问题描述

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

from django.core 导入管理management.call_command('syncdb',interactive=False)

将它放在 settings.py 中不起作用,因为它需要已经加载设置.

将它们放在视图中并从外部访问该视图也不起作用,因为有一些中间件会使用数据库,而这些中间件会失败并且不允许我访问该视图.

将它们放在中间件中是可行的,但每次访问我的应用程序时都会调用它.一个可能的解决方案可能是创建一个完成所有工作的中间件,然后将自身从 MIDDLEWARE_CLASSES 中删除,以便不再调用它.我可以在没有太多猴子补丁的情况下做到这一点吗?

解决方案

编写在 __init__ 中执行此操作的中间件,然后从__init__,django 会为所有请求移除它:).顺便说一下,__init__ 在启动时调用,而不是在第一次请求时调用,因此它不会阻止您的第一个用户.

有关于添加启动信号的讨论,但不会很快可用(例如,一个主要问题是应该何时发送此信号)

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

更新: Django 1.7 包含对此的支持.(文档,由票证链接)

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)

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.

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?

解决方案

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)

Related Ticket: https://code.djangoproject.com/ticket/13024

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

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

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