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】
