繁体   English   中英

Flask 中的全局变量返回未定义

[英]Variables in Flask that are global are returning not defined

大家好,我确实有脚本的这一部分:

global auth, username, password, index, authType, rotation # Frist try - doesn't work
auth, username, password, index, authType, rotation = None # Second try - doesn't work either


        
@app.route("/set", methods=["GET","POST"])
def setup():
    auth = request.args.get("auth", type=str)
    username = request.args.get("username", type=str)
    password = request.args.get("password", type=str)
    index = request.args.get("index")
    authType = request.args.get("type", type=str)
    rotation = request.args.get("rotation", type=str)
    
    print(authType)

    return anotherMethod()

def anotherMethod():
    #Do something here with authThype mentioned above.
    return "succes"

在这种情况下, authType get 是一个未定义的错误。 另外,我尝试将上面的所有变量设置为“无”,并且删除了“全局”声明,因为我想在一个请求中获取它们,然后将它们处理到其他方法中,而不将它们作为方法变量发送,但这些方法都没有工作。

你们对如何处理通过 api 调用发送到同一 .py 文件的其他方法中的变量有很好的想法吗?

您不需要使用全局变量。 request.args.get()默认为字符串,所以不需要。 试试这个来诊断:

@app.route("/set", methods=["GET","POST"])
def setup():

    auth     = request.args.get("auth")
    username = request.args.get("username")
    password = request.args.get("password")
    index    = request.args.get("index")
    authType = request.args.get("type", "no type arg sent")
    rotation = request.args.get("rotation")
    
    print(authType)
    return anotherMethod(authType)

def anotherMethod(authType=None):
    print(f"authType is {authType} inside anotherMethod()")
    return "success"

编辑:

如果你坚持使用全局变量。 你需要在函数中声明它们(如果你想在那里改变它们):

auth = username = password = index = authType = rotation = None

@app.route("/set", methods=["GET","POST"])
def setup():

    global auth, username, password, index, authType, rotation

    auth     = request.args.get("auth")
    username = request.args.get("username")
    password = request.args.get("password")
    index    = request.args.get("index")
    authType = request.args.get("type", "no type arg sent")
    rotation = request.args.get("rotation")
    
    print(authType)
    return anotherMethod()

def anotherMethod():
    print(f"authType is {authType} inside anotherMethod()")
    return "success"

另一种解决方案:

不确定为什么您不想将值作为方法变量传递,但这可能符合您的愿望。 嵌套函数:

@app.route("/set", methods=["GET","POST"])
def setup():

    auth     = request.args.get("auth")
    username = request.args.get("username")
    password = request.args.get("password")
    index    = request.args.get("index")
    authType = request.args.get("type", "no type arg sent")
    rotation = request.args.get("rotation")
    
    print(authType)

    def anotherMethod():
        print(f"authType is {authType} inside anotherMethod()")
        return "success"

    print(anotherMethod())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM