1.

What are URL Processors? How to internationalize Blueprint URLs?

Answer»

URL processors are a new feature in Flask 0.7. The notion is that you MAY have a collection of resources with similar components in the URL that you don't always want to SUPPLY explicitly. For example, you might have a bunch of URLs with language code in them, but you don't want to have to deal with it in each and every function.

When used in CONJUNCTION with blueprints, URL processors are extremely useful. We'll deal with both application-specific URL processors and blueprint specifics here.

Internationalized Blueprint URLs: It's simple to PREFIX all URLs with a common string using blueprints, and it's trivial to do so for every function. Furthermore, blueprints can contain per-blueprint URL processors, which takes a lot of complexity from the url_defaults() function by eliminating the need to check if the URL is truly interested in the 'lang_code' parameter:

from flask import Blueprint, G[Text Wrapping Break][Text Wrapping Break]bp = Blueprint('frontend', __name__, url_prefix='/<lang_code>')[Text Wrapping Break][Text Wrapping Break]@bp.url_defaults[Text Wrapping Break]def add_language_code(endpoint, values):[Text Wrapping Break]    values.setdefault('lang_code', g.lang_code)[Text Wrapping Break][Text Wrapping Break]@bp.url_value_preprocessor[Text Wrapping Break]def pull_lang_code(endpoint, values):[Text Wrapping Break]    g.lang_code = values.pop('lang_code')[Text Wrapping Break][Text Wrapping Break]@bp.route('/')[Text Wrapping Break]def index():[Text Wrapping Break]    ...[Text Wrapping Break][Text Wrapping Break]@bp.route('/about')[Text Wrapping Break]def about():[Text Wrapping Break]    ...


Discussion

No Comment Found