0


cannot import name Markup from jinja2解决方案

web框架flask中引入pyecharts代码运行,出错显cannot import name 'Markup' from 'jinja2'(如图1),分析发现在jinja2版本过高 3.1.2中已经去掉了Markup,改为marupsafe可实现。
from flask import Flask
from jinja2 import Markup, Environment, FileSystemLoader
from pyecharts.globals import CurrentConfig

# 关于 CurrentConfig,可参考 [基本使用-全局变量]
CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

from pyecharts import options as opts
from pyecharts.charts import Bar

app = Flask(__name__, static_folder="templates")

def bar_base() -> Bar:
    c = (
        Bar()
        .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
        .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
        .add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
        .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
    )
    return c

@app.route("/")
def index():
    c = bar_base()
    return Markup(c.render_embed())

if __name__ == "__main__":
    app.run()

将代码改一下,

from jinja2.utils import markupsafe
def index():
    c = bar_base()
    return markupsafe.Markup(c.render_embed())

代码如下:

from flask import Flask
# from jinja2 import Markup
from jinja2.utils import markupsafe
from pyecharts import options as opts
from pyecharts.charts import Bar
app = Flask(__name__, static_folder="templates")
def bar_base() -> Bar:
    c = (
        Bar()
            .add_xaxis(["衬衫", "羊毛衫", "雪纺衫", "裤子", "高跟鞋", "袜子"])
            .add_yaxis("商家A", [5, 20, 36, 10, 75, 90])
            .add_yaxis("商家B", [15, 25, 16, 55, 48, 8])
            .set_global_opts(title_opts=opts.TitleOpts(title="Bar-基本示例", subtitle="我是副标题"))
    )
    return c
@app.route("/")
def index():
    c = bar_base()
    return markupsafe.Markup(c.render_embed())
if __name__ == "__main__":
    app.run()

运行结果:

标签: flask python 后端

本文转载自: https://blog.csdn.net/u014125025/article/details/129064453
版权归原作者 天和都成 所有, 如有侵权,请联系我们删除。

“cannot import name Markup from jinja2解决方案”的评论:

还没有评论