简体   繁体   English

如何使用 Flask 将数据从 JS 发送到 Python?

[英]How do I send data from JS to Python with Flask?

I'm making a website with Flask and I'd like to be able to execute python code using data from the page.我正在用 Flask 创建一个网站,我希望能够使用页面中的数据执行 python 代码。 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?我知道我可以在 javascript 中执行{{ function() }} ,但是如何使用 js 变量在 javascript 中执行{{ function(args) }} 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.到目前为止,我唯一能想到的就是用 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. jQuery 需要从 Python 函数中获取字典对象列表,然后可以在 html 中使用。 So I need to be able to do something like:所以我需要能够做类似的事情:

JS: JS:

var dictlist = { getDictList(args) };
dictlist.each(function() {
    $("<.Class>").text($(this)['Value']).appendTo("#element");
});

Python: Python:

def getDictList(args):
    return dictlistMadeFromArgs

To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request 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. Flask 有六种可用的HTTP方法 ,其中我们只需要GET和POST。 Both will take jsdata as a parameter, but get it in different ways. 两者都将jsdata作为参数,但以不同的方式获取它。 That's how two completely different languages in two different environments like Python and Javascript exchange data. 这就是两个完全不同的语言在两个不同的环境中如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 GET as follows: 第一个是由/getmethod/<javascript_data>使用AJAX GET访问 ,如下所示:

$.get( "/getmethod/<javascript_data>" );

The second one by using an AJAX POST request: 第二个使用AJAX POST请求:

$.post( "/postmethod", {
    javascript_data: data 
});

Where javascript_data is either a JSON dict or a simple value. 其中javascript_data是JSON dict或简单值。

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: 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. 因为我们需要的只是内部的dict而不是列表,我们得到的项目存储在索引0这是dict。

Also, import json . 另外, import json

.html .html

... id="clickMe" onclick="doFunction();">

.js .js

    function doFunction()
    {
        const name = document.getElementById("name_").innerHTML

        $.ajax({
            url: '{{ url_for('view.path') }}',
            type: 'POST',
            data: {
                name: name
            },
            success: function (response) {
            },
            error: function (response) {
            }
        });

    };

.py .py

@app.route("path", methods=['GET', 'POST'])
def view():
    name = request.form.get('name')
    ...

im new in coding, but you can try this:我是编码新手,但你可以试试这个:
index.html索引.html

 <script> var w = window.innerWidth; var h = window.innerHeight; document.getElementById("width").value = w; document.getElementById("height").value = h; </script>
 <html> <head> <!---Your Head---> </head> <body> <form method = "POST" action = "/data"> <input type = "text" id = "InputType" name = "Text"> <input type = "hidden" id = "width" name = "Width"> <input type = "hidden" id = "height" name = "Height"> <input type = "button" onclick = "myFunction()"> </form> </body> </html>

.py .py

 from flask import Flask, request app = Flask(__name__) html = open("index.html").read() @app.route("/") def hello(): return html @app.route("/data", methods=["POST", "GET"]) def data(): if request.method == "GET": return "The URL /data is accessed directly. Try going to '/form' to submit form" if request.method == "POST": text = request.form["Text"] w = request.form["Width"] h = request.form["Height"] //process your code return //value of your code

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM