我试图在单击按钮时打印随机值start
并通过单击按钮停止它stop
。该Start
按钮按预期工作,即在单击时打印随机值,但是当stop
单击按钮时,它不会跳出循环(尽管它进入该stop
部分)并继续打印随机值。如何停止打印随机值并重新开始。?
我的代码的简短摘要:- 在 views.py 中,signal
请求变量,然后将其发送到generate_random_temperature
生成随机数的函数。生成数字工作正常,但它无法停止生成数字的服务。
我怎样才能阻止它?
HTML 文件
<form type = "POST">
{% csrf_token %}
<input type="text" placeholder = "Enter City Name" id = "city_name">
<input type="submit" value = "start" id="submit">
<input type="reset" value = "Stop" id="stop">
</form>
JS文件
$(function(){
$("#start").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard/",
data : { 'city_name' : $("#city_name").val(),
'signal' : "True"
},
});
});
$("#stop").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "/dashboard/",
data : { 'city_name' : $("#city_name").val(),
'signal' : "False"
},
});
});
});
服务.py
def generate_random_temperature(city_name, status):
city = City.objects.filter(city_name = city_name)
for data in city:
status = data.status
print status
if status == "True" :
while(1):
print randrange(1,51)
time.sleep(5)
elif status == "False" :
print "Exiting"
视图.py
def dashboard(request):
if request.is_ajax():
status = request.POST['status']
city_name = request.POST['city_name']
city = City.objects.filter(city_name = city_name)
for data in city:
data.status = status
data.save()
generate_random_temperature(city_name, status)
ctx = {}
return render_to_response('dashboard/dashboard.html',ctx, context_instance = RequestContext(request))
输出
True // When Start button is clicked, service is started
25
13
False // When Stop button is clicked, it enters the else section, prints Exiting , but then again starts printing numbers. It does not breaks out of the while loop.
Exiting
[23/Aug/2013 05:38:33] "POST /dashboard/ HTTP/1.1" 200 2363
45
25
26
31