【发布时间】: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