如何在flask应用程序python中重新初始化全局变量

问题描述 投票:0回答:1

这是 Flask app.py

from flask import Flask, redirect, url_for, request
import trainer
app = Flask(__name__)
 

@app.route('/success/<name>')
def success(name):
    gValue = trainer.myFunction()
    name = name + gValue
    return 'welcome %s' % name
 
 
@app.route('/login', methods=['POST', 'GET'])
def login():
    if request.method == 'POST':
        user = request.form['nm']
        return redirect(url_for('success', name=user))
    else:
        user = request.args.get('nm')
        return redirect(url_for('success', name=user))
 
 
if __name__ == '__main__':
    app.run(debug=True, threaded=True, use_reloader=False)

HTML 文件

<html>
<body>   
    <form action = "http://localhost:5000/login" method = "post">
<p>Enter Name:</p>
<p><input type = "text" name = "nm" /></p>
<p><input type = "submit" value = "submit" /></p>
    </form>  
</body>
</html>

培训师.py

from utils import sumValue

def myFunction():
   pullValue = sumValue()
   return pullValue

utils.py

aggregateValue = " defaultValue"

def sumValue():
    global aggregateValue
    x = " mainValue"
    x1 = x + aggregateValue
    aggregateValue = " modifiedValue"
    x2 = x1 + aggregateValue
    print(x2)
    return x2

运行应用程序

C:\test>python app.py
 * Serving Flask app 'app'
 * Debug mode: on
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:5000
Press CTRL+C to quit
127.0.0.1 - - [09/Jan/2024 16:12:57] "POST /login HTTP/1.1" 302 -
 mainValue defaultValue modifiedValue
127.0.0.1 - - [09/Jan/2024 16:12:57] "GET /success/Value HTTP/1.1" 200 -
127.0.0.1 - - [09/Jan/2024 16:15:59] "POST /login HTTP/1.1" 302 -
 mainValue modifiedValue modifiedValue
127.0.0.1 - - [09/Jan/2024 16:15:59] "GET /success/Value HTTP/1.1" 200 -

在第一次运行中我们得到

主值默认值修改值

第二轮

主值修改值修改值

由于第二次运行是全新运行,我希望中间值应该是defaultValue而不是modifiedValue,

utils.py 中的全局声明在第二次运行期间未初始化,

如果我们按Ctrl+C并重新开始,内存将被清除以获取defaultValue

我可以知道如何在这里初始化全局变量吗?

python flask
1个回答
0
投票

从我在您的代码中看到的,您可以添加一行来重置变量,您可以在完成 sumValue() 函数之前执行此操作。

aggregateValue = " defaultValue"

def sumValue():
    global aggregateValue
    x = " mainValue"
    x1 = x + aggregateValue
    aggregateValue = " modifiedValue"
    # Print the variable [MOD]
    print("===> " + aggregateValue)
    x2 = x1 + aggregateValue
    print(x2)
    aggregateValue = " defaultValue"
    # Print the variable [RESET]
    print("$$$$> " + aggregateValue)
    return x2
© www.soinside.com 2019 - 2024. All rights reserved.