python request向服务端发送文件
本篇文章主要介绍1. 如何使用python request向服务端发送文件 2. 服务端如何接收文件 3. 服务端如何发送文件
- 如何使用python request向服务端发送文件
request.post可以发送file类型
def foo():
local_url = "http://127.0.0.1:5000/test_api"
file = {'video': open("/path/to/video.mp4", 'rb')}
res = requests.post(url=local_url,
files=file,
data={"filename": "video.mp4"},
timeout=100000)
- 服务端如何接收文件
服务端使用flask搭建,可以接受file类型
from flask import Flask, request
app = Flask(__name__)
@app.route("/test_api", methods=['POST'])
def entrypoint():
# create cache folder
save_folder = 'tmp'
if os.path.exists(save_folder):
shutil.rmtree(save_folder)
os.mkdir(save_folder)
# get video
video = request.files['video']
filename = request.form['filename']
# save video
video_load_path = os.path.join(save_folder, filename)
video.save(video_load_path)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
- 服务端发送文件
基于flask搭建的服务可以使用send_file() 返回文件
from flask import Flask, request
app = Flask(__name__)
@app.route("/test_api", methods=['POST'])
def entrypoint():
# create cache folder
save_folder = 'tmp'
if os.path.exists(save_folder):
shutil.rmtree(save_folder)
os.mkdir(save_folder)
# get video
video = request.files['video']
filename = request.form['filename']
# save video
video_load_path = os.path.join(save_folder, filename)
video.save(video_load_path)
# send file to client
return send_file(video_load_path, mimetype='video/mp4', as_attachment=True)
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)
客户端接收服务端的发送
def foo():
local_url = "http://127.0.0.1:5000/test_api"
file = {'video': open("/path/to/video.mp4", 'rb')}
res = requests.post(url=local_url,
files=file,
data={"filename": "video.mp4"},
timeout=100000)
with open("response.mp4", 'wb') as f:
f.write(res.content)
或者也可以把文件通过cdn发送到用于存储文件的地方,并将存储地址返回给用户,用户通过此地址访问文件
VIDEO_UPLOAD_URL = 'http://xxxxx/upload_video.php'
def upload_video(video_bytes):
files = {
'file': video_bytes
}
try:
resp = requests.post(VIDEO_UPLOAD_URL, files=files)
if resp.status_code == 200:
url = json.loads(resp.text)['url']
crc = binascii.crc32(video_bytes)
url = '{}?crc={}&type=5'.format(url, crc)
return url
else:
return None
except Exception as err:
logging.error('upload_video failed, error info {}'.format(err))
return None
from flask import Flask, request
app = Flask(__name__)
@app.route("/test_api", methods=['POST'])
def entrypoint():
# create cache folder
save_folder = 'tmp'
if os.path.exists(save_folder):
shutil.rmtree(save_folder)
os.mkdir(save_folder)
# get video
video = request.files['video']
filename = request.form['filename']
# save video
video_load_path = os.path.join(save_folder, filename)
video.save(video_load_path)
# upload video
video_url = upload_video(open(video_load_path, 'rb').read())
return jsonify({"status": "success", "url": video_url})
if __name__ == '__main__':
app.run(host="0.0.0.0", port=5000)