python - 对象没有被传递到 flask 路由中

标签 python function flask decorator routes

我有一个函数和一个 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/

相关文章:

python - 如何通过继承在两个不同的类中拆分函数?初学者

java - 这段代码复杂度为 O(log^2(n)) 吗?

nginx - 如何配置 nginx 和 uwsgi 将调用从路径重定向到子域?

reactjs - 将 React 应用程序集成到 Flask 应用程序中

python - Django:将 session 数据存储在类变量中是否合理?

python - 延迟加载的描述符

php - 检查字符串是否超过限制字符然后显示 '...'

python - 用于提取关注者计数的正则表达式模式

python - 根据 python 中的给定条件最小化 n 的最快方法

python - 你怎么能得到 flask 中文件的文件路径?