gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 20:36:21 24 4
gpt4 key购买 nike

在 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

有人有什么建议吗?

谢谢

最佳答案

Flask 不希望您从 View 函数返回 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)

关于python - Flask Python,试图将列表或字典返回给 Ajax 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12193013/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com