如何将 Altair 图从一条 Flask 路线传递到另一条路线?

How to pass an Altair graph from one Flask route to another?

我是 Flask 的新手。我正在开发一个网络应用程序来显示图表。我需要显示的图表之一是使用 Altair。

from altair import layer

def create_altair(anomaly_id):
    .
    .
    .
    graph = (
        layer(interval, All, normals, anomalies, current_anomaly)
        .properties(width=870, height=450)
        .configure_title(fontSize=20)
    )

    return graph.to_json(), one_anomaly
@App.route("/anomaly/<int:anomaly_id>", methods=["GET", "POST"])
@login_required
def anomaly(anomaly_id):

    graph, current_anomaly = create_altair(anomaly_id)
    if """form is valide, it will be input to the database""":
        anomaly_id += 1
        return redirect(
            url_for(
                "anomaly",
                title="Anomaly Dectection",
                anomaly_id=anomaly_id,
                form=form,
                single_anomaly=current_anomaly,
                graph=graph,
            )
        )

    return render_template(
        "anomaly.html",
        title="Anomaly Dectection",
        anomaly_id=anomaly_id,
        form=form,
        single_anomaly=current_anomaly,
        graph=graph,
    )

然后我需要将我从异常路线得到的图表传递到下面的Altair图表路线。我尝试在URL link(如此post)和flask.session中使用变量。但是两者都不起作用。这些是正确的使用方法吗?或者还有其他我没有探索过的方法吗?提前致谢!

########################
# Altair Routes
########################

@App.route("/chart/anomaly/<string:graph>")
def anomaly_chart(graph):
    return graph
<!-- Render Charts -->

<script type="text/javascript">
    function parse(url, div) {
        var opt = {
            mode: "vega-lite",
            renderer: "svg",
            actions: { export: true, source: false, editor: false }
        };

        vegaEmbed("#" + div, url, opt, function (error, result) {
            // result.view is the Vega View, url is the original Vega-Lite specification
            vegaTooltip.vegaLite(result.view, url);
        });
    }
    parse("/chart/anomaly/" + {{ graph }}, "pred");

</script>

我通过将 json 文件保存在本地并从另一个 flask 路径检索该本地文件解决了这个问题。