Flask - object "NoneType" cannot be called

I am working on my first flash application. By accepting some code directly from this , I try to make sure that the value is present in the user's cookies.

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

I keep getting this error:

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

I am trying to understand the cause of this error. Please help.

+5
source share
1 answer

Problem

remember_unique_iddoes not return a response object, but call_after_request_callbacksassigns the result of the call of each callback added through the decorator after_this_requestto result, and then returns it. I.e:

# 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

Decision

Or:

  • Refresh remember_unique_idto return a modified response object
  • 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- ( ). , , , , , WSGI, . , after_request, , (, , WSGI- ), TypeError.

+5

All Articles