为什么json.dumps()必须在Flask中? [英] Why is json.dumps() a must in Flask?

查看:235
本文介绍了为什么json.dumps()必须在Flask中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

(这可能是一个愚蠢的问题,所以请戴上你的愚蠢的盾牌!)我一直是一个PHP程序员,现在正在学习Python +烧瓶。我最近不得不通过AJAX发布数据并返回响应。最后,工作的代码是:

  @ 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'}) return 1 我得到一个Exception int不可调用。首先,我不明白是谁试图调用 int ,为什么?其次,在PHP中,经常可能只是 echo 1; ,这将成为AJAX响应。为什么不在中返回1 在Flask中工作,然后呢?

解决方案

应该由Flask视图返回的逻辑在文档中描述详细说明:


视图函数的返回值会自动转换为
a响应对象。如果返回值是一个字符串,它将
转换成一个响应对象,字符串作为响应主体,一个
200 OK错误代码和一个text / html mimetype。 Flask
适用于将返回值转换为响应对象的逻辑是:
如下:

$ ul

  • 返回正确类型的响应对象直接从视图返回
    。如果它是一个字符串,一个响应对象被创建
    与该数据和默认参数。

  • 如果元组被返回,元组中的
    项可以提供额外的信息。这样的元组必须以
    的形式存在(response,status,headers),其中至少有一个元素具有
    才能在元组中。状态值将覆盖状态码,
    头可以是附加头值的列表或字典。如果
    没有任何作用,Flask将假定返回值是一个有效的WSGI
    应用程序,并将其转换为一个响应对象。

    在你的情况中,整数 1 code>返回 - Flask应用最后一条规则,并尝试将其转换为响应对象并失败。在内部, make_response()方法,如果是整数,则调用 force_type()方法 werkzeug.Response 类,最终会失败创建当尝试实例化WSGI应用程序时, BaseResponse 类的实例:

      app_rv = app(environ,start_response)

    其中 app 在你的情况是整数 1


    (This is probably a dumb question, so please wear your stupidity shields!) I've been a PHP programmer and am now learning Python + Flask. I recently had to struggle a lot with posting data through AJAX and returning a response. Finally, the code that worked was:

    @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'})
    

    If I change return json.dumps({'status': 'success'}) to return 1 I get an Exception that int is not callable. First of all, I don't understand who is trying to call that int and why? Secondly, in PHP, it was frequently possible to just echo 1; and this would become the AJAX response. Why doesn't return 1 work in Flask, then?

    解决方案

    The logic behind what should be returned by Flask views is described in the docs in detail:

    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.

    In your case, integer 1 is returned - Flask applies the last rule and tries to convert it into a response object and fails. Internally, make_response() method is called which, in case of an integer, would call force_type() method of a werkzeug.Response class which would eventually fail creating an instance of a BaseResponse class when trying to instantiate a WSGI app:

    app_rv = app(environ, start_response)
    

    where app in your case is integer 1.

    这篇关于为什么json.dumps()必须在Flask中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆