Flask多语言应用自定义URL路由规则实现问题咨询
问题修复步骤
以下修改可直接解决你列出的所有问题:
1. 修复路由参数语法(解决/it/foo//en/foo404问题)
Flask路由变量使用尖括号<>而非大括号{},修改blueprints/www.py中的slug路由:
# 替换原错误写法 @www.route('/{slug}') @www.route('/<slug>') def slug(locale, slug): # 后续会加slug合法性校验 return render_template('slug.html', locale=locale, slug=slug)
2. 修正locale校验逻辑(解决/foo/test匹配test路由、/foo不返回404问题)
原逻辑会将非法locale强制改为默认意大利语,导致任意字符串都被识别为合法locale,直接修改manage_locales方法:
@www.url_value_preprocessor def manage_locales(endpoint, values): if 'locale' not in values: return if values['locale'] not in all_locales: # 非法locale直接返回404,不要替换为默认值 abort(404)
3. 新增默认locale重定向规则(解决/it//it/不跳转到根域名问题)
在blueprints/www.py中新增请求前置处理器,所有带/it/前缀的请求统一301重定向到无前缀路径:
from flask import request @www.before_request def redirect_default_locale(): # 仅处理带locale前缀的蓝图请求 if request.endpoint and request.endpoint.startswith('www.'): locale = request.view_args.get('locale') if locale == default_locale: # 替换路径中的/it/前缀 path = request.full_path.replace(f'/{locale}/', '/', 1) # 适配无尾斜杠的/it场景 if path == request.full_path: path = request.full_path.replace(f'/{locale}', '/', 1) path = path.replace('//', '/') return redirect(path, code=301)
4. 新增slug合法性校验(解决/foo不返回404问题)
如果slug需要对应实际存在的内容,在slug路由中增加存在性判断即可:
@www.route('/<slug>') def slug(locale, slug): # 替换为你的实际合法slug列表,或者从数据库查询判断 valid_slugs = ['about', 'services', 'contact'] if slug not in valid_slugs: abort(404) return render_template('slug.html', locale=locale, slug=slug)
可选优化:限制locale参数匹配范围
可以通过自定义路由转换器从根源上避免非法locale匹配到前缀规则,进一步提升路由匹配效率:
- 在
app.py中注册自定义转换器:
from werkzeug.routing import BaseConverter class LocaleConverter(BaseConverter): regex = '|'.join(['it', 'en']) app = Flask(__name__) app.url_map.converters['locale'] = LocaleConverter
- 修改带前缀蓝图的注册规则:
# 替换原写法 app.register_blueprint(www, name='www', url_prefix='/<locale>') app.register_blueprint(www, name='www', url_prefix='/<locale:locale>')
内容的提问来源于stack exchange,提问作者AndColla
相关产品推荐
相关产品推荐

