• 【Flask教程03】视图常用逻辑


    视图常用逻辑

    • 返回 JSON
    • 重定向
      • url_for
    • 自定义状态码

    1、返回JSON

    在使用 Flask 写一个接口时候需要给客户端返回 JSON 数据,在 Flask 中可以直接使用 jsonify 生成一个 JSON 的响应

    # 返回JSON
    @app.route('/demo4')
    def demo4():
        json_dict = {
            "user_id": 10,
            "user_name": "laowang"
        }
        return jsonify(json_dict)
        # return json_dict  # 字典对象不可直接调用

    不推荐使用 json.dumps 转成 JSON 字符串直接返回,因为返回的数据要符合 HTTP 协议规范,如果是 JSON 需要指定 content-type:application/json

    2、重定向

    • 重定向到 百度 官网
    # 重定向
    @app.route('/demo5')
    def demo5():
        return redirect('http://www.baidu.com')
    • 重定向到自己写的视图函数
      • 可以直接填写自己 url 路径
      • 也可以使用 url_for 生成指定视图函数所对应的 url
    @app.route('/demo1')
    def demo1():
        return 'demo1'
    
    # 重定向
    @app.route('/demo5')
    def demo5():
    # return redirect(url_for('demo1'))
    return redirect('/demo1')
    • 重定向到带有参数的视图函数
      • 在 url_for 函数中传入参数
    # 路由传递参数
    @app.route('/user/<int:user_id>')
    def user_info(user_id):
        return 'hello %d' % user_id
    
    # 重定向
    @app.route('/demo5')
    def demo5():
        # 使用 url_for 生成指定视图函数所对应的 url
        return redirect(url_for('user_info', user_id=100))

    3、自定义状态码

    • 在 Flask 中,可以很方便的返回自定义状态码,以实现不符合 http 协议的状态码,例如:status code: 666
    @app.route('/demo6')
    def demo6():
        return '状态码为 666', 666

     

  • 相关阅读:
    简单的理解原型链
    react->Context笔记
    工作上git指令小结
    vue 绑定事件如何传递参数的同时拿到事件对象
    vsCode卸载后重新安装,以前的插件有没有效果的解决方法
    mongo 分组 aggregation
    Redisson分布式锁原理
    Virtual server server already has a web module live-mix-1.0.2-t230 loaded at / therefore web module
    二进制中 1 的个数
    替换空格
  • 原文地址:https://www.cnblogs.com/zeug/p/11362888.html
Copyright © 2020-2023  润新知