flask接口图片及参数的发送及接收

该博客介绍了如何使用Python的Flask框架编写后台接口,以接收前端通过POST请求发送的图片和参数。两种接收方式分别是:1) 图片放在files中,参数放在form中;2) 图片和参数一起通过data传递,图片需base64编码。前端发送请求时,可以将图片转换为base64编码并附带参数一起发送。
摘要由CSDN通过智能技术生成

python可用来写后台程序,一般用flask写后台服务器的接口,当前端通过web页面发送图片及参数时,后台服务器接口会收到图片及参数;图片及参数不能直接以原来的形式在网络中传输,需要进行转换成二进制字符串的形式传输。下面介绍两种发送和对应接收的方式:

1、首先写上后台服务器接口,用于接收解码前端传过来的图片及参数,解码后的图片可以直接处理或保存。

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/09/02 19:08
# @Author  : lishanlu
# @File    : receve_samples.py
# @Software: PyCharm
# @Discription: 接收图片和参数的不同方式

from __future__ import absolute_import, print_function, division
from flask import Flask,request
import cv2
import json
import numpy as np
import base64

app = Flask(__name__)


@app.route("/recv_files", methods=['POST'])
def recv_files():
    data = request.form
    print("===== data:",data)
    f_obj = request.files.get('file', None)
    if f_obj is None:
        return json.dumps({'status': 1, 'msg': 'No image was received.', 'result': []})
    content = f_obj.read()
    nparr = np.fromstring(content, np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    cv2.imwrite('recv_files.jpg',img_np)
    print("======== img shape:",img_np.shape)
    return "ok"


@app.route("/recv_json", methods=['POST'])
def recv_json():
    data = request.data
    data = json.loads(data)
    name = data.get('name', 'no_recv')
    age = data.get('age', 'no_recv')
    print("======= recv args: ", name, str(age))
    image_string = data['img']
    img_data = base64.b64decode(image_string)
    nparr = np.fromstring(img_data, np.uint8)
    img_np = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    cv2.imwrite('recv_json.jpg', img_np)
    print("======== img shape:", img_np.shape)
    return "ok"


if __name__ == "__main__":
    app.run(host='0.0.0.0', port=3200)

服务通过3200端口监听前端传过来的请求,程序定义了两种接收方式,一种是把图片放在files中,参数放在form中;另一种是把图片和参数一起通过data传过来,但图片需要经过base64编码才能传,这边接收端也需要解码,才能用。

2、前端发送请求的方式:

#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/09/02 19:06
# @Author  : lishanlu
# @File    : post_request_samples.py
# @Software: PyCharm
# @Discription: 上传图片及参数的不同方式

from __future__ import absolute_import, print_function, division
import requests
import cv2
import base64


def img2b64(img):
    retval, buffer = cv2.imencode('.bmp', img)
    # buffer = img.tostring()
    pic_str = base64.b64encode(buffer)
    pic_str = pic_str.decode()
    return pic_str


def img2b64_f(path):
    fs = open(path,'rb')
    buffer = fs.read()
    fs.close()
    pic_str = base64.b64encode(buffer)
    pic_str = pic_str.decode()
    return pic_str


def post_files():
    files = {'file':open('./images/01.jpg','rb')}
    data = {'name':'xyz','age':33}
    r = requests.post('http://localhost:3200/recv_files', data=data, files=files)
    print('========== res:', r.text)


def post_json():
    path = './images/01.jpg'
    img = cv2.imread(path)
    pic_str = img2b64(img)
    data = {'img': pic_str, 'name': 'xyz', 'age':33}
    r = requests.post('http://localhost:3200/recv_json', json=data)
    print('+++++++++ res:', r.text)


if __name__ == '__main__':
    #post_files()
    post_json()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值