flask之response


 1     import os
 2     from flask import Flask,render_template,redirect,jsonify,send_file
 3     app=Flask(__name__)
 4     
 5     #開發中開啟debug模式,也可以直接在app.run()中設置參數
 6     # app.debug=True
 7     # app.config['DEBUG']=True
 8     
 9     
10   #(1)flask中的return類似django中的return HttpResponse()
11     #return直接返回文本內容,在1.1.1版本之后可以返回字符串、字典、元組等,
12     # The return type must be a string, dict, tuple, Response instance, or WSGI callable
13     @app.route('/')
14     def home():
15         return  'first_flask'
16     
17     # @app.route('/')
18     # def home():
19     #     return  {'key':'first_flask' }
20     
21     #(2)flask中的return render_template() 類似django中的return render()
22     #return render_teplate()返回靜態文件頁面
23     @app.route('/index')
24     def index():
25         return render_template('index.html')
26     
27     
28     #(3)flask中的return redirect()類似django中的return redirect()重定向302臨時
29     #return redirect()重定向請求
30     @app.route('/reback')
31     def reback():
32         return redirect('/index')
33     
34     
35     
36     #(4)flask中的jsonify()支持直接發送json數據類型,response-headers中的content-type:applicaiton/json
37     @app.route('/flask_json')
38     def flask_json():
39         return jsonify(['a',2])
40     
41     
42     #(5)flask中的return send_file()直接可以返回文件
43     #后端會對send_file返回的文件進行自動識別,類未識別或者瀏覽器不能解析的就會直接下載
44     @app.route('/flask_file')
45     def flask_file():
46         filepath=os.path.join(os.path.dirname(os.path.abspath(__file__)),'file')
47         filename='1.png'      #Content-Type: image/png
48         #filename='1.mp3'      #Content-Type: audio/mpeg
49         #filename='1.mp4'       #Content-Type: video/mp4
50         # filename = '1.pdf'    #Content-Type: application/pdf
51         # filename = '1.pptx'   #Content-Type: application/vnd.openxmlformats-officedocument.presentationml.presentation
52         # filename = '1.docx'   #Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document
53         # filename='1.zip'      #Content-Type: application/x-zip-compressed
54         # filename='1.rar'      #Content-Type: application/octet-stream
55         file=os.path.join(filepath,filename)
56         return send_file(file)
57     
58     
59     if __name__ == '__main__':
60         #flak服務默認端口是5000,可以通過參數指定
61         # app.run()
62         app.run(host='192.168.16.14',port=8888,debug=True)

 

 

templates模板文件中的頁面index.html:

  

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>Title</title>
 6 </head>
 7 <body>
 8 <h1>登陸成功,歡迎來到index頁面</h1>
 9 <a href="">點擊查看數據信息</a>
10 </body>
11 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM