【问题标题】:Python: Global variable isn't getting affected/changed by functionPython:全局变量不会受到函数的影响/更改
【发布时间】:2020-06-11 19:06:40
【问题描述】:

我正在开发的 Flask 应用程序出现问题。

名为 buttonNum 的全局变量应该随着 button() 的每次调用而改变;但是,ardCom() 中的 buttonNum 不受影响,不承认使用 button() 对其所做的更改。我在网上找到了有关如何使用全局变量的示例,这应该根据我所知道的情况起作用。

我感谢任何和所有的帮助。 谢谢

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

【问题讨论】:

  • 您确定只有一次烧瓶应用实例在运行吗?许多网络服务器将启动应用程序的多个实例作为原始负载平衡解决方案。
  • 全局变量对于在 Web 服务器中运行的多线程应用程序是不安全的。您可以查看此答案以获取详细信息:stackoverflow.com/a/49664342/3129414

标签: python loops flask global-variables global


【解决方案1】:

当烧瓶服务器运行时,它可能会运行一些实例。为了使您的代码有效,您可以将值存储在文件(如 json)或数据库中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-10-02
    • 1970-01-01
    • 2021-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-16
    • 1970-01-01
    相关资源
    最近更新 更多