加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 22:59:48 所属栏目:Python 来源:网络整理
导读:(这可能是一个愚蠢的问题,所以请穿上你的愚蠢盾牌!)我是一名 PHP程序员,现在正在学习 Python Flask.我最近不得不通过AJAX发布数据并返回响应而苦苦挣扎.最后,有效的代码是: @app.route('/save',methods=['POST'])def save_subscriptions(): if request.met
(这可能是一个愚蠢的问题,所以请穿上你的愚蠢盾牌!)我是一名 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读