Skip to main content
 首页 » 编程设计

python之对全局变量没有影响

2024年11月24日10lvdongjie

我的代码有问题。我正在创建一个小型 Web 应用程序,我想检索在 html 页面上输入的值。因此我使用表格。我正在恢复我在消息中的值(value)。我导入了另一个 python 文件“thread.py”,其中包含一个 reception() 函数,将其分配给一个全局变量“var_maman”,该变量在开始时初始化为 0。当我运行 DJango 应用程序然后运行我的 thread.py 程序(它持续显示全局变量)并且我在我的网站上输入了一个值,全局变量没有变化,我不知道该怎么办了。 感谢您的帮助!

View .py

from __future__ import unicode_literals 
from django.shortcuts import render,redirect 
from django.http import HttpResponse, Http404 
import sql 
import thread 
from .forms import ContactForm 
# Create your views here. 
 
 
def RPI(request,rpi_id): 
    if int(rpi_id) > 10: 
        return redirect("/page/accueil/") 
    Pactive = sql.run("Pactive") 
    Preactive = sql.run("Qreactive") 
    Courant = sql.run("I") 
    form = ContactForm(request.POST or None) 
    if form.is_valid():  
        message = form.cleaned_data['message'] 
        thread.reception(message) 
        print("Le message est : RPI"+rpi_id+","+message) 
        envoi = True 
 
    return render(request, 'page/RPI.html',locals()) 
 

线程.py

 
import sys 
import time 
global var_maman 
 
def reception(message): 
    global var_maman 
    print("entre dans reception") 
    var_maman = message 
 
if __name__ == '__main__': 
    global var_maman 
    var_maman=0 
 
    while True : 
        print var_maman 
        time.sleep(1) 

请您参考如下方法:

您可以为您的打印函数使用实际的线程,从您的 view.py 中调用它。

import threading 
import time 
 
def reception(message): 
    while True : 
        print message 
        time.sleep(1) 

然后您可以从 RPI View 启动线程:

reception_thread = threading.Thread(target=reception, args=(message,)) 
reception_thread.start()