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()
运行结果:文章来源:https://www.toymoban.com/news/detail-505982.html
文章来源地址https://www.toymoban.com/news/detail-505982.html
到了这里,关于cannot import name Markup from jinja2解决方案的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!