首页 > 解决方案 > 如何在 Flask 网页中嵌入模板化的散景应用程序?

问题描述

假设我有以下由散景服务器提供的应用程序:
main.py:

from bokeh.io import curdoc
from bokeh.models.widgets.markups import Div

div = Div(text="Hello world", name="div")

curdoc().add_root(div)

这个应用程序使用了一个 jinja 模板和一个 css 文件,如下所示:

索引.html:

{% extends base %}

<!-- goes in head -->
{% block preamble %}
    <style type="text/css">{% include 'styles.css' %}</style>
{% endblock %}

<!-- goes in body -->
{% block contents %}
    <div id="main">
        <div id="caption">
            {{ embed(roots.div) }}
        </div>
    </div>
{% endblock %}

样式.css:

#caption {
    background-color: red;
    padding-left: 20px;
}

在 Flask 应用程序上,我具有以下视图功能:

__init__.py:

from flask import Flask, render_template
from bokeh.client import pull_session
from bokeh.embed import server_session


def create_app() -> Flask:

    app = Flask(__name__)

    @app.route("/apps/<string:app_name>", methods=["GET"])
    def apps(app_name):
        app_url = f"http://localhost:5100/{app_name}"

        with pull_session(url=app_url) as session:

            # generate a script to load the customized session
            script = server_session(session_id=session.id, url=app_url)

            # use the script in the rendered page
            return render_template("embed_app.html", script=script, app_name=app_name)

    return app

现在,我的问题是应该如何embed_app.html使应用程序保持其在散景服务器中出现的相同 html 结构和样式。我试图按照这个例子,我设置embed_dashboard.html这个:

<!doctype html>

<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>{{ app_name }} App</title>
    </head>

    <body>
        {{ script|safe }}
    </body>
</html>

但它没有用。HTML 结构不一样,因此没有应用样式规则。

文件系统如下所示:

project/  
  bokeh_app/  
    Test/
      main.py  
      templates/  
        index.html  
        styles.css  
  flask_app/  
    __init__.py  
    templates/  
      embed_app.html  

我运行散景服务器:

bokeh serve --port 5100 --allow-websocket-origin localhost:5000 --allow-websocket-origin 127.0.0.1:5000 --glob bokeh_app/*

然后是应用程序:

export FLASK_APP=flask_app/__init__.py  
flask run

标签: pythonpython-3.xflaskbokeh

解决方案


推荐阅读