如何在不上传 favicon 文件的情况下将 favicon 添加到 Google colab 上的 Flask 路由?

Posted

技术标签:

【中文标题】如何在不上传 favicon 文件的情况下将 favicon 添加到 Google colab 上的 Flask 路由?【英文标题】:How to add a favicon to a Flask route on Google colab without uploading a favicon file? 【发布时间】:2021-07-31 15:36:57 【问题描述】:

我想在 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()

【问题讨论】:

您想这样做而不上传/存储实际的 favicon.ico? 嗨@GinoMempin,是的,这可能吗?因为 google colab 不会将图像永久存储在那里。是否可以改为使用 favicon.ico 的链接? 【参考方案1】:

如果您在 Google Colab 上并且不想上传或存储任何静态 HTML 文件或 favicon.ico 文件,您可以只使用 return an entire HTML page from a string,然后使用带有指向某些 favicon 链接的 &lt;head&gt; 块文件。

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(实际上显示了一个图标):

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

@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>
''')

这两种解决方案似乎都有效

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 模板)的设置可能更易于维护。

【讨论】:

嗨吉诺!非常感谢您的详细回答,这正是我想要的!我对 html 和 api 真的很陌生,所以我不确定如何将我在许多以前提出的问题中找到的答案合并到我的程序中。所以你的回答真的解决了我的问题!非常感谢!!

以上是关于如何在不上传 favicon 文件的情况下将 favicon 添加到 Google colab 上的 Flask 路由?的主要内容,如果未能解决你的问题,请参考以下文章

如何在不包含节点模块文件夹的情况下将我的 React 项目上传到 GitHub [重复]

如何在不使用 SDK 的情况下将文件从 Android 上传到 Amazon S3

如何在不创建 IAM 用户的情况下将文件从 EKS 上传到 S3 存储桶?

如何在不丢失 exif 数据的情况下将 UIImage 转换为 JPEG?

Python 3:如何在不保存在磁盘上的情况下将 pandas 数据帧作为 csv 流上传?

在不使用字符串的情况下将图像上传到android中的服务器