项目背景
由于需要将算法处理过的视频放进存储服务器上,所以涉及到了跨服务器上传视频、图片等
代码实现
@api_view(['POST'])
def upload(request):
#定义一个固定的返回值
response = {'state': 1, 'des': 'normal'}
# 获取参数
if request.method == 'POST':
obj = request.FILES.get('obj')
des = request.POST.get("des", '')
number = request.POST.get("number", '')
person = request.POST.get("person", '')
time = request.POST.get("time", '')
# 将文件存入本地
f = open(obj.name, 'wb')
for line in obj.chunks():
f.write(line)
f.close()
# 获取文件名以及后缀
obj_split = obj.name.split(".")
# if obj_split[-1] in ["jpg","png","jpeg"]:
# if obj_split[-1] in ["mp4","avi","mkv"]:
# 从数据库获取存储服务器ip、port、username、password、path等信息
node_query = NodeManagement.objects.filter(node_type="risk").values()
host = node_query[0]["ip"]
port = int(node_query[0]["port"])
username = node_query[0]["username"]
password = node_query[0]["password"]
target_path = node_query[0]["relative_path"]
transport = paramiko.Transport(host, port)
# 本地文件路径
local_file = obj.name
random_str = ''.join(random.sample(string.ascii_letters + string.digits, 32))
# 上传服务器文件路径
print(obj_split[-1])
if obj_split[-1] in ["jpg","png","webp"]:
# f = open(obj.name, 'rb')
# files = {"files": f}
# dev_risk_image(files)
# f.close()
target_file = target_path + random_str +'.'+ obj_split[-1]
if obj_split[-1] in ["mp4","avi","mkv"]:
target_file = target_path + random_str +'.'+ obj_split[-1]
# 建立连接
transport.connect(username=username, password=password)
sftp = paramiko.SFTPClient.from_transport(transport)
# 上传文件
sftp.put(local_file, target_file)
os.remove(obj.name)
# 关闭连接
transport.close()
Risk.objects.create(time=datetime.strptime(time, '%Y-%m-%d %H:%M:%S'), path=host + target_file,
des=des, person=person, number=number)
return HttpResponse("success")
标签:node,obj,target,python,request,split,query,服务器,上传
From: https://www.cnblogs.com/beijie/p/17366710.html