视图常用逻辑
返回JSON
在使用 Flask 写一个接口时候需要给客户端返回 JSON 数据,在 Flask 中可以直接使用 jsonify 生成一个 JSON 的响应
| |
| @app.route('/demo4') |
| def demo4(): |
| json_dict = { |
| "user_id": 10, |
| "user_name": "laowang" |
| } |
| return jsonify(json_dict) |
不推荐使用 json.dumps 转成 JSON 字符串直接返回,因为返回的数据要符合 HTTP 协议规范,如果是 JSON 需要指定 content-type:application/json
重定向
| |
| @app.route('/demo5') |
| def demo5(): |
| return redirect('http://www.www.taobao.com') |
- 重定向到自己写的视图函数
- 可以直接填写自己 url 路径
- 也可以使用 url_for 生成指定视图函数所对应的 url
| |
| @app.route('/demo1') |
| def demo1(): |
| return 'demo1' |
| |
| |
| @app.route('/demo5') |
| def demo5(): |
| return redirect(url_for('demo1')) |
| |
| @app.route('/user/<int:user_id>') |
| def user_info(user_id): |
| return 'hello %d' % user_id |
| |
| |
| @app.route('/demo5') |
| def demo5(): |
| |
| return redirect(url_for('user_info', user_id=100)) |
自定义状态码
- 在 Flask 中,可以很方便的返回自定义状态码,以实现不符合 http 协议的状态码,例如:status code: 666
| @app.route('/demo6') |
| def demo6(): |
| return '状态码为 666', 666 |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?