Top Flask 2.0 features you must checkout

Top Flask 2.0 features you must checkout

Flask - the most popular light-weight Python WSGI web framework, has released its latest version Flask 2.0.0. Here is the top 6 things that you must know about latest flask.

Flask installation

To enable async support in Flask, we must install it with async support packages. To use flask in windows, you must use Python 3.9.

pip install 'flask[async]'

Async functions support

Flask now supports async views, error handlers, before and after request, and teardown functions.This means you can use both synchronous and asynchronous code in flask, for example to use aiohttp to concurrently make requests. asyncpg to make asyncronous database calls.

"""
pip install 'flask[async]'
pip install aiohttp
"""

from flask import Flask, jsonify
import asyncio
import aiohttp

app = Flask(__name__)


async def async_fetch(session, url, params=None):
    async with session.get(url, params=params) as response:
        return response.status


@app.route('/')
async def async_hello():
    async with aiohttp.ClientSession(connector=aiohttp.TCPConnector(ssl=False)) as session:
        tasks = []
        urls = ('https://hashnode.com/', 'https://sureshdsk.dev/')
        for url in urls:
            tasks.append(
                async_fetch(session, url)
            )
        responses = await asyncio.gather(*tasks)
    response = dict(zip(urls, responses))
    return jsonify(response)


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

Short form route handler

Flask now support short form route decorators for declaring single HTTP-method route. i.e. app.get, app.post, app.patch, app.put, and app.delete.

@app.get('/sync')
def hello():
    """
    short form for @app.route('/sync', methods=['GET'])
    """
    return jsonify({'Hello': 'World!!'})

Type hints

Flask 2.0 is now fully type hinted. For the folks who like to implement static typing, especially flask extension developers, this would be very helpful

Lets take a look at app.run() method

def run(
        self,
        host: t.Optional[str] = None,
        port: t.Optional[int] = None,
        debug: t.Optional[bool] = None,
        load_dotenv: bool = True,
        **options: t.Any,
    ) -> None:

Nested blueprints

Flask blueprints is one of my favourite feature, since it helps to structure application code. Flask 2.0 Blueprints now supports nested blueprints.

from flask import Flask, Blueprint, jsonify

app = Flask(__name__)

user_app = Blueprint('user', __name__)
user_management_app = Blueprint('user_management', __name__)


@app.get('/')
def home():
    return jsonify({'Hello': 'World!!', 'app': 'main'})


@user_app.get('/')
def user_home():
    return jsonify({'Hello': 'World!!', 'app': 'user_app'})


@user_app.get('/test')
def user_hello():
    return jsonify({'Test': 'OK', 'app': 'user_app'})


@user_management_app.get('/')
def user_management_home():
    return jsonify({'Hello': 'World!!', 'app': 'user_management_app'})


@user_management_app.get('/test')
def user_management_hello():
    return jsonify({'Test': 'OK', 'app': 'user_management_app'})


user_app.register_blueprint(user_management_app, url_prefix='/admin')
app.register_blueprint(user_app, url_prefix='/user')


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

So we can have routes from nested blueprints below

/
/user/
/user/test
/user/admin
/user/admin/test

Config file

It is now easier to load configuration from your favourite file format using the Config's from_file method. We can use toml.load or json.load to load toml or json file respectively.

config.toml

DEBUG = true
DATABASE_URI = "sqlite:////tmp/foo.db"
"""
pip install toml
"""
from flask import Flask, jsonify
import toml

app = Flask(__name__)
app.config.from_file("config.toml", load=toml.load)


print('='*20)
print('Using ', app.config['DATABASE_URI'])


@app.get('/')
def home():
    return jsonify({'Hello': 'World!!', 'app': 'main'})


if __name__ == '__main__':
    app.run()

So are you excited? what is the feature from flask 2.0 that you like the most? Comment below!

Did you find this article valuable?

Support Suresh Kumar by becoming a sponsor. Any amount is appreciated!