英文:
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:
<input type="hidden" name="dataname" value={{dataframe|safe}}>
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代码:
<input type="hidden" name="dataname" value={{json_dataframe}}>
在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:
<input type="hidden" name="dataname" value={{json_dataframe}}>
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!
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论