Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

favicon.ico results in 404 error in flask app

I found a lot of entries in my logfile, which indicate that somebody tried to load /favicon.ico and similar files

GET - /favicon.ico
GET - /apple-touch-icon.png
GET - /apple-touch-icon-precomposed.png

I read a lot about this issue online, but I can't get rid of it. Here is what I trued. First I added the following to my head tag

<link rel="shortcut icon" href="/static/favicon/favicon.ico" type="image/x-icon">

However, even though I provide this information in my header, there seem to be browsers out there which don't care about it and still call /favicon.ico? So I thought just putting the ico file at root and be done with it, but it does not seem to work? If I call

http://localhost:5000/static/favicon/favicon.ico

I get to the icon, but

http://localhost:5000/favicon.ico

Does not work (gives 404)? I cleared my cache and tried it with Chrome and Safari, but I get 404 in both cases? I am really at a loss here. If I move the image in the static folder and call

http://localhost:5000/static/favicon.ico

it works, but the root folder doesn't? What am I missing here?

like image 336
carl Avatar asked Feb 19 '18 09:02

carl


2 Answers

By default, the flask will only serve files on the /static endpoint. You can add a custom view to handle the default /favicon request.

The flask documentation has some more information on this subject:

https://flask.palletsprojects.com/en/1.1.x/patterns/favicon/

import os 
from flask import send_from_directory     

@app.route('/favicon.ico') 
def favicon(): 
    return send_from_directory(os.path.join(app.root_path, 'static'), 'favicon.ico', mimetype='image/vnd.microsoft.icon')
like image 94
gtalarico Avatar answered Oct 01 '22 22:10

gtalarico


I ran into a very similar problem. I do not have the necessary points to add a comment to the answer yet. So I'll do it using "Your answer". For those who need a much more specific answer on how to use url_for () here is one way to do it.

<!-- Adding a favicon icon to Flask app -->
<!-- SEE: https://favicon.io/favicon-converter/-->

<link rel="shortcut icon"
      href="{{ url_for('static', filename='favicon.ico') }}">

<link rel="apple-touch-icon"
      sizes="180x180"
      href="{{ url_for('static', filename='apple-touch-icon.png') }}">

<link rel="icon"
      type="image/png"
      sizes="180x180"
      href="{{ url_for('static', filename='favicon-32x32.png') }}">

<link rel="icon"
      type="image/png"
      sizes="16x16"
      href="{{ url_for('static', filename='favicon-16x16.png') }}">

<link rel="manifest"
      href="site.webmanifest">

To generate the necessary files use the following link: https://favicon.io/favicon-converter/ All files were copied into the /static directory.

like image 44
Ramiro Avatar answered Oct 02 '22 00:10

Ramiro