Python Django全局变量 [英] Python Django Global Variables

查看:219
本文介绍了Python Django全局变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在Django中寻找简单但推荐的方式来将变量存储在内存中。当Apache重新启动或Django开发服务器重新启动时,变量将重置为0.更具体来说,我想计算每个模型实例(数据库记录)上发生特定操作的次数,但是出于性能原因,不想将这些计数存储在数据库中。我不在乎服务器重新启动后计数是否消失。但是,只要服务器启动,我希望Django shell和Web界面之间保持一致,我希望能够返回每个模型实例发生的动作多少次。

I'm looking for simple but recommended way in Django to store a variable in memory only. When Apache restarts or the Django development server restarts, the variable is reset back to 0. More specifically, I want to count how many times a particular action takes place on each model instance (database record), but for performance reasons, I don't want to store these counts in the database. I don't care if the counts disappear after a server restart. But as long as the server is up, I want these counts to be consistent between the Django shell and the web interface, and I want to be able to return how many times the action has taken place on each model instance.

我不希望变量与用户或会话相关联,因为我可能希望在没有登录的情况下返回这些计数(我想让计数器无论用户登录什么都一致)。我是否描述了一个全局变量?如果是,在Django中如何使用它?我注意到像urls.py,settings.py和models.py这样的文件似乎每个服务器启动仅被解析一次(与views.py似乎被解析为eache时间的请求相反)。这是否意味着我应该在其中一个文件中声明我的变量?或者我应该以某种方式将其存储在模型属性中(只要服务器正在运行)这可能是一个容易的问题,但我只是不知道如何在Django中完成。

I don't want the variables to be associated with a user or session because I might want to return these counts without being logged in (and I want the counts to be consistent no matter what user is logged in). Am I describing a global variable? If so, how do I use one in Django? I've noticed the files like the urls.py, settings.py and models.py seems to be parsed only once per server startup (by contrast to the views.py which seems to be parsed eache time a request is made). Does this mean I should declare my variables in one of those files? Or should I store it in a model attribute somehow (as long as it sticks around for as long as the server is running)? This is probably an easy question, but I'm just not sure how it's done in Django.

任何意见或建议都非常感激。
谢谢,
Joe

Any comments or advice is much appreciated. Thanks, Joe

推荐答案

不能声明全局变量。如果完成,设置(常量)就OK了。但变量违反了共享的架构,可能会导致很多麻烦。 (最好的情况是他们会不一致)

You mustn't declare global variables. Settings (constants) are OK if done right. But variables violate with shared-nothing architecture and might cause a lot of trouble. (best case they'll be inconsistent)

我只会将这些统计信息存储在缓存中。 (嗯,实际上我会将它们存储在数据库中,但是你明确表示你相信会对性能产生负面影响,所以...)

I would simply store those statistics in the cache. (Well, actually I would store them in the database but you made clear you believe it will have a negative impact on performance, so...)

新的 incr() decr()方法特别适合计数。有关更多信息,请参见文档

The new incr() and decr() methods are especially suitable for counting. See docs for more info.

这篇关于Python Django全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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