Emilio Garcia
Emilio Garcia

Reputation: 576

Adding a favicon to a Flask server without HTML

My flask server constantly reports

xx.xxx.xxx.xxx - - [DD/MM/YYYY HH:MM:SS] "GET /favicon.ico HTTP/1.1" 404 -

In the code for my flask server I've added,

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),'favicon.ico', mimetype='image/vnd.microsoft.icon')

and I've added a favicon titled favicon.ico to the same directory that my flask server is running from.

Favicon location

If I try to navigate to http://www.myurl.com/favicon.ico I get a 404. My flask server isn't serving an html landing page so I can't add <link rel='shortcut icon' href='favicon.ico' type='image/x-icon'/ > anywhere. I don't really care about actually having a favicon, I just want to stop the error from showing up. How can I serve a favicon/stop the error?

Upvotes: 30

Views: 34498

Answers (2)

JayRizzo
JayRizzo

Reputation: 3616

For what it is worth, This worked for me:

from flask import url_for

# Load Browser Favorite Icon
@app.route('/favicon.ico')
def favicon():
    return url_for('static', filename='image/favicon.ico')

.

I have my images in the image folder inside of the static folder.

-- app
  -- static
    -- image
      -- favicon.ico
PS: This was on 
MacOS 12.6 (21G115)
Python 3.10.8
Flask 2.2.2
Jinja2 3.1.2
Viewing in Brave Browser v1.45.116 (Oct 28th, 2022)

Upvotes: 7

Raj Pandey
Raj Pandey

Reputation: 523

Put the icon in your static directory as favicon.ico. and below code in python file

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

href - http://flask.pocoo.org/docs/0.12/patterns/favicon/

Upvotes: 52

Related Questions