为什么是json.dumps文件()必须在Flask里?

2024-06-26 10:25:50 发布

您现在位置:Python中文网/ 问答频道 /正文

(这可能是个愚蠢的问题,所以请戴上你的愚蠢盾牌!)我是一名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的异常。首先,我不明白是谁在试图称之为{},为什么?其次,在PHP中,经常可能只使用echo 1;,这将成为AJAX响应。那么,为什么return 1在烧瓶里不起作用呢?在


Tags: jsongetreturnemailrequestsavestatusajax
1条回答
网友
1楼 · 发布于 2024-06-26 10:25:50

烧瓶视图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.

在您的例子中,返回整数1Flask应用最后一条规则并尝试将其转换为响应对象,但失败了。在内部,^{} method被调用,如果是整数,它将调用werkzeug.Response类的^{} method,当尝试实例化一个WSGI应用时,最终将无法创建BaseResponse类的实例:

app_rv = app(environ, start_response)

其中app在您的例子中是整数1。在

相关问题 更多 >