我有一个函数和一个 flask 路由设置。但是,当我转到“simplepage”时,出现错误“NameError: global name 'aaa' is not defined”。为什么没有任何对象被传递给 testfun?这是由于 app.route 装饰器还是由于 flask ?我可以让所有的对象都传递给testfun吗?我的实际代码要复杂得多,需要传递更多的对象,但创建这个简化的场景是为了说明我的问题。
def testfun():
b=aaa
@app.route("/simplepage/", methods=['GET'])
def simplepage():
aaa=1
testfun()
return flask.render_template('page.html')
最佳答案
这是由于 Python's scoping rules (正如@johnthexiii 指出的那样)- testfun->aaa
绑定(bind)到全局范围,因为在 testfun
中的任何地方都没有声明名为 aaa
的变量> 并且没有封闭范围(即 testfun
未在另一个函数或类中声明)。
您需要将 aaa
作为参数传递给 testfun
:
testfun(aaa)
如果 testfun
需要太多参数,您可以通过多种方式来 DRY 代码:
使用多个函数:如果
testfun
正在做大量工作,则将其分解为多个返回数据中间转换的函数:def start_test(arg1, arg2, arg3): # do stuff with args return result_stage_1 def continue_test(arg3, arg4, arg5): # do stuff with args return result_stage_2 def finalize_test(arg7, arg8): # do stuff with args return real_result
使用关键字参数:如果需要可变数量的参数并且
testfun
不能被分解,您可以使用关键字参数简化函数的调用:def testfun(arg1=None, arg2=None, arg3=None, arg4=None, arg5=None, arg6=None, arg7=None, arg8=None): # do stuff with args # call it as so args = {"arg1": "some args", "arg5": "have defaults"} if complex_condition: args["arg3"] = 17 elif another_condition: args["arg7"] = 10 testfun(**args)
用类(或闭包)封装状态和行为:如果以上都不适合您,那么您可能需要离开无状态函数的领域并创建类或闭包-创建函数来保存您的状态并使您能够根据需要修改行为。
关于python - 对象没有被传递到 flask 路由中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16050301/