python - 为什么 json.dumps() 在 Flask 中是必须的?

标签 python flask

(这可能是个愚蠢的问题,所以请戴上你的愚蠢盾牌!)我曾经是一名 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'})

如果我将 return json.dumps({'status': 'success'}) 更改为 return 1 我会得到一个异常,即 int is not callable 。首先,我不明白是谁在尝试调用 int 以及为什么?其次,在 PHP 中,通常可能只是 echo 1;,这将成为 AJAX 响应。那么,为什么 return 1 在 Flask 中不起作用?

最佳答案

Flask View 返回内容背后的逻辑 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被调用,如果是整数,将调用 force_type() method werkzeug.Response 类在尝试实例化 WSGI 应用程序时最终将无法创建 BaseResponse 类的实例:

app_rv = app(environ, start_response)

在您的例子中,app 是整数 1

关于python - 为什么 json.dumps() 在 Flask 中是必须的?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34468308/

相关文章:

python - Nltk安装

Python - 属性错误 : 'NoneType' object has no attribute 'findAll'

python - Jinja 中是否有用于记录宏的官方格式?

python - 如何在 Jinja2 中使用命名空间类使用全局变量?

python - 捕捉 Flask 的所有路线

python - 如果前一列中的值不同,则制作一个增加的计数器?

python - 是否可以在selenium webdriver python中获取iframe的内容?

python - 将 virtualenv 移动到另一台具有不同 python 版本的 PC

python - 将 Flask-SQLAlchemy 中的模型分离到另一个文件会破坏 PyDev 导入检测

Python Marshmallow 未检测到必填字段中的错误