[web] Serialize in JSON a base64 encoded data (xxx is not JSON serializable)

在使用json向web api上传文件(比如图片文件或者音频文件)的时候,json里是不能放bytes类型数据的,否则报错

xxx is not JSON serializable

那怎么传数据呢?

解决方法:先把文件读取成bytes,然后进行字符串化,这样就可以dump了。(注意此时server端接收到这些数据后,要反向转换为bytes才行)

客户端:

import requests
import time
import base64
import threading
import json


def main():
    benchmark(1)
    time.sleep(10)

    benchmark(2)
    time.sleep(10)

    benchmark(10)

end_point = 'http://219.223.174.254:8080/THU/VC_api/' # THU/VC_api
# 读取音频文件得到字节流
audio_64_string = base64.b64encode(open("C:/Users/LT/Desktop/source.wav","rb").read())
# 将字节流转换为utf-8编码的字符串,才能被json dump
input_data = {"data":audio_64_string.decode('utf-8'),"service":"VC"}
headers = {'User-Agent' : 'Mozilla/5.0 (Linux; Android 4.2.1; en-us; Nexus 4 Build/JOP40D) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.166 Mobile Safari/535.19'}
error_result = []
correct_result = []
def target():
    try:
        result = requests.post(end_point, json=input_data,headers=headers)
        ResponseTime = float(result.elapsed.seconds) # 获取响应时间,单位s
        if result.status_code != 200:
            error_result.append("0")
        else:
            correct_result.append(ResponseTime)
    except Exception as e:
        print(e)

def benchmark(batch_size):
    threads =[]
    error_result.clear()
    correct_result.clear()

    beg = time.time()
    try:
        for i in range(batch_size):
            thd = threading.Thread(target=target)
            threads.append(thd)

        last_j = None
        for j in threads:
            # j.setDaemon(True) # https://www.cnblogs.com/alan-babyblog/p/5325071.html
            j.start()
            last_j =j
        last_j.join()
    except Exception as e:
        print(e)
    end = time.time()

    print('concurrent processing: ',batch_size)
    print('failed request:', len(error_result))
    print('correct_result_time: ' ,correct_result)
    print('avg_response time: ' ,float(sum(correct_result)) / float(len(correct_result)))
    print('total time: ',(end-beg),' s')
    print('seconds  per completed request: ', (end-beg)*1./batch_size*1.,' s/request')
    print('吞吐率 requests  per second: ', batch_size * 1. / (end - beg) * 1. , ' request/s')


if __name__=='__main__':
    main()

服务端:

# body为json格式
received_json_data = json.loads(request.body.decode('utf-8'))
# 此时data还是utf-8编码的字符串
data = received_json_data["data"]
# 先将字符串转化为bytes然后进行base64编码
plain_data = b64decode(bytes(data,encoding='utf8'))

参考:

https://stackoverflow.com/questions/37225035/serialize-in-json-a-base64-encoded-data

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值