【Flask】Respones

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】
原文地址:https://www.cnblogs.com/youxiu123/p/11605770.html