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

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

问题描述

我正在用Flask制作一个网站,我希望能够使用页面中的数据执行python代码。我知道我可以简单地使用表单,但它是一个不断更新的单页面,因为它接收用户的输入,每当发生事情时,它会重新加载页面,这将是一个巨大的痛苦。我知道我可以在JavaScript内做 {{function()}} ,但是我该怎么做 {{function(args)}} 里面的JavaScript使用js变量?到目前为止,我唯一能想到的就是用js更新外部数据库,比如MongoDB,然后用Python读取,但是这个过程会让网站变慢。



jQuery需要从Python函数获取一个字典对象列表,然后可以在html中使用它。所以我需要能够做到这一点:



JS:

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

Python:

  def getDictList(args):
return dictlistMadeFromArgs


解决方案

使用Flask从Javascript获取数据到Python,您可以使用 AJAX POST

请求或
AJAX GET 请求。



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



首先,在Flask中实例化GET路径:



$ $ p $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $ $返回$ $ $ $

或POST一个:

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

第一个被 / getmethod /< javascript_data> / code>与 AJAX GET ,如下所示:

  $。get(/ getmethod /< javascript_data>); 

第二个通过使用 AJAX POST 请求:

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

其中 javascript_data 是JSON字典或一个简单的值。

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



<$ pre $



$例如,


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']
返回json.loads(jsdata)[0]

如果您需要以相反方式将Python数据推送到Javascript,请创建一个简单的GET路由,而不使用返回JSON编码字典的参数:

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

从JQuery中检索并解码:



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

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

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

因为我们需要的只是内部的字典,而不是列表,所以我们得到的是存储在字典索引0的项目。



另外, import json


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.

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");
});

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 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.

First, instantiate a GET route in Flask:

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

or a POST one:

@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:

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

The second one by using an AJAX POST request:

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

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

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

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:

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

Retrieve it from JQuery and decode it:

$.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:

[{'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.

Also, import json.

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

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