Python 烧瓶 request.json 到 dict

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19963647/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 15:05:34  来源:igfitidea点击:

Flask request.json to dict

pythonjsonjquerydictionaryflask

提问by Sebastian

Im struggling with JQuery ajax methods and Flask, trying to make an ajax call to retrieve some form.

我正在努力使用 JQuery ajax 方法和 Flask,试图进行 ajax 调用以检索某种形式。

My js code looks like this:

我的 js 代码如下所示:

$.ajax({
       type: 'POST',
       url: '/projects/dummyName',
       data: JSON.stringify("{'ajax': 'True'}"),
       contentType: 'application/json;charset=UTF-8',
       dataType: 'html',
       success: function(responseData, textStatus, jqXHR) {
           $("#myform").text(responseData);
         },
       error: function (responseData, textStatus, errorThrown) {
           alert('Error: '+errorThrown + ". Status: "+textStatus);
       }
}); 

Basically im adding the data parameter to let the server method that this is an ajax call. But i just cant get that data in the server as a dict. Tried millon ways, im cant make it work.

基本上我添加数据参数让服务器方法这是一个ajax调用。但是我无法将服务器中的数据作为 dict 获取。试过万种方法,我不能让它工作。

This is the dummy server method:

这是虚拟服务器方法:

@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
    print(request.json)
    print(request.json['ajax'])
    if name:
        project = db.getProject(name)
        form = ProjectForm(project)

        if request.json['ajax'] == True:
            return render_template("myform.html", form=form)
        else:
            return render_template("projectView.html", form=form)
    else:
        return render_template("projects.html")

So, request.json returns a string:

因此, request.json 返回一个字符串:

{'ajax': 'True'}

{'ajax': '真'}

Of course the app breaks when try to access json['ajax'] and I get a BAD RESPONSE error msg. I thought that would give me a python dict, because otherwise what would be the difference between request.json and request.data if both are strings.

当然,当尝试访问 json['ajax'] 时应用程序会中断,并且我收到 BAD RESPONSE 错误消息。我认为这会给我一个 python dict,否则如果 request.json 和 request.data 都是字符串,那么它之间的区别是什么。

How can i get a python dict with all the data passed in the ajax call? Does it depend on the way I define the contentType? does it depend on the use of JSON.stringify or not?

我怎样才能得到一个包含在 ajax 调用中传递的所有数据的 python 字典?它是否取决于我定义 contentType 的方式?它是否取决于 JSON.stringify 的使用?

Help will be much appreciated! Thanks

帮助将不胜感激!谢谢

回答by Seberius

The data is being put into request.json because of the mimetype of the request. I believe you are looking for get_json.

由于请求的 mimetype,数据被放入 request.json。我相信你正在寻找get_json

@app.route('/projects/<name>', methods=['GET', 'POST'])
def projects(name=None):
    req_json = request.get_json()
    print(req_json['ajax'])
    if name:
        project = db.getProject(name)
        form = ProjectForm(project)

        if req_json['ajax']:
            return render_template("myform.html", form=form)
        return render_template("projectView.html", form=form)
    return render_template("projects.html")

I do not have access to my dev machine at the moment so I haven't tested this, but it should work from my understanding of the docs.

我目前无法访问我的开发机器,所以我还没有对此进行测试,但是根据我对文档的理解,它应该可以工作。