# 1、发送
def image_to_base64(image_np):
image = cv2.imencode(".jpg", image_np)[1].tobytes()
base64_data = base64.b64encode(image)
base64_data = base64_data.decode()
return base64_data
#async异步同构,可以视为多开了一个线程
async def send(name, image):
#data字典中key叫字段,需要和后端确定要传输哪些数据和字段
#这里面图片被转为base64,图片的二进制数据形式传输
data = {
"userName": name,
"downWordImg": image_to_base64(image),
"downWordTime": time.strftime("%Y-%m-%d %H:%M:%S")
}
try:
#self.url为URL.txt中的url,这个接口路径和后端要就行
#如 http://192.168.3.39:8080/python/judge/test
#该url由ip,端口和路由指向组成
#这是一个post请求,会把data字典里的数据发给后端
response = requests.post(self.url, json=data).text
print(f"{time.strftime('%Y-%m-%d %H:%M:%S')}:\t{name}")
except Exception as e:
print('send fail with {}'.format(e))
return
# 2、接收
from wsgiref.simple_server import make_server
import json
#这个接口编写未使用任何框架,基于WSGI,用于获取后端请求的数据
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/html')])
#request_body里保存了所有请求字段,请求头、状态码、数据等
request_body = environ["wsgi.input"].read(int(environ.get("CONTENT_LENGTH", 0)))
request_body = json.loads(request_body)
# for key,value in enumerate(environ):
# print(key)
# print(value)
if 'data' not in request_body.keys():
return [b'<h1>Invalid data!</h1>']
else:
data = request_body['data']
body = json.dumps({'data': data})
print(body.encode("utf-8"))
return [body.encode("utf-8")]
def run():
http = make_server('0.0.0.0', 5000, application).serve_forever()
if __name__ == '__main__':
run()