简体   繁体   English

带有Apache的Django:view.py中的全局变量

[英]Django with Apache : Global variable in view.py

please I need some help, I have a web application with classic functionalities for users management (account creation, login,...). 请给我一些帮助,我有一个具有经典功能的Web应用程序,用于用户管理(帐户创建,登录等)。 my problem is that I am trying to creat an instance of an object "UserObject" (not serializable object) for each user when he connects (login), this object will be used to process user requests in some views, so the object must be accessible from any view, for that i have a global dictionary "users_objects" in view.py that contains all users objects (the dictionary key is the user name and the value is the "UserObject" object), so view.py look lik this : 我的问题是我试图为每个用户在连接(登录)时为每个用户创建一个对象“ UserObject”(不是可序列化的对象)的实例,该对象将用于在某些视图中处理用户请求,因此该对象必须是从任何视图均可访问,因为我在view.py中拥有一个包含所有用户对象的全局字典“ users_objects”(字典键是用户名,值是“ UserObject”对象),因此view.py看起来很像:

from user_object import UserObject

users_objects = {}

def login(request):

    //login control and creation of session and context
    ......
    ......
    global users_objects
    user_name = request.session['name']
    users_objects[user_name] = UserObject()
    return render(request, 'mySite/home.html', context)

def request_view(request):

    param = request.GET.get('parameter', None)
    global users_objects
    user_name = request.session['name']
    obj = users_objects[user_name]
    res = obj.process(param)
    return HttpResponse(str(res))

This approach work fine with django dev-server, but when I configure django with a real production server (apache) the content of the global dictionary "users_objects" disappear and I get an empty dictionary. 这种方法在django dev-server上可以正常工作,但是当我用实际的生产服务器(apache)配置django时,全局字典“ users_objects”的内容消失了,我得到了一个空字典。 please, did anyone know why does this happen ?? 请,有人知道为什么会这样吗? and what is the best solution to use a global dictionary in django ?? 在Django中使用全局字典的最佳解决方案是什么? thank you in advance 先感谢您

The reason this is happening is because mod_wsgi is running your app with multiple processes, each of which have their own variable space. 发生这种情况的原因是因为mod_wsgi使用多个进程运行您的应用程序,每个进程都有自己的可变空间。

But there is no good reason to do this. 但是没有充分的理由这样做。 Data is stored in the database, don't put it in global objects. 数据存储在数据库中,请勿将其放在全局对象中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM