【Flask】Respones

Flask of HTTPResponse

Copy the code
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)
Copy the code

Flask in the HttpResponse in our view is actually a direct return strings and django in HttpResponse ( "hello word") as

Flask of render

When using a template to render the page we need to import render_template ; and the need to create a templates folder in the project directory used to store html page;

Otherwise, there may be an exception of a Jinja2

Encounter this problem, basically the path to your template problem

Set this folder as a template folder

Copy the code
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)
Copy the code

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

Flask中的redirect

Copy the code
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)
Copy the code

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

Flask返回特殊的格式

返回JSON格式的数据

jsonify

Copy the code
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)
Copy the code

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

发送文件

send_file

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

我们以图片为列:

Copy the code
Import the Flask the Flask from, the send_file 
App = the Flask (name__ __) 

@ app.route ( '/') 
DEF Home (): 
    # Access / return path to a picture 
    return the send_file ( "Templates / jypyter.png") 

IF __name__ == ' __main__ ': 
    app.run ( "0.0.0.0", 9876)
Copy the code

View response header Content-type type

Other content-type

MP3 【Content-Type: audio/mpeg】
MP4 【Content-Type: video/mp4】

Guess you like

Origin www.cnblogs.com/youxiu123/p/11605770.html