zoukankan      html  css  js  c++  java
  • Flask基础(06)-->视图常用逻辑

     Flask基础(06)-->视图常用逻辑

    • 返回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)

      2.重定向

        也可以使用 url_for 生成指定视图函数所对应的 url

    @app.route('/user/demo1')
    def demo1():
        return 'demo1'
    
    # 重定向到demo1
    @app.route('/demo5')
    def demo5():
        return redirect(url_for('demo1'))#通过函数名去寻找路由
    # 重定向到百度
    @app.route('/demo5')
    def demo5():
        return redirect('http://www.baidu.com')

    重定向到带有参数的视图函数

    • 在 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))
    • 自定义状态码
    @app.route('/demo6')
    def demo6():
        return '状态码为 666', 666
  • 相关阅读:
    四大组件的工作过程
    理解Window和WindowManager
    Android中的动画
    View的工作原理
    62、滑动窗口的最大值
    61、数据流中的中位数
    60、二叉搜索树的第k个结点
    59、序列化二叉树
    58、把二叉树打印成多行
    57、按之字形顺序打印二叉树
  • 原文地址:https://www.cnblogs.com/888888CN/p/9470798.html
Copyright © 2011-2022 走看看