如何在python中读取multiDicts(烧瓶) [英] How do read multiDicts in python (flask)
问题描述
我有一个行列表
[{'name':'John','email':'John@test.com'},{'name':'Jenny','email':'Jenny@yahoo.com'}]
我正在使用ajax从javascript发送它们.我不确定如何在python/flask中读取它.我可以在request.form中看到数据.当我尝试访问它时,我遇到了问题.
request.form [0]
没有给我 {'name':'John','email':'John@test.com'}
>
@ app.route('/listusers',Methods = ['POST'])def do_listusers():对于request.form中的数据:打印(str(数据))打印(str(数据['名称']))
数据本身是
[{'name':'John','email':'John@test.com'},{'name':'Jenny','email':'Jenny@yahoo.com'}]
我期待着
{'name':'John','email':'John@test.com'}
数据[0]
也无效.
使用POST请求通过AJAX将JSON数据从模板发送到Flask:
- 将请求标头设置为内容类型JSON. 在发送到Flask之前先
-
JSON.stringify
数据.
在Flask中接收JSON数据:
- 使用
request.get_json()
.可以在当用户单击
Send Data
按钮时,它将JSON数据从模板发送到Flask应用.在Flask应用程序中,将处理数据并将处理后的数据返回到模板.I have a list of rows
[ {'name': 'John', 'email': 'John@test.com'}, {'name': 'Jenny', 'email': 'Jenny@yahoo.com'} ]
I am using ajax to send them from javascript. I am not sure how to read it in python/flask. I can see the data in request.form. When I try to access it, I am running into issues.
request.form[0]
does not give me{'name': 'John', 'email':'John@test.com'}
@app.route('/listusers', methods=['POST']) def do_listusers(): for data in request.form: print(str(data)) print(str(data['name']))
data itself is
[ {'name': 'John', 'email': 'John@test.com'}, {'name': 'Jenny', 'email': 'Jenny@yahoo.com'} ]
I was expecting
{'name': 'John', 'email': 'John@test.com'}
Also
data[0]
is not valid as well.解决方案Send JSON data from Template to Flask using AJAX using POST request:
- Set request header to content type JSON.
JSON.stringify
the data before sending to Flask.
Receive JSON data in Flask:
- Use
request.get_json()
. Details of this method can be found in official documentation.
I am showing an example of sending JSON data to Flask, processing in Flask and returning the processed data from Flask to template.
Initially the JSON data contains an array of objects:
[ {"name": "John", "email": "John@test.com"}, {"name": "Jenny", "email": "Jenny@yahoo.com"} ]
Suppose we need to modify this data to have an
id
attribute.Folder structure:
├── app.py └── templates └── index.html
app.py
:from flask import Flask, request, jsonify, render_template app = Flask(__name__) def get_processed_data(data): for i,item in enumerate(data): data[i]["id"] = i return data @app.route("/", methods=['GET', 'POST']) def login(): if request.method == "POST": request_data = request.get_json() processed_data = get_processed_data(request_data) return jsonify(processed_data), 200 return render_template("index.html") if __name__ == '__main__': app.run(host='0.0.0.0', port=5000)
index.html
:<html> <head> <title>Post JSON data using AJAX</title> </head> <body> <h2> POST JSON data using AJAX </h2> <button id="send_data_btn">Send Data</button> <script> var send_data_btn = document.getElementById("send_data_btn"); function postData() { var request_url = "http://127.0.0.1:5000/"; var request_payload = [ {"name": "John", "email": "John@test.com"}, {"name": "Jenny", "email": "Jenny@yahoo.com"} ]; var xhr = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP"); xhr.open('POST', request_url); xhr.onreadystatechange = function() { if (xhr.readyState==4 && xhr.status==200) { var processed_data = JSON.parse(xhr.responseText); console.log(processed_data); } }; xhr.setRequestHeader("Content-type", "application/json"); xhr.send(JSON.stringify(request_payload)); } send_data_btn.addEventListener("click", postData); </script> </body> </html>
Output:
When user clicks on
Send Data
button, it sends the JSON data from template to Flask app. In Flask app, the data is processed and returns the processed data to template.这篇关于如何在python中读取multiDicts(烧瓶)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!