這個問題在這里已經有了答案: 如何在 Flask 中提供靜態檔案 24 個答案 4天前關閉。
有沒有可以使用 Flask 顯示沒有 HTML 標簽的 SVG 的解決方案?
我正在構建類似于這個專案的專案,它允許用戶通過生成影像(在 SVG 中)用戶的統計資訊在他們的靜態網站上顯示他們當前的統計資訊。
根據我的理解,這個概念是:
- 使用 GET 引數來指定用戶的資料,主題...等
- 服務器查詢用戶資料
- 服務器回傳一個帶有用戶資料的 svg
來自存盤庫的示例:
https://github-readme-streak-stats.herokuapp.com/?user=DenverCoder1
示例的結果:
https://i.imgur.com/Kc9hMzT.png
我在python Flask中撰寫了后端
但是,我找不到僅按燒瓶顯示 svg 的解決方案
我已經嘗試過SVG 的render_template()方法或return原始字串,它們都不能只顯示沒有 html 標記的 SVG
- 使用
render_template()
@app.route("/test_rend" , methods=['GET'])
def Test_rend():
...
return render_template("img.svg")
- 回傳 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 的解決方案?
uj5u.com熱心網友回復:
為了將資料作為純 SVG 檔案提供,有必要定義回應的 mimetype。因此,瀏覽器使用“Content-Type”標頭識別檔案并正確解釋它。
這個例子展示了原始資料的使用。
@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'
)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/447392.html
上一篇:慣性垂直拖動滾動
