【发布时间】:2020-07-17 20:21:20
【问题描述】:
我已经使用生成折线图的 plotly 库编写了 Python 代码,我想在 HTML 上运行时运行相同的 Python 文件。如何在网页浏览器/网页上动态运行 Python 脚本?
Python 脚本
import pandas as pd
import plotly
import plotly.express as px
import numpy as np
import matplotlib.pyplot as plt
from pandas import Series, DataFrame
from numpy import nan as NA
import glob
from pathlib import Path
import plotly.graph_objects as go
p = Path(r'c:\Users\shivarad\Documents') # path to files
files = list(p.rglob('*graph22.csv')) # get files
fig = go.Figure()
for f in files:
file_name = f.stem
df = pd.read_csv(f, dtype={'Pass Percentage': int, 'original_pass_percent':int})
df = df.sort_values(by=['build ID'], axis = 0)
print(df.head())
fig.add_trace(go.Scatter(x=df['build ID'], y=df['Pass Percentage'],mode='lines',name=file_name))
fig.update_layout(title='Pass Percent VS Build ID of all the Test Suites',plot_bgcolor='rgb(230,
230,230)',showlegend=True)
fig.show()
我想在 HTML 文件中呈现上述 python 文件,并希望通过按钮或单击来运行 python 文件。
HTML 脚本
<!DOCTYPE html>
<html>
<title>OV Daily Test Results</title>
<body>
<form action="cgi-bin/results.py" method="post">
<input type="Submit" name="show_last_runs" value="Display Results For Last 2 Runs"></br></br>
<b>Enter Build id</b></br>
<input type="text" name="build_id_2_runs" size="15"><br>
<input type="Submit" name="show_last_2_runs" value="Show Results For Last 2 Runs"></br></br>
<input type="Submit" name="collect_last_2_runs" value="Collect Results For Last 2 Runs"></br>
</br></br>
<b>Enter Build id</b></br>
<input type="text" name="build_id" size="15"><br>
<input type="Submit" name="show_button" value="Show Results">
<input type="submit" name="refresh_button" value="Collect Results" />
</form>
<form action="toweb.py" method="post">
<label form="Test suites">For Bar Graph Choose the Test Suite:</label>
<input type="submit" name="Test_suites" value="Submit" />
</form>
</body>
</html>
如何在网页上动态获取 Python 绘图结果,或者建议我任何可以在网页上获得结果的方法。
【问题讨论】:
-
策略:打开一个 BytesIO 流,在该流上调用 fig.write_html 方法,将该流解码为字符串,将字符串发送给客户端(通过直接构建 html 或 Ajax)。
-
另外,请告诉我们您打算如何从浏览器调用 Python 脚本。对我来说,这充其量似乎很奇怪。
-
我是 Ajax 的新手,实际上我尝试在 CGI 的帮助下调用这个 python 脚本,但运气不好,我无法在网页上查看结果。所以请指导我在网页上动态获取折线图的任何可能方式
-
嗯,这是一个比 Stackoverflow 更合适的问题。可能最简单的方法是从 Python Flask 服务器为您的网站提供服务。根据获取请求,您创建绘图,将其转换为如上所述的 html 字符串,将其插入 Jinja 模板并将其发送给客户端。 flask.palletsprojects.com/en/1.1.x 网上有足够多的关于所有这些问题的教程可以帮助您入门。这种方式不需要 CGI。如果由于某些原因您需要使用现有的网络服务器,只需让它将任何获取绘图的请求转发到 Flask 服务器。
标签: python html web graph plotly