本文共 2738 字,大约阅读时间需要 9 分钟。
Flask 是一款高效的微框架,其路由系统是核心功能之一。在很多 Web 应用中,接口通常遵循 RESTful API 设计风格,这种风格简洁而优雅,对开发者和用户都很友好。通过 Flask 的路由系统,开发者可以将 URL 映射到相应的视图函数,从而实现数据处理和返回。
在 Flask 框架中,route() 装饰器是实现路由映射的核心工具。装饰器的使用非常方便,开发者只需要关注业务逻辑和数据处理,不用担心路由配置。
FlaskProject 的虚拟环境,项目目录下创建 flask_route.py 文件。from flask import Flaskapp = Flask(__name__)
@app.route('/') 装饰后端功能,访问指定的 URL 视图函数。from flask import Flaskapp = Flask(__name__)@app.route('/index')def index(): return render_template('route_one.html')if __name__ == '__main__': app.run(debug=True) @app.route('/index'):定义了当访问 /index 时会调用 index() 视图函数。render_template('route_one.html'):将结果传递给模板文件进行展示。app.run():开启 Flask 应用服务器。在实际应用中,API demands 通常需要动态处理数据。Flask 的路由允许将 URL 中的参数传递给视图函数。
@app.route('/phone/ ')def phone(num): return render_template('route_one.html', num=num) /phone/{num},例如 /phone/123。num 参数,返回模板文件,模板可展示数值。@app.route('/phone/ ') 使用 int 确定 num 为整数类型。
在有些场景中,需要对 URL 参数进行验证,确保符合特定格式。Flask 提供了强大的路由转换功能,允许使用正则表达式对 URL 参数进行匹配。
Flask 的转换器接口允许开发者自定义规则,根据需求添加正则匹配功能。
werkzeug.routing 中的转换器基类:from werkzeug.routing import BaseConverter
BaseConverter 的新转换器类:class RegexConverter(BaseConverter): def __init__(self, url_map, *args): super(RegexConverter, self).__init__(url_map) self.regex = args[0]
regex属性用于存储正则表达式模式。app.url_map.converters['re'] = RegexConverter
@app.route('/phones/ ')def phone_size(phone_num): return render_template('route_one.html', phone_num=phone_num) /phones/{符合正则规则的数字},例如 /phones/1234。phone_num 参数。以下是完整的代码示例,展示了路由基础使用、路由传参以及正则匹配的综合应用:
from flask import Flask, render_templatefrom werkzeug.routing import BaseConverterapp = Flask(__name__)@app.route('/index')def index(): return render_template('route_one.html')@app.route('/phone/ ')def phone(num): return render_template('route_one.html', num=num)# 定义自定义正则转换器class RegexConverter(BaseConverter): def __init__(self, url_map, *args): super(RegexConverter, self).__init__(url_map) self.regex = args[0]# 将转换器添加到 Flask 的 URL 映射中app.url_map.converters['re'] = RegexConverter@app.route('/phones/ ')def phone_size(phone_num): return render_template('route_one.html', phone_num=phone_num)if __name__ == '__main__': app.run(debug=True) /index: 显然是默认访问页面。/phone/123: 接收任意字母和数字参数,展示动态数值。/phones/1234: 只接受数字,验证参数格式。这种配置方式既支持动态传参,也可以进行参数验证,适合复杂的 API 接口需求。
Flask 的路由系统灵活且强大,支持动态传参和自定义转换器,可根据项目需求灵活配置。通过合理使用 route() 装饰器,开发者可以轻松实现高效的接口映射。当需要对 URL 参数格式进行验证时,自定义转换器是非常有用的工具。
转载地址:http://mgspz.baihongyu.com/