Python Web Development with Flask — Favicon, Background Tasks, and HTTP Method Overrides

John Au-Yeung
3 min readJan 31, 2021
Photo by Patrick Tomasso on Unsplash

Flask is a simple web framework written in Python.

In this article, we’ll look at how to develop simple Python web apps with Flask.

Favicon

We can add a favicon by putting it in the static folder and then referencing it.

For example, we can write:

app.py

from flask import send_from_directory, Flask, render_template
import os
app = Flask(__name__)@app.route('/favicon.ico')
def favicon():
return send_from_directory(os.path.join(app.root_path, 'static'),
'favicon.ico', mimetype='image/vnd.microsoft.icon')
@app.route('/')
def hello_world():
return render_template('index.html')

templates/index.html

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

Then we put our favicon.ico file into the static folder.

Now we should see the favicon displayed in our browser’s tab.

Deferred Request Callbacks

We can add callbacks that are called before or after the current request.

For example, we can write:

from flask import Flaskapp = Flask(__name__)@app.before_request
def before_request():
print('before called')
@app.after_request
def after_request(response):
print('after called')
return response
@app.route('/')
def hello_world():
return 'hello world'

We call the @app.before_request to add a callback that’s run before a request is made.

The @app.after_request decorator lets us add a callback that’s run after a request is made.

The response parameter has the response that we return.

HTTP Method Overrides

We can add HTTP method overrides with our own class.

--

--