Flask框架 之request对象
一、request对象属性
属性 | 说明 | 类型 |
---|---|---|
data | 记录请求的数据,并转换为字符串 | * |
form | 记录请求中的表单数据 | MultiDict |
args | 记录请求中的查询参数 | MultiDict |
cookies | 记录请求中的cookie信息 | Dict |
headers | 记录请求中的报文头 | EnvironHeaders |
method | 记录请求使用的HTTP方法 | GET/POST |
url | 记录请求的URL地址 | string |
files | 记录请求上传的文件 | * |
二、form、data、args使用
@app.route("/login", methods=["GET", "POST"]) def login(): print(request.data) # 获取表单提交的数据用request.form name = request.form.get("name") password = request.form.get("password") # 获取相同名称,返回列表 name_li = request.form.getlist("name") # 获取queryString数据用 city = request.args.get("city") # 判断请求类型 if request.method == "GET": pass elif request.method == "POST": pass # 获取json数据 j_name = request.json.get("name") return "name=%s, password=%s" % (name, password)
三、文件上传
前端代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>文件上传</title> <link rel="stylesheet" href="/static/layui/css/layui.css" media="all"> <style> .layui-upload { text-align: center; margin-top: 10%; } img { width: 200px; } </style> </head> <body> <div class="layui-upload"> <button type="button" class="layui-btn" id="test1">上传图片</button> <div class="layui-upload-list"> <img class="layui-upload-img" id="demo1"> <p id="demoText"></p> </div> </div> <script src="/static/layui/layui.js" charset="utf-8"></script> <script> layui.use('upload', function () { var $ = layui.jquery , upload = layui.upload; //普通图片上传 var uploadInst = upload.render({ elem: '#test1' , url: '/upload' , before: function (obj) { //预读本地文件示例,不支持ie8 obj.preview(function (index, file, result) { $('#demo1').attr('src', result); //图片链接(base64) }); } , done: function (res) { //如果上传失败 if (res.code > 0) { return layer.msg('上传失败'); } //上传成功 return layer.msg(res.msg); } , error: function () { //演示失败状态,并实现重传 var demoText = $('#demoText'); demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>'); demoText.find('.demo-reload').on('click', function () { uploadInst.upload(); }); } }); }); </script> </body> </html>
python脚本:
@app.route("/upload", methods=["POST", "GET"]) def upload(): if request.method == "GET": return render_template("upload.html") elif request.method == "POST": files = request.files if "file" not in files: return json.dumps({"code": 1, "msg": "上传失败"}) file = files.get("file") file.save("./static/upload/" + file.filename) return json.dumps({"code": 0, "msg": "上传成功"})
效果图如下: