Flask中的全局变量未定义

2024-09-28 23:09:50 发布

您现在位置:Python中文网/ 问答频道 /正文

大家好,我有一段脚本:

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是一个未定义的错误。此外,我尝试将上面的所有变量设置为“None”,并删除了“global”声明,因为我希望在一个请求中获取它们,然后将它们处理到其他方法中,而不将它们作为方法变量发送,但这些方法都不起作用

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


Tags: 方法authgetindexrequesttypeusernameargs
1条回答
网友
1楼 · 发布于 2024-09-28 23:09:50

您不需要使用全局变量request.args.get()默认为string,因此不需要这样做。尝试以下方法进行诊断:

@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"

编辑:

如果你坚持使用globals。您需要在函数中声明它们(如果您想在那里更改它们):

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

相关问题 更多 >