python中将图片从客户端(client)推到(POST)到服务器端(server)的方法

从客户端推json到服务器端的工作可以用flask很容易做到,那么需要推送图片的话可以先将图片存到json中再进行操作。

服务器端

from flask import request, Flask
import json
import numpy as np
app = Flask(__name__) @app.route("/frame", methods=['POST'])
def get_frame():
res = request.json # 获取推过来的json,也可以用data然后转换成json
# res = json.loads(request.data)
frame = eval(res["image"].decode("base64")) # dtype为int32
frame = np.array(frame, dtype=np.uint8)
cv2.imshow("frame", frame)
cv2.waitkey(0) if __name__ == "__main__":
app.run("0.0.0.0", port=8081) #端口为8081

PS:关于request函数获取的内容可以具体参考这里

客户端

1. 将图片存入json

import cv2
import json img = cv2.imread("/your/image")
res = {"image": str(img.tolist()).encode('base64')} # img是ndarray,无法直接用base64编码,否则会报错

2. 推送json到服务器端

import requests

_ = requests.post("/your/server/url", json=res)    # 比如这里/http://192.168.1.112:8081/frame
# _ = requests.post("/your/server/url", data=json.dumps(res)) # 如果服务器端获取的方式为data

参考

  1. requests: http://docs.python-requests.org/en/master/user/quickstart/#more-complicated-post-requests
  2. flask request: http://flask.pocoo.org/docs/0.12/quickstart/#the-request-object
  3. https://*.com/questions/9746303/how-do-i-send-a-post-request-as-a-json
  4. https://*.com/questions/27837346/how-to-include-pictures-bytes-to-a-json-with-python-encoding-issue
  5. https://*.com/questions/20001229/how-to-get-posted-json-in-flask
  6. https://*.com/questions/10434599/how-to-get-data-received-in-flask-request
上一篇:MySQL测试工具之-tpcc


下一篇:看完99%的人都学会了!java兼职程序员招聘