您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

python – 为什么在Flask中必须使用json.dumps()?

5b51 2022/1/14 8:22:12 python 字数 3264 阅读 528 来源 www.jb51.cc/python

(这可能是一个愚蠢的问题,所以请穿上你的愚蠢盾牌!)我是一名 PHP程序员,现在正在学习 Python Flask.我最近不得不通过AJAX发布数据并返回响应而苦苦挣扎.最后,有效的代码是: @app.route('/save', methods=['POST']) def save_subscriptions(): if request.method == 'POST':

概述

@app.route('/save',methods=['POST'])
def save_subscriptions():
    if request.method == 'POST':
        sites = request.form.get('selected')
        print(sites)
        sites = sites[0:-1]        
        g.cursor.execute('UPDATE users SET sites = %s WHERE email = %s',[sites,session.get('email')])
        g.db.commit()
        return json.dumps({'status': 'success'})

如果我更改返回json.dumps({‘status’:’success’})返回1我得到一个异常,即int不可调用.首先,我不明白谁试图称之为int,为什么?其次,在PHP中,经常可以只回显1;这将成为AJAX的回应.为什么不在Flask中返回1个工作呢?

The return value from a view function is automatically converted into
a response object for you. If the return value is a string it’s
converted into a response object with the string as response body,an
200 OK error code and a text/html mimetype. The logic that Flask
applies to converting return values into response objects is as
follows:

If a response object of the correct type is returned it’s directly
returned from the view.

If it’s a string,a response object is created
with that data and the default parameters.

If a tuple is returned the
items in the tuple can provide extra information. Such tuples have to
be in the form (response,status,headers) where at least one item has
to be in the tuple. The status value will override the status code and
headers can be a list or dictionary of additional header values.

If
none of that works,Flask will assume the return value is a valid WSGI
application and convert that into a response object.

在您的情况下,返回整数1 – Flask应用最后一个规则并尝试将其转换为响应对象并失败.在内部,调用make_response() method,在整数的情况下,将调用werkzeug.Response类的force_type() method,这在尝试实例化WSGI应用程序时最终将无法创建BaseResponse类的实例:

app_rv = app(environ,start_response)

在你的情况下,应用程序是整数1.

总结

以上是编程之家为你收集整理的python – 为什么在Flask中必须使用json.dumps()?全部内容,希望文章能够帮你解决python – 为什么在Flask中必须使用json.dumps()?所遇到的程序开发问题。


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶