如何使用 Flask 将数据从 JS 发送到 Python? [英] How do I send data from JS to Python with Flask?

查看:36
本文介绍了如何使用 Flask 将数据从 JS 发送到 Python?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 Flask 制作一个网站,我希望能够使用页面中的数据执行 python 代码.我知道我可以简单地使用表单,但它是一个在接收用户输入时不断更新的单个页面,每次发生某些事情时让它重新加载页面会很痛苦.我知道我可以在 javascript 中执行 {{ function() }} 但我如何在 javascript 中使用 js 变量执行 {{ function(args) }} ?到目前为止,我唯一能想到的就是用 js 更新像 MongoDB 这样的外部数据库,然后使用 Python 从中读取数据,但是这个过程会大大减慢网站的速度.

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.

jQuery 需要从 Python 函数中获取字典对象列表,然后才能在 html 中使用.所以我需要能够做这样的事情:

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:

JS:

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

蟒蛇:

def getDictList(args):
    return dictlistMadeFromArgs

推荐答案

要使用 Flask 从 Javascript 到 Python 获取数据,您可以创建一个 AJAX POST 请求或 AJAX GET 请求与您的数据.

To get data from Javascript to Python with Flask, you either make an AJAX POST request or AJAX GET request with your data.

Flask 有六个可用的 HTTP 方法,我们只需要 GET 和 POST.两者都将 jsdata 作为参数,但以不同的方式获取它.这就是 Python 和 Javascript 等两种不同环境中的两种完全不同的语言交换数据的方式.

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 中实例化一个 GET 路由:

First, instantiate a GET route in Flask:

@app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
    return jsdata

或 POST 一个:

@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
    jsdata = request.form['javascript_data']
    return jsdata

第一个由 /getmethod/ 使用 AJAX GET 如下:

The first one is accessed by /getmethod/<javascript_data> with an AJAX GET as follows:

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

第二个使用 AJAX POST 请求:

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

其中 javascript_data 是 JSON 字典或简单值.

Where javascript_data is either a JSON dict or a simple value.

如果您选择 JSON,请确保将其转换为 Python 中的 dict:

In case you choose JSON, make sure you convert it to a dict in Python:

json.loads(jsdata)[0]

例如

获取:

@app.route('/getmethod/<jsdata>')
def get_javascript_data(jsdata):
    return json.loads(jsdata)[0]

发布:

@app.route('/postmethod', methods = ['POST'])
def get_post_javascript_data():
    jsdata = request.form['javascript_data']
    return json.loads(jsdata)[0]

如果你需要反过来做,将 Python 数据推送到 Javascript,创建一个简单的不带参数的 GET 路由,返回一个 JSON 编码的字典:

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:

@app.route('/getpythondata')
def get_python_data():
    return json.dumps(pythondata)

从 JQuery 中检索并解码:

Retrieve it from JQuery and decode it:

$.get("/getpythondata", function(data) {
    console.log($.parseJSON(data))
})

json.loads(jsdata)[0] 中的 [0] 存在是因为当你在 Python 中解码一个 JSON 编码的字典时,你会得到一个列表内部的单个字典,存储在索引 0,因此您的 JSON 解码数据如下所示:

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:

[{'foo':'bar','baz':'jazz'}] #[0: {'foo':'bar','baz':'jazz'}]

因为我们需要的只是里面的字典而不是列表,所以我们将项目存储在索引 0 处,即字典.

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.

另外,import json.

这篇关于如何使用 Flask 将数据从 JS 发送到 Python?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆