Kangting
Kangting

Reputation: 31

No effect on global variable

I have a problem with my code. I am creating a small web application, and I want to retrieve a value that has been entered on an html page. Therefore I use the forms. I am recovering my value in message. I imported another python file "thread.py" which contains a reception() function to assign it to a global variable "var_maman" initialized at the beginning to 0. When I run the DJango application and then run my thread.py program (it continuously displays the global variable) and I enter a value on my site, there is no change on the global variable, I don't know what to do anymore. Thank you for your help!

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())

thread.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)

Upvotes: 2

Views: 67

Answers (1)

Viktor Petrov
Viktor Petrov

Reputation: 444

You can use actual threading for your print function, calling it from your view.py.

import threading
import time

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

Then you can start the thread from your RPI view:

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

Upvotes: 1

Related Questions