Skip to content
Myr

urlprocessors.rst

This file

Path

docs/patterns/urlprocessors.rst

126 lines · 4.2 KiB

Last changed by

Merge branch 'master' of github.com:mitsuhiko/flaskArmin Ronacherbefore adoption30d9efb

History of this file

Take it

1Using URL Processors2====================34.. versionadded:: 0.756Flask 0.7 introduces the concept of URL processors.  The idea is that you7might have a bunch of resources with common parts in the URL that you8don't always explicitly want to provide.  For instance you might have a9bunch of URLs that have the language code in it but you don't want to have10to handle it in every single function yourself.1112URL processors are especially helpful when combined with blueprints.  We13will handle both application specific URL processors here as well as14blueprint specifics.1516Internationalized Application URLs17----------------------------------1819Consider an application like this::2021    from flask import Flask, g2223    app = Flask(__name__)2425    @app.route('/<lang_code>/')26    def index(lang_code):27        g.lang_code = lang_code28        ...2930    @app.route('/<lang_code>/about')31    def about(lang_code):32        g.lang_code = lang_code33        ...3435This is an awful lot of repetition as you have to handle the language code36setting on the :data:`~flask.g` object yourself in every single function.37Sure, a decorator could be used to simplify this, but if you want to38generate URLs from one function to another you would have to still provide39the language code explicitly which can be annoying.4041For the latter, this is where :func:`~flask.Flask.url_defaults` functions42come in.  They can automatically inject values into a call for43:func:`~flask.url_for` automatically.  The code below checks if the44language code is not yet in the dictionary of URL values and if the45endpoint wants a value named ``'lang_code'``::4647    @app.url_defaults48    def add_language_code(endpoint, values):49        if 'lang_code' in values or not g.lang_code:50            return51        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):52            values['lang_code'] = g.lang_code5354The method :meth:`~werkzeug.routing.Map.is_endpoint_expecting` of the URL55map can be used to figure out if it would make sense to provide a language56code for the given endpoint.5758The reverse of that function are59:meth:`~flask.Flask.url_value_preprocessor`\s.  They are executed right60after the request was matched and can execute code based on the URL61values.  The idea is that they pull information out of the values62dictionary and put it somewhere else::6364    @app.url_value_preprocessor65    def pull_lang_code(endpoint, values):66        g.lang_code = values.pop('lang_code', None)6768That way you no longer have to do the `lang_code` assignment to69:data:`~flask.g` in every function.  You can further improve that by70writing your own decorator that prefixes URLs with the language code, but71the more beautiful solution is using a blueprint.  Once the72``'lang_code'`` is popped from the values dictionary and it will no longer73be forwarded to the view function reducing the code to this::7475    from flask import Flask, g7677    app = Flask(__name__)7879    @app.url_defaults80    def add_language_code(endpoint, values):81        if 'lang_code' in values or not g.lang_code:82            return83        if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):84            values['lang_code'] = g.lang_code8586    @app.url_value_preprocessor87    def pull_lang_code(endpoint, values):88        g.lang_code = values.pop('lang_code', None)8990    @app.route('/<lang_code>/')91    def index():92        ...9394    @app.route('/<lang_code>/about')95    def about():96        ...9798Internationalized Blueprint URLs99--------------------------------100101Because blueprints can automatically prefix all URLs with a common string102it's easy to automatically do that for every function.  Furthermore103blueprints can have per-blueprint URL processors which removes a whole lot104of logic from the :meth:`~flask.Flask.url_defaults` function because it no105longer has to check if the URL is really interested in a ``'lang_code'``106parameter::107108    from flask import Blueprint, g109110    bp = Blueprint('frontend', __name__, url_prefix='/<lang_code>')111112    @bp.url_defaults113    def add_language_code(endpoint, values):114        values.setdefault('lang_code', g.lang_code)115116    @bp.url_value_preprocessor117    def pull_lang_code(endpoint, values):118        g.lang_code = values.pop('lang_code')119120    @bp.route('/')121    def index():122        ...123124    @bp.route('/about')125    def about():126        ...