0

having an issue with a Flask app I'm working on.

The global variable named buttonNum is supposed to be changed with each calling of button(); however, buttonNum in ardCom() remains unaffected, not acknowledging the changes made to it with button(). I have found examples online on how to use globals and this should work from what I know.

I appreciate any and all help. Thanks

import time
import json
import serial
import flask
from multiprocessing import Process
from flask import Flask, request, render_template, make_response

buttonNum = 0
app = Flask(__name__)

@app.route('/')
def default():
    headers = {'Content-Type': 'text/html'}
    return make_response(render_template('index.html'),200,headers)

@app.route('/setup', methods=['POST'])
def setup():
    data = request.get_json
    return {'result' : "Success"}

@app.route('/button', methods=['POST'])
def button():
    global buttonNum
    buttonNum= int(request.form['number'])
    typeOf = int(request.form['type'])
    value = int(request.form['value'])
    return "success"

def ardCom():
    global buttonNum
    county = 1
    ph = b''
    ph = ser.read()

    if ph == b'S':
        ser.write(ph)
        while (ph != b'E'):
            ph = ser.read()
            if ph == b'E':
                ser.write(ph)
                break
            #print(str(buttonNum))
            if ph == b'\x00' and buttonNum != county:
                writeOut(b'\x00')
                county += 1
            if ph  == b'\x01' or buttonNum == county:
                writeOut(b'\x01')
                print("Button", end = " ")
                print(county, end = " ")
                print("has been pressed.")
                county += 1

def writeOut(datByte):
    ser.write(datByte)

def runApi():
    app.run(host='0.0.0.0')

if __name__  == '__main__':
    ser = serial.Serial('/dev/ttyACM0', 9600, timeout=1)
    ser.flush()
    time.sleep(1)
    apiProcess = Process(target=runApi)
    apiProcess.start()
    while True:
        ardCom()
  • 1
    Are you sure there is only once instance of the flask app running? Many webservers will spin up several instances of an app as a primitive load-balancing solution. – John Gordon Jun 11 '20 at 19:11
  • 1
    Global variables are not safe for multi threaded application that run in web server. You can check this answer for details: https://stackoverflow.com/a/49664342/3129414 – arshovon Jun 11 '20 at 19:31

1 Answers1

0

When a flask server runs, it might runs some instances. To make your code works, you could store the value in a file(like json) or in a database.

Agung Wiyono
  • 377
  • 3
  • 8