flask返回数据的五种方式

 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数据类型
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)

 

猜你喜欢

转载自www.cnblogs.com/open-yang/p/11165554.html