一尘不染

Flask Python,尝试将列表或字典返回给Ajax调用

flask

在Flask应用中,我有以下ajax调用:

    $.ajax({
            url: "{{ url_for( 'bookings.get_customer' ) }}",
            type: "POST",
            data: nameArray,
            success: function( resp ){
                console.log( resp )
            }
        })

如你所见,我正在传递一个数组,我将在该数组上搜索我的mongo数据库,该数据库将返回或不返回客户。

因此,负责处理此ajax调用的python def是:

@bookings.route( '/get_customer', methods=[ 'POST' ] )
def get_customer():
    name = {}
    for key, value in request.form.items():
     name[ key ] = value

    customer_obj = customer_class.Customer()
    results = customer_obj.search_customer( name )

    return results  

为了论证,可以说customer_obj调用返回以下列表:

[{'customer': {
               u'first_name': u'Dave', 
               u'tel': u'0121212121458', 
               u'country': u'UK',     
               u'address2': u'Townington', 
               u'address3': u'Cityville', 
               u'email': u'dave@smith.com', 
               u'postcode': u'A10 5BC', 
               u'address1': u'10 High Street', 
               u'second_name': u'Smith'
             }, 
 'customer_id': u'DaveSmithA10 5BCCat_Vegas1346244086'
}]

当我尝试将其返回给ajax调用时

return results

我收到以下错误:

 TypeError: 'list' object is not callable

这是回溯:

Traceback (most recent call last):
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1701, in __call__
return self.wsgi_app(environ, start_response)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1689, in wsgi_app
response = self.make_response(self.handle_exception(e))
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1687, in wsgi_app
response = self.full_dispatch_request()
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1361, in
full_dispatch_request
response = self.make_response(rv)
File "/usr/local/lib/python2.7/dist-packages/flask/app.py", line 1450, in make_response
rv = self.response_class.force_type(rv, request.environ)
File "/usr/local/lib/python2.7/dist-packages/werkzeug/wrappers.py", line 711, in
force_type
response = BaseResponse(*_run_wsgi_app(response, environ))
File "/usr/local/lib/python2.7/dist-packages/werkzeug/test.py", line 818, in
run_wsgi_app
app_iter = app(environ, start_response)
TypeError: 'list' object is not callable

有没有人有什么建议?


阅读 837

收藏
2020-04-07

共1个答案

一尘不染

Flask不希望你list从视图函数返回对象。尝试jsonify之前:

from flask import jsonify

@bookings.route( '/get_customer', methods=[ 'POST' ] )
def get_customer():
    name = {}
    for key, value in request.form.items():
        name[ key ] = value

    customer_obj = customer_class.Customer()
    results = customer_obj.search_customer( name )

    return jsonify(customers=results)   
2020-04-07