如何将数据框从Jinja传递到Flask路由

huangapple go评论62阅读模式
英文:

How to pass a dataframe from jinja to flask route

问题

我有一个显示数据框的Jinja模板,并希望通过表单将这个数据框传递到Flask中的一个新路由。

在HTML表单中,我尝试了以下代码,但没有成功:

<input type="hidden" name="dataname" value={{dataframe|safe}}>

有人能提出将数据框传递到Flask路由的最佳方法吗?

谢谢!

英文:

I have a jinja template that displays a dataframe and I would like to pass this dataframe through a form to a new route in flask.

In the HTML form, I tried the following code but with no success:

&lt;input type=&quot;hidden&quot; name=&quot;dataname&quot; value={{dataframe|safe}}&gt;

Can anyone suggest the best possible way to pass a data frame to the flask route?

Thanks!

答案1

得分: 2

根据Mark的建议,我做了以下操作:

在jinja中,我将数据框转换为JSON,如下所示:

{%set json_dataframe = dataframe.to_json()%}

将数据框传递到Flask路由的HTML代码:

&lt;input type=&quot;hidden&quot; name=&quot;dataname&quot; value={{json_dataframe}}&gt;

在Flask路由中,我加载了JSON字典:

parsed_json = json.loads(json_dataframe)

然后使用以下方法将其转换为数据框:

pd.DataFrame.from_dict(parsed_json)

就是这样。这个方法非常有效!

英文:

Based on Mark's suggestion, I did the following:

In jinja, I converted the data frame to JSON as follows:

{%set json_dataframe = dataframe.to_json()%}

html code for passing the datframe to flask route:

&lt;input type=&quot;hidden&quot; name=&quot;dataname&quot; value={{json_dataframe}}&gt;

and in the flask route, I loaded the json dictionary as:

parsed_json = json.loads(json_dataframe) 

and then converted to a data frame using:

pd.DataFrame.from_dict(parsed_json)

That's it. This worked like a charm!

huangapple
  • 本文由 发表于 2023年3月9日 14:32:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/75681153.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定