如何使用 Flask 将数据从 JS 发送到 Python?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29987323/
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
How do I send data from JS to Python with Flask?
提问by Sneaky Beaver
I'm making a website with Flask and I'd like to be able to execute python code using data from the page. I know that I can simply use forms but it's a single page that is continually updated as it receives user input and it'd be a massive pain in the ass to have it reload the page every time something happens. I know I can do {{ function() }}
inside the javascript but how do I do {{ function(args) }}
inside the javascript using js variables? So far the only thing I can think of is to update an external database like MongoDB with the js then use Python to read from that, but this process will slow down the website quite a lot.
我正在用 Flask 制作一个网站,我希望能够使用页面中的数据执行 python 代码。我知道我可以简单地使用表单,但它是一个在接收用户输入时不断更新的单个页面,每次发生某些事情时让它重新加载页面将是一个巨大的痛苦。我知道我可以{{ function() }}
在 javascript 中做,但是如何{{ function(args) }}
使用 js 变量在 javascript 中做呢?到目前为止,我唯一能想到的就是用 js 更新像 MongoDB 这样的外部数据库,然后使用 Python 从中读取数据,但是这个过程会大大减慢网站的速度。
The jQuery needs to get a list of dictionary objects from the Python function which can then be used in the html. So I need to be able to do something like:
jQuery 需要从 Python 函数中获取一个字典对象列表,然后可以在 html 中使用它。所以我需要能够做这样的事情:
JS:
JS:
var dictlist = { getDictList(args) };
dictlist.each(function() {
$("<.Class>").text($(this)['Value']).appendTo("#element");
});
Python:
Python:
def getDictList(args):
return dictlistMadeFromArgs
采纳答案by Alper Turan
To get data from Javascript to Python with Flask, you either make an AJAX POSTrequest or AJAX GETrequest with your data.
要使用 Flask 将数据从 Javascript 获取到 Python,您可以使用数据发出AJAX POST请求或AJAX GET请求。
Flask has six HTTP methods available, of which we only need the GET and POST. Both will take jsdata
as a parameter, but get it in different ways. That's how two completely different languages in two different environments like Python and Javascript exchange data.
Flask有六个可用的 HTTP 方法,其中我们只需要 GET 和 POST。两者都将jsdata
作为参数,但以不同的方式获取它。这就是 Python 和 Javascript 等两种不同环境中的两种完全不同的语言交换数据的方式。
First, instantiate a GET route in Flask:
首先,在 Flask 中实例化一个 GET 路由:
@app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return jsdata
or a POST one:
或 POST 一个:
@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return jsdata
The first one is accessed by /getmethod/<javascript_data>
with an AJAX GETas follows:
第一个是通过AJAX GET访问的/getmethod/<javascript_data>
,如下所示:
$.get( "/getmethod/<javascript_data>" );
The second one by using an AJAX POSTrequest:
第二个使用AJAX POST请求:
$.post( "/postmethod", {
javascript_data: data
});
Where javascript_data
is either a JSON dict or a simple value.
哪里javascript_data
是 JSON 字典或简单值。
In case you choose JSON, make sure you convert it to a dict in Python:
如果您选择 JSON,请确保将其转换为 Python 中的 dict:
json.loads(jsdata)[0]
Eg.
例如。
GET:
得到:
@app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
return json.loads(jsdata)[0]
POST:
邮政:
@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
jsdata = request.form['javascript_data']
return json.loads(jsdata)[0]
If you need to do it the other way around, pushing Python data down to Javascript, create a simple GET route without parameters that returns a JSON encoded dict:
如果你需要反过来做,将 Python 数据推送到 Javascript,创建一个简单的 GET 路由,不带参数,返回一个 JSON 编码的 dict:
@app.route('/getpythondata')
def get_python_data():
return json.dumps(pythondata)
Retrieve it from JQuery and decode it:
从 JQuery 中检索它并对其进行解码:
$.get("/getpythondata", function(data) {
console.log($.parseJSON(data))
})
The [0]
in json.loads(jsdata)[0]
is there because when you decode a JSON encoded dict in Python, you get a list with the single dict inside, stored at index 0, so your JSON decoded data looks like this:
该[0]
中json.loads(jsdata)[0]
有没有因为当你解码Python中的JSON编码字典,你得到的单字典里面,存储在索引0,所以你的JSON解码后的数据看起来像这样的列表:
[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]
Since what we need is the just the dict inside and not the list, we get the item stored at index 0 which is the dict.
由于我们需要的只是里面的字典而不是列表,我们得到存储在索引 0 的项目,即字典。
Also, import json
.
还有,import json
。