【问题标题】:how can I load svg file into my python flask page? [duplicate]如何将 svg 文件加载到我的 python 烧瓶页面中? [复制]
【发布时间】:2018-11-23 20:26:23
【问题描述】:

所以我想将一个 svg 文件放入我的页面中(不是作为图像,而是作为 xml 元素) - 需要这样的文件,以便我可以动态更改页面中的元素。

我做了一个简单的代码,我认为它会做:

@app.route('/map_test/')
def test():
   svg = render_template('file.svg')
   response = make_response(svg)
   response.content_type = 'image/svg+xml'
   return render_template('test.html', svg=response)

和test.html:

{% block content %}
<section>
    {{ svg }}
</section>
{% endblock %}

....刚刚返回 &lt;Response 126181 bytes [200 OK]&gt; 而不是 svg 元素...

所以...我需要做什么才能让它发挥作用?

【问题讨论】:

  • 你的进口是什么?
  • 从烧瓶导入 make_response、render_template、请求

标签: python svg flask


【解决方案1】:

这成功了:

from flask import Markup

@app.route('/map_test/')
def test():
   svg = open('file.svg').read
   return render_template('test.html', svg=Markup(svg))

【讨论】:

  • 标记()?你导入这个功能了吗?它是自定义功能吗?它是一个内置函数吗?请编辑您的答案。谢谢
  • 我猜你需要调用 read。所以 svg = open('file.svg').read()
【解决方案2】:
from flask import Flask, render_template

app = Flask(__name__)


@app.route('/')
def hello_world():
   img = './static/download.svg'

   return render_template('index.html', img=img)


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

index.html

<!DOCTYPE html>
<html lang="en">
<body>
<img src="{{ img }}">
</body>
</html>

将您的 svg 文件放在名为 static 的目录中

【讨论】:

  • 嗯...我希望我的 svg 元素是动态的,这就是为什么我一直在尝试加载完整的 svg 元素...这会让我将我的 svg 文件加载为图片但不允许我动态更改元素。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 2015-06-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多