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

查看:34
本文介绍了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 这样的文件似乎在每次服务器启动时只被解析一次(与 view.py 相比,它似乎在每次发出请求时都被解析).这是否意味着我应该在这些文件之一中声明我的变量?或者我应该以某种方式将它存储在模型属性中(只要它在服务器运行期间一直存在)?这可能是一个简单的问题,但我不确定它是如何在 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.

非常感谢任何评论或建议.谢谢,乔

Any comments or advice is much appreciated. Thanks, Joe

推荐答案

不得声明全局变量.如果操作正确,设置(常量)就可以了.但是变量违反了shared-nothing 架构,可能会导致很多麻烦.(最好的情况是它们会不一致)

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天全站免登陆