当前位置:   article > 正文

Flask 结合 axios 使用 / GET PSOT / 文件上传 / 转 base64_flask axios params

flask axios params

axios 默认的 Content-Type 请求头是:Content-Type: application/json

例如 post 请求中 axios 默认提交的 data 就是 json 数据

这里需要注意的是,jQuery 的默认 Content-Type 请求头是:Content-Type: application/x-www-form-urlencoded

如果项目是从 jQuery 转到 axios 上,需要在 axios 上做 Content-Type 的处理

axios.post({
    headers: {'Content-Type': 'application/x-www-form-urlencoded'}
})
    .then(function (response) {
        console.log(response);
    })
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

get 请求

axios 的 get 请求:

axios({
    method:'get',
    url:'tpls/',
    params: {
        ID: 12345
    }
})
    .then(function (response) {
        console.log(error);
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10

axsio 的别名写法:

axios.get('/tpls?ID=12345')
    .then(function (response) {
        // handle success
        console.log(response);
    })
    .catch(function (error) {
        // handle error
        console.log(error);
    })
    .then(function () {
        // always executed
    });
  
// or
  
axios.get('/tpls', {
    params: {
    ID: 12345
    }
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    })
    .then(function () {
        // always executed
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

如果请求的是图片流,如下:

axios({
    method:'get',
    url:'tpls/img',
    responseType:'stream'
})
    .then(function (response) {
        response.data.pipe(fs.createWriteStream('detail.jpg'))
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8

Flask 的 get 请求处理

1. 可以获取到单个的值

request.args.get('key')
  • 1

2. 可以获取get请求的所有参数返回值是ImmutableMultiDict类型

requestValues = request.args
  • 1

3. 将获得的参数转换为字典

requestValues.to_dict()
  • 1

json 的 post 请求

axios 进行 post 请求:

axios({
    method: 'post',
    url: 'tpls/submit',
    data: {
        name: 'alma',
        edu: {shcool: 'MIT', age: '20'}
    }
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

axios 别名的写法:

axios.post('tpls/submit', {
        name: 'alma',
        edu: {shcool: 'MIT', age: '20'}
    })
  • 1
  • 2
  • 3
  • 4

不做 response 的处理也是可以的

flask 这边这样接受请求,以及 return 一个 response:

@app.route('tpls/submit', methods=['POST'])
def submit():
    anchor = request.json
    print(anchor.get('name'))
    return 'response'
  • 1
  • 2
  • 3
  • 4
  • 5

也就是说,flask 拿到的 json 数据直接变成了 dict 类型,可以和方便的使用

Flask 几种获取 json data 的方式

Ajax 请求不来源于 form 提交,flask 的 request.form 是拿不到数据的,只能通过以下几种方式拿到数据:

1. 获取未经处理过的原始数据而不管内容类型,如果数据格式是json的,则取得的是json字符串,排序和请求参数一致

request.get_data()
  • 1

以 get_data() 拿到的数据,将会变成 bytes 对象,如:

b'{'name': 'alma'}'
  • 1

此时需引入 json 模块,再次重新将其以 json 形式转为 dict(如果 data 是 json):

json.loads(request.get_data())
  • 1

2. 将请求参数做了处理,得到的是字典格式的,因此排序会打乱依据字典排序规则

request.get_json()
  • 1

3. 可以获取未经处理过的原始数据,如果数据格式是json的,则取得的是json字符串,排序和请求参数一致

request.data
  • 1

4. 将请求参数做了处理,得到的是字典格式的,因此排序会打乱依据字典排序规则

request.json
  • 1

这几种方式就好得多,拿过来就是 dict,直接用

文件上传的 post 请求

html 创建 input file, 比如:

<input name="file" type="file" accept="image/png,image/gif,image/jpeg" id="imgFile"/>
  • 1

封装一个 FormDate 对象,然后请求头使用Content-Type: 'multipart/form-data’:

let file = e.target.files[0];
let param = new FormData();
param.append('pic_file', file, file.name);

axios({
    method: 'post',
    url: 'tpls/submit',
    headers: {'Content-Type': 'multipart/form-data'},
    data: param
})
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16

axios 别名的写法:

let file = e.target.files[0];
let param = new FormData();
param.append('pic_file', file, file.name);
let config = {
    headers: {'Content-Type': 'multipart/form-data'}
};

axios.post('tpls/submit', param, config)
    .then(function (response) {
        console.log(response);
    })
    .catch(function (error) {
        console.log(error);
    });
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14

Flask 获取 file 的方式

1. 获取 files 对象

@app.route('tpls/submit', methods=['POST'])
def submit():
    anchor = request.files
    print(request.files)
    return 'response'
  • 1
  • 2
  • 3
  • 4
  • 5

2. 获取 files 对象的 FileStorage 对象

anchor = request.files['pic_file']
  • 1

3. FileStorage 的属性,FileStorage对象由 werkzeug.datastructures 模块创建,可参考该模块下的 FileStorage 类来操作:

def __init__(
    self,
    stream=None,
    filename=None,
    name=None,
    content_type=None,
    content_length=None,
    headers=None,
)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

4. FileStorage 的 save() 方法,可以直接将 FileStorage 存储下来

basedir = os.path.abspath(os.path.dirname(__file__))
path = basedir+"/static/photo/"
file_path = path+img.filename
...
anchor = request.files['pic_file’]
anchor.save(file_path)
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6

5. FileStorage 是字节流容器,可以进行读取,这一点在 werkzeug.datastructures 模块中也有说明:

FileStorage.read()
# or
FileStorage.stream.read()
  • 1
  • 2
  • 3

比如可以读出字节流来转成 base64

@app.route('tpls/submit', methods=['POST'])
def submit():
    anchor = request.files['pic_file']
    base64_data = base64.b64encode(anchor.read())
    s = base64_data.decode()
    print('data:image/jpeg;base64,%s' % s)
    return 'response'
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

其他参考

https://www.cnblogs.com/wupeiqi/articles/7552008.html 请求和响应部分

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/凡人多烦事01/article/detail/66555
推荐阅读
相关标签
  

闽ICP备14008679号