zoukankan      html  css  js  c++  java
  • Flask-Response

    Flask中的HTTPResponse

    from flask import Flask,redirect
    app = Flask(__name__)
    
    @app.route("/index")
    def index():
        return "hello word"    # HttpResponse【返回字符串】
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    在Flask 中的HttpResponse 在我们看来其实就是直接返回字符串和django中的HttpResponse("hello word")一样

    Flask中的render

    使用模板渲染页面时我们需要导入render_template;并且需要在项目的目录下创建一个templates文件夹用来存放html页面;

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

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

    设置该文件夹为模板文件夹

    from flask import Flask,render_template
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        # 模板渲染
        return render_template("home.html")
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    flask的模板渲染和django的模板渲染差不多,只不过django用的render而flask用render_template

    Flask中的redirect

    from flask import Flask,redirect      # 导入redirect
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        # 访问/重定向到index页面
        return redirect("/index")
    
    @app.route("/index")
    def index():
        return "hello word"    # HttpResponse
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    每当访问/就会重定向到index页面

    Flask返回特殊的格式

    返回JSON格式的数据

    jsonify

    from flask import Flask,jsonify
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        return jsonify({"name":"henry","age":18})
        # 在Flask 1.1.1 版本中 可以直接返回字典类型 可以不再使用jsonify了
        # return {"name":"henry","age":18}
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    响应头中加入 Content-type:application/json

    发送文件

    send_file

    打开并返回文件内容,
    自动识别文件类型,
    响应头中加入Content-type:文件类型
    ps:当浏览器无法识别Content-type时,会下载文件

    我们以图片为列:

    from flask import Flask,send_file
    app = Flask(__name__)
    
    @app.route('/')
    def home():
        # 访问/路径给返回一个图片
        return send_file("templates/jypyter.png")
    
    if __name__ == '__main__':
        app.run("0.0.0.0",9876)

    查看响应头中的Content-type类型

    其他content-type

    MP3 【Content-Type: audio/mpeg】
    MP4 【Content-Type: video/mp4】
  • 相关阅读:
    H5及微信中唤起app的解决方案
    html5统计数据上报API:SendBeacon
    基于webpack4的react开发环境配置
    electron-vue开发爬坑指南
    利用git 进行多人协作开发
    js 性能优化利器:prepack
    各种渲染方式对比解析
    Nuxt.js部署应用的方式
    微信小程序--data的赋值与取值
    甘超波:什么是个人定位
  • 原文地址:https://www.cnblogs.com/songzhixue/p/11164765.html
Copyright © 2011-2022 走看看