Search code examples
python-3.xflaskfavicon

adding a favicon to flask


I'm trying to follow the instructions given here: Adding a favicon to a Flask server without HTML on how to add a favicon to a flask app, however its not working for me. Here is my application file:

from flask import Flask,send_from_directory
application=Flask(__name__)

@application.route('/')
def main():
    return '<html><p>hello world</p></html>'

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

if __name__=='__main__': application.run(debug = True)

and here is my directory structure:

➜  demo ls -R
application.py static

./static:
favicon.ico

When I run the application in Firefox, no favicon is shown, and when I run it in Chrome, the default favicon is shown. I used this website to convert a png into an ico file: https://www.freeconvert.com/png-to-ico

Please let me know where I'm going wrong.

When I run the app in chrome, I get this error in the console:

GET http://localhost:5000/favicon.ico 500 (INTERNAL SERVER ERROR)

Solution

  • I needed to import os, here is the working application:

    from flask import Flask,send_from_directory
    import os
    application=Flask(__name__)
    
    @application.route('/')
    def main():
        return '<html><p>hello world</p></html>'
    
    @application.route('/favicon.ico')
    def favicon():
        return send_from_directory(os.path.join(application.root_path, 'static'),
            'favicon.ico',mimetype='image/vnd.microsoft.icon')
    
    if __name__=='__main__': application.run(debug = True)