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

前端之家收集整理的这篇文章主要介绍了python – 为什么在Flask中必须使用json.dumps()?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
(这可能是一个愚蠢的问题,所以请穿上你的愚蠢盾牌!)我是一名 PHP程序员,现在正在学习 Python Flask.我最近不得不通过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’})返回1我得到一个异常,即int不可调用.首先,我不明白谁试图称之为int,为什么?其次,在PHP中,经常可以只回显1;这将成为AJAX的回应.为什么不在Flask中返回1个工作呢?

解决方法

Flask视图 is described in the docs应该返回的逻辑背后的逻辑:

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相关文章