烧瓶网址处理器

时间:2020-03-23 21:31:01

标签: url flask routes internationalization

我正在为两种语言构建flask Web应用程序。 我读了https://flask.palletsprojects.com/en/1.1.x/patterns/urlprocessors/#internationalized-application-urls

 from flask import Flask, g

app = Flask(__name__)

@app.url_defaults
def add_language_code(endpoint, values):
    if 'lang_code' in values or not g.lang_code:
        return
    if app.url_map.is_endpoint_expecting(endpoint, 'lang_code'):
        values['lang_code'] = g.lang_code

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    g.lang_code = values.pop('lang_code', None)

@app.route('/<lang_code>/')
def index():
    ...

@app.route('/<lang_code>/about')
def about():
    ...

但是,我不明白“值”的确切含义。 我也运行了代码,但是它给出了以下错误。

g.lang_code = values.pop('lang_code',None)

AttributeError:'NoneType'对象没有属性'pop'

您能提供任何建议吗?谢谢!

1 个答案:

答案 0 :(得分:0)

我正在研究与您相同的教程,发现使用尾部斜杠(例如 example.com/en/)可以正常工作,但是在尝试加载路由而不输入时出现 AttributeError: 'NoneType' object has no attribute 'pop' 错误浏览器中的尾部斜杠(例如 example.com/en)。

默认情况下,Flask 无论如何都会将非尾随斜杠 URL 重定向到尾随斜杠,所以我只是通过添加最低限度来解决这个问题以避免错误:

@app.url_value_preprocessor
def pull_lang_code(endpoint, values):
    if values is None:
        values = {}
    g.lang_code = values.pop('lang_code', None)