python - Flask - 'NoneType' 对象不可调用

标签 python flask werkzeug

我正在开发我的第一个 Flask 应用程序。直接从this中取出一些代码,我试图确保用户的 cookie 中存在一个值。

def after_this_request(f):
    if not hasattr(g, 'after_request_callbacks'):
        g.after_request_callbacks = []
    g.after_request_callbacks.append(f)
    return f

@app.after_request
def call_after_request_callbacks(response):
    for callback in getattr(g, 'after_request_callbacks', ()):
        response = callback(response)
    return response

@app.before_request
def detect_unique_id():
    unique_id = request.cookies.get('unique_id')
    if unique_id is None:
        unique_id = generate_unique_id()
        @after_this_request
        def remember_unique_id(response):
            response.set_cookie('unique_id', unique_id)
    g.unique_id = unique_id

我一直收到这个错误:

Traceback (most recent call last):
  File "/..../env/lib/python2.7/site-packages/flask/app.py", line 1701, in __call__
    return self.wsgi_app(environ, start_response)
  File "/..../env/lib/python2.7/site-packages/flask/app.py", line 1690, in wsgi_app
    return response(environ, start_response)
TypeError: 'NoneType' object is not callable

我正在尝试了解此错误的原因。请帮忙。

最佳答案

问题

remember_unique_id 不返回响应对象,但 call_after_request_callbacks 将调用通过 after_this_request 装饰器添加的每个回调的结果分配给 结果 然后返回它。也就是说:

# This
for callback in getattr(g, 'after_request_callbacks', ()):
    response = callback(response)

# translates to this
for callback in [remember_unique_id]:
    response = callback(response)

# which translates to this
response = remember_unique_id(response)

# which translates to this
response = None

解决方案

或者:

  • 更新remember_unique_id返回修改后的响应对象
  • 更新 call_after_request_callbacks 以检查返回的对象并确保它不是 None:

    for callback in getattr(g, 'after_request_callbacks', ()):
        result = callback(response)
        if result is not None:
            response = result
    

为什么会这样?

Flask 是一个 WSGI 应用程序,它期望 response 是一个 WSGI 应用程序(即,一个可调用对象)。当它处理来自 View 模板的响应时,它会运行一些检查以确保它是可以用作响应对象的东西,如果返回值不是 WSGI 应用程序,它会将其转换为一个。它检查响应对象没有被after_request装饰器改变,所以当它尝试调用响应对象时(它假定它是一个有效的 WSGI应用程序)你会得到 TypeError

关于python - Flask - 'NoneType' 对象不可调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11939858/

相关文章:

python - 如何继续处理车牌裁剪?

python - Flask/http- 告诉客户端请求需要更多时间才能完成

webapp2 - Werkzeug 和 WebApp2 - 调试显示和控制台不工作

python - 在 Django 中验证 GET 参数的正确方法

python - 基于公共(public)键对 pandas 数据框进行分组

python - 重新安装计算机后 Flask 不再提供静态文件

python - flask 同一页面上的多个表单

python - 默认 login_required 而不是到处添加装饰器

python-2.7 - Flask Urls 中用于路由的问号

python - 从 Flask POST 中传递的不仅仅是结果页面