zoukankan      html  css  js  c++  java
  • 第二篇 Flask的Response三剑客及两个小儿子

    一、Response三剑客

    (一)Flask中的HTTPResponse

    @app.route("/")             #app中的route装饰器
    def index():                #视图函数
        return "Hello World"

    在Flask 中的HttpResponse 在我们看来其实就是直接返回字符串。

    (二)Flask中的Redirect

    @app.route("/")             #app中的route装饰器
    def index():                #视图函数
        return redirect("/login")

    (三)Flask中的render(render_template)

    @app.route("/")             #app中的route装饰器
    def index():                #视图函数
        return render_template("home.html")

    注意: 如果要使用 render_template 返回渲染的模板,请在项目的主目录中加入一个目录 templates

    否则可能会有一个Jinja2的异常哦

    遇到上述的问题,基本上就是你的template的路径问题

    二、两个小儿子

    (一)from flask import jsonify

    from flask import jsonify
    
    @app.route("/")
    
    def index():
        return jsonify({"name","fengchong"})

    jsonify里面放的是一个字典的数据类型,给前端返回的是一个标准的json字符串,并且将响应头的Content-Type改为application/json

    (二)from flask import send_file

    from flask import send_file
    
    @app.route("/")
    
    def index():
        return send_file(path)

    send_file 相当于做了下面几件事:打开文件并返回文件内容,且自动识别文件格式,并修改Content-Type类型。

  • 相关阅读:
    SQL Server 2008 PREEMPTIVE_OS_GETPROCADDRESS 等待类型
    数据库使用 jemalloc 内存优化算法
    my.cnf 推荐配置
    WIN 命令合成一个大内存的图片怎么搞
    jupyter notebook加载DDP预训练模型
    model.add_module
    einsum爱因斯坦求和
    skimage.measure.label
    easyocr下载模型失败
    测试面试题 05
  • 原文地址:https://www.cnblogs.com/fengchong/p/10245522.html
Copyright © 2011-2022 走看看