如何*不*在syncdb上运行Django代码
我有一些服务器启动代码位于我的 Django 应用程序之一的“models.py”中。我需要在服务器启动时运行该代码。
问题是,该代码发出 SQL 查询,这阻止我使用 psycopg2
运行 syncdb
(它会破坏事务,并且不会创建表。
)中间件并引发 django.core.exceptions.MiddlewareNotUsed 并不是最佳选择,因为我也希望在 Django shell 中产生效果(并且将初始化代码放在中间件中无论如何听起来都不正确。 )此外,我需要等待第一个请求才能执行此操作。我想在服务器启动时运行代码,而不是在第一个客户访问我的网站时运行代码。
服务器启动信号在 Django 中仍未实现,因此这不是一个选项。
因此,我想以某种方式:
- 检查 Django 是否正在运行同步数据库,所以我不执行查询,
- 或者检查相应的表是否存在,如果不存在,那么也只是不要做任何查询
我在任何文档中都没有找到上述两个选项。我该怎么做?或者有更好的(即理智的)方式来做我想做的事吗?
I have some server startup code that is lying in the "models.py" of one of my Django apps. I need to run that code on server startup time.
The problem is, that code issues a SQL query, which prevents me from running syncdb
with psycopg2
(it breaks the transaction, and tables are not created.)
Putting the code in a middleware and raising django.core.exceptions.MiddlewareNotUsed
is not optimal as I'd like to have the effect in the Django shell too (and putting initialization code in a middleware doesn't sound right anyway.) Also I'd need to wait for the first request to do that. I want to run code on server startup, not when the first customer comes knocking on my website.
Server startup signals are still not implemented in Django, so that's not an option.
Thus, I'd like to somehow either:
- check if Django is running a syncdb, so I don't do the queries,
- or, alternatively, check it the corresponding tables are there, and if they are not, then, too, just don't do any queries
Non of the above two options have I found in any of the documentation. How do I do that? Or is there a better (i.e. sane) way of doing what I want to do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Django 还应该在启动时加载 urls.py;我无法告诉您这是否适合您的代码,但如果您愿意,请尝试一下!
Django should also load
urls.py
on startup; I cannot tell you if that's a suitable place for your code, but give it a try if you want to!您是否考虑过连接到
post_syncdb
< /a> 信号?也许您可以在收到此信号时运行自定义 SQL。这可能会解决您的部分问题;您仍然需要弄清楚如何在服务器启动时运行 SQL。Have you considered connecting to the
post_syncdb
signal? Perhaps you can run the custom SQL on receiving this signal. This may solve on part of your problem; you still have to figure out how to run the SQL on server startup.您可以在settings.py中进行检查:
然后
You can put a check in settings.py:
Then
一些异常处理怎么样?当执行查询但数据库表不存在时,会引发 Django.db.utils.DatabaseError 。尝试..除了我认为查询代码是满足你的第二个标准的方式。
问题:
models.py
解决方案:
模型.py
How about a bit of exception handling? When doing a query but the database table does not exist, a
Django.db.utils.DatabaseError
is raised. Try..except the query code is the way of meeting your second criteria as I think.Problem:
models.py
Solution:
models.py