如何在不上传网站图标文件的情况下将网站图标添加到 Google colab 上的 Flask 路线?

问题描述

我想在 Google Colab 上的 Flask 应用程序上向路线 (/) 添加收藏图标,以便它停止发送返回 404 的第二个 GET 请求。

我该怎么做?

我看过各种帖子,但它们都包含 HTML 文件,而我想在 Google Colab 本身上执行此操作,而不必每次都上传图像?

import os
from flask import send_from_directory,Flask

app = Flask(__name__)
run_with_ngrok(app)  

@app.route('/')
def index():
    return '<h1>Hello!</h1>'

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

解决方法

如果您在 Google Colab 上并且不想上传或存储任何静态 HTML 文件或 favicon.ico 文件,您可以只使用 return an entire HTML page from a string,然后使用 <head> 块链接到一些网站图标文件。

from flask import Flask,render_template_string
from flask_ngrok import run_with_ngrok

app = Flask(__name__)
run_with_ngrok(app)  

# Here I'm using a favicon.ico of a pizza from some random generator site
FAVICON_URL='https://favicon-generator.org/favicon-generator/htdocs/favicons/2015-01-17/50e4281252565f8fc85151c075d4e937.ico'

@app.route("/")
def hello():
    content='Hello!'
    return render_template_string(f'''<!doctype html>
<html>
    <head>
        <link rel="icon" href="{FAVICON_URL}">
    </head>
    <body>
        <h1>{content}</h1>
    </body>
</html>
''')

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

这消除了 /favicon 上的 404(并实际显示了一个图标):

using external favicon

如果您不关心显示实际图标,您可以尝试使用 href="data:," 将其保留为“空”,如这篇文章 this answer 中的 How to prevent favicon.ico requests? 建议:

@app.route("/")
def hello():
    content='Hello!'
    return render_template_string(f'''<!doctype html>
<html>
    <head>
        <link rel="icon" href="data:,">
    </head>
    <body>
        <h1>{content}</h1>
    </body>
</html>
''')

using empty favicon

两种解决方案似乎都适用

  • Google Colab
  • Flask 1.1.2 和 flask-ngrok 0.0.25
  • macOS 上的 Firefox 88 和 Chrome 90

此处可能存在的问题是必须将整个 HTML 页面维护为内联字符串,这可能不安全且繁琐 ("Generating HTML from within Python is not fun")。我不知道您计划制作的网络应用程序有多复杂。这在 Google Colab 上是有意义的,但使用带有静态 HTML 文件(+ Jinja 模板)的设置可能更易于维护。