组团学

reponse对象(响应对象)

阅读 (189756)

一、作用

返回给客户端的信息

2、概述

request对象是有服务创建的,response对象需要程序员手动创建

3、创建response对象

  • 导入
    from flask import make_response

  • 原型
    def make_response(*args):
    def make_response(info, status, headers):

  • 参数
    info 必选参数 返回的数据
    status 可选参数 响应状态码
    headers 可选参数 子主题

  • 示例

    @app.route("/res/") def res(): response = make_response("lucky is a good man", 200, {"Content-Type": "text/plain; charset=utf-8"}) return response
  • 注意

    可以直接返回一个字符串,flask会自动包装成response对象

4、响应数据

  • 返回字符串数据

    @app.route("/res1/") def res(): response = make_response("lucky is a good man", 200, {"Content-Type": "text/plain; charset=utf-8"}) return response
  • 返回json数据

    from flask import json @myApp.route("/res2/") def res3(): return jsonify({'name':'lucky', 'age':18})
  • 返回页面

    @myApp.route("/res3/") def res3(): return render_template("index.html")

5、状态码

  • 作用

    告诉客户端对于请求处理结果的状态

  • 使用方式

    方式一

    @myApp.route("/res4/") def res4(): response = make_response("lucky is a good man", 999) return response

    方式二

    @myApp.route("/res4/") def res4(): response = make_response("lucky is a good man") return response,999

6、重定向 与 反向解析

  • 重定向作用

    可以直接通知浏览器转向到另一个地址

  • 导入

    from flask import redirect,url_for

    redirect:重定向 通过传递路由地址参数 进行重定向跳转

    url_for: 反向解析 将当前的视图函数名称反向构造出 路由地址

  • redirect 重定向使用

    # 使用redirect @app.route('/redirect/') def my_redirect(): # 去首页 无参路由 return redirect('/') # 带一个参数的路由地址的重定向 return redirect('/arg/lucky/') # 带多个参数的路由地址的重定向 return redirect('/args/lucky/18/')
  • url_for 反向解析使用

    # 使用url_for 的视图函数 @app.route('/url_for/') def my_urlfor(): # 构造首页路由 print(url_for('index')) # / # 给url_for 一个带参的视图函数 但是没给参数 会报错werkzeug.routing.BuildError: Could not build url for endpoint 'arg'. Did you forget to specify values ['name']? print(url_for('arg')) # 带一个参数 给参数 print(url_for('arg',name='lucky')) # /arg/lucky/ # 带多个参数的视图函数 # werkzeug.routing.BuildError: Could not build url for endpoint 'args'. Did you forget to specify values ['age', 'name']? print(url_for('args')) # 带参数 print(url_for('args',name='lucky',age=18)) #/args/lucky/18/ return 'url_for'
  • redirect和url_for的组合使用

    # redirect 和 url_for的组合使用 @app.route('/ru/') def ru(): # 去首页 return redirect(url_for('index')) # 去一个参数的路由地址 return redirect(url_for('arg',name='lucky')) # 去多个参数的路由地址 return redirect(url_for('args',name='lucky',age=18))

7、终止执行

  • 概述

    • 如果是视图函数执行过程中出现了错误,可以通过abort函数立即终止视图函数的执行

    • 通过abort函数,可以向前端返回一个http标准中存在的状态码,表示出现的错误信息。使用abort函数返回http标准中不存在的状态码是没有任何实际意义的

    • 如果触发了abort函数,那么其后面的代码不会被执行 类似于python中的raise

  • 导入

    from flask import abort

  • 使用

    # 终止 @app.route('/abort/') def err(): # 使用abort函数不是说控制权就归你了,它只是向系统抛出了指定的异常 # 异常的处理仍然会按照框架中写好方式进行 abort(404) return 'abort测试' # 错误页面定制 @app.errorhandler(404) def page_not_found(err): return err """ Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again. """
需要 登录 才可以提问哦