【问题标题】:How to use different global variable for different browser sessions in Django website如何在 Django 网站中为不同的浏览器会话使用不同的全局变量
【发布时间】:2013-07-11 02:54:05
【问题描述】:

我正在尝试计算我的 Django 网站。我使用全局变量 testc 进行计数(我知道这会导致问题,但我不知道如何在没有全局变量的情况下进行计数)。所以如果两个浏览器同时打开网站(threadtest.html),它们都会增加相同的testc(当然)。有没有办法在每个浏览器会话中单独计数?我需要使用多线程吗?谢谢。

这是我的看法:

testc=0
def threadtest(request):
    global testc
    if request.method == 'POST':
        testc=testc+1
        print testc
    return render(request,'threadtest.html',{'count':testc,})

这是模板: base.html

{% load staticfiles %}
{% load static %}
{% load extra_tags %}
<html>
<head>
<title>{% block title %}{% endblock %}</title>


{%block myscripts %}{% endblock %}

</head>
<body>
<div id="content">
    {% block content %}{% endblock %}
</div>

</body>
</html>

threadtest.html

{% extends 'base.html' %}
<html>
<head><title></title></head>

<body>

{% block content %}
<h1> Current count is </h1>
<h1> {{count}} </h1>
<form action="/threadtest/" method="post">{% csrf_token %}
<input type= "submit" name = "button" value = "addit" />
</form>
{% endblock %}
</body>
</html>

【问题讨论】:

  • 后来我通过使用“会话变量”得到了这个。比如 request.session('myvar')=xxxx.

标签: django multithreading global counting


【解决方案1】:

您可以从以下位置获取该信息:

request.META['HTTP_USER_AGENT']

一些输出将是例如:

   Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/28.0.1500.70 Safari/537.36

也许你会发现这个snippet对你有帮助

【讨论】:

  • 感谢您的回答。我想要做的是为每个单独的浏览器会话分配一个全局变量。这是你建议的吗?
  • 是的,您可以查看 sn-p 并根据“check_browser”函​​数的结果创建会话变量
猜你喜欢
  • 2021-03-01
  • 2014-10-26
  • 2017-09-30
  • 2014-03-02
  • 2014-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-05-02
相关资源
最近更新 更多