Flask Web框架的安装和启动
安装: pip install Flask - 1.1.2
应用Flask
# 三行启动flask 提供服务
from flask import Flask
app = Flask(__name__)
app.run()
# 六行启动 实现"HelloWorld"
from flask import Flask # 导入Flask类,创建Flask应用对象
app = Flask(__name__) # app = application
@app.route("/index") # 为 Flask应用对象增加路由
def index(): # 与路由绑定的视图函数 视图函数名尽可能保持唯一
return "HelloWorld" # 相当于Django中的HttpResponse
if __name__ == '__main__': # 当前文件处于脚本状态下运行如下代码
app.run() # 启动 Flask应用
Flask 中的 Response(对比Django)
Django Flask
HttpResponse("HelloWorld") "HelloWorld"
render(html文件) render_template(html文件)
redirect("/home") redirect("/home")
- 除了上述三个外, Flask还有两个特殊返回值 !
send_file("文件路径") 返回文件
# 打开并返回文件内容 自动识别文件类型
# 在ResponseHeaders中加入Content-Type:文件类型 -- 可以被客户端识别的文件类型
# 若有不能识别的文件类型 -- 下载处理
jsonify("字符串或数据类型") 返回JSON字符串
# Content-Type:application/json == 标准格式
# 1.打包JSON序列化JSON字符串
# 2.编写 ResponseHeaders 加入 Content-Type:application/json
Flask 中的 Request
- methods=['POST','GET'] 在添加路由的装饰器中允许请求方式
- from flask import request
request.form #获取FormData数据
request.methods #获取请求方式
request.args #获取URL中的数据
request.files #获取请求体中的文件数据 FileStorage对象
#保存文件的操作
my_file = request.files.get("my_file")
new_file = os.path.join("img",my_file.filename)
my_file.save(new_file)
request.headers #获取请求头中的数据
request.cookies #获取cookie对象
request.path,request.host,request.host_url这几个用一个例子一起记
#通过发送 GET 到 http://127.0.0.1:5000/test/a?x=1
request.path: /test/a
request.host: 127.0.0.1:5000
request.host_url: http://127.0.0.1:5000/
request.full_path: /test/a?x=1
request.json #请求头中的Content_Type:application/json 字典
request.data #请求体的原始信息,Content_Type中没有Form或application/json的时候存一份
Flask 中的 Session
- from flask import session
- 使用session的前提 : 在app中加入secret_key
Session 服务器端的键值对
Cookie 客户端的键值对
交由客户端保管机制:
1.开启session
2.session序列化字符串
3.通过secret_key加密
4.通过cookie返回客户端
接收session:
1.通过cookie获取session
2.通过secret_key解密
3.反序列化字典
4.session