是否有任何解决方案可以使用 Flask 显示没有 HTML 标签的 SVG?

Is there any solution that can show SVG without HTML tags using Flask?

是否有任何解决方案可以使用 Flask 显示不带 HTML 标签的 SVG?

我正在构建类似于 this project 的项目,它允许用户通过生成图像(在 SVG 中)用户的统计信息来在他们的静态网站上显示他们的当前统计信息。

按照我的理解,概念是:

  1. 使用 GET 参数指定用户数据、主题...等
  2. 服务器查询用户数据
  3. 服务器 return 带有用户数据的 svg

存储库中的示例:

https://github-readme-streak-stats.herokuapp.com/?user=DenverCoder1

示例结果:

https://i.imgur.com/Kc9hMzT.png

我在python Flask

中写了后端

但是,我无法通过 flask

找到仅显示 svg 的解决方案

我试过 render_template() 方法或 return 原始 SVG 字符串,它们都不能显示 只有没有 html 标签的 SVG

  1. 使用 render_template()
@app.route("/test_rend" , methods=['GET'])
def Test_rend():
    ...
    
    return render_template("img.svg")

  1. return SVG 原始字符串
@app.route("/test_raw" , methods=['GET'])
def Test_raw():
    ...
    
    return '''
    <svg width="100px" height="100px" xmlns="http://www.w3.org/2000/svg">

        <rect height="100%" width="100%" fill="white" />

            <circle cx="50%" cy="45%" r="40%" fill-opacity="0" style="stroke:green; stroke-width:6%; " />

            <text x="20%" y="47%" fill="blue" font-size="1.3em" font-weight="bold">ZERO</text>

            <text x="26%" y="65%" fill="blue" font-size="1em" font-weight="900" >JUDGE</text>


            <line x1="5%" y1="10%" x2="95%" y2="10%" style="stroke:white; stroke-width:30%; "/>

            <line x1="5%" y1="20%" x2="95%" y2="20%" style="stroke:green; stroke-width:10%; "/>

            <line x1="5%" y1="25%" x2="95%" y2="25%" style="stroke:white; stroke-width:5%; "/>
    </svg>
    '''

两个代码的结果:

https://i.imgur.com/GAEXZju.png

是否有任何解决方案可以使用 Flask 显示不带 HTML 标签的 SVG?

为了将数据作为纯 SVG 文件提供,有必要定义响应的 mimetype。因此,浏览器使用 'Content-Type' header 识别文件并正确解释它。

这个例子展示了原始数据的使用。

@app.route('/')
def index():
    svg = '''
    <svg width="100px" height="100px" xmlns="http://www.w3.org/2000/svg">
        <rect height="100%" width="100%" fill="white" />
        <circle cx="50%" cy="45%" r="40%" fill-opacity="0" style="stroke:green; stroke-width:6%; " />
        <text x="20%" y="47%" fill="blue" font-size="1.3em" font-weight="bold">ZERO</text>
        <text x="26%" y="65%" fill="blue" font-size="1em" font-weight="900" >JUDGE</text>
        <line x1="5%" y1="10%" x2="95%" y2="10%" style="stroke:white; stroke-width:30%; "/>
        <line x1="5%" y1="20%" x2="95%" y2="20%" style="stroke:green; stroke-width:10%; "/>
        <line x1="5%" y1="25%" x2="95%" y2="25%" style="stroke:white; stroke-width:5%; "/>
    </svg>
    '''
    return app.response_class(svg, mimetype='image/svg+xml')

使用 render_template 看起来像这样。

@app.route('/')
def index():
    return app.response_class(
        render_template('img.svg'),
        mimetype='image/svg+xml'
    )