将InMemory文件复制到远程服务器

时间:2017-12-12 08:09:41

标签: python django

有没有办法将request.FILES中的文件复制到Django中的100.100.1.100/home/dbadmin/EncFiles等远程位置?我咨询过thisthis个问题,但我不需要登录服务器来复制文件。

我的内存中有一个简单的文件,我需要发送到另一台服务器。我该怎么做?

2 个答案:

答案 0 :(得分:0)

评论似乎不能包含格式化代码,因此我必须使用答案回复:

def crop_avatar(file_path,size):

    avatar_format = get_image_format(os.path.splitext(file_path)[1])
    file_format = avatar_format.split('/')[1]
    avatar_filename = get_avatar_filename(file_path)

    image_file = default_storage.open(file_path)
    image = Image.open(image_file)
    if image.mode not in ('L', 'RGB'):
        image = image.convert('RGB')
    width,height = image.size

    crop_ratio = float(200)/(size[2]-size[0])
    ratio = float(480)/width * crop_ratio

    width  = int(width  * ratio)
    height = int(height * ratio)

    left = int(size[0] * crop_ratio)
    top =  int(size[1] * crop_ratio)

    crop_image = image.resize((width,height),Image.ANTIALIAS)


    crop_image = crop_image.crop((left,top,left+200,top+200))

    avatar_io = BytesIO()#this is for default_storage using.
    crop_image.save(avatar_io, format=file_format)

    avatar = InMemoryUploadedFile(
        avatar_io,
        None,
        avatar_filename,
        avatar_format,
        len(avatar_io.getvalue()),
        None)
    avatar.seek(0)
    saved_path =  default_storage.save(avatar_filename, avatar)
    image_file.close()
    default_storage.delete(file_path)


    return saved_path

答案 1 :(得分:0)

最终结果非常简单。我在两台具有相同凭据的计算机上创建了两个用户,为该用户授予了该文件夹的权限,并使用以下代码复制文件。哦,以及通过局域网连接的计算机。

serverPath = r"\\192.111.111.111/myFolder"

if os.path.exists(serverPath):
    for key in request.FILES:
        fileName = request.FILES[key].name
        d, filePath = tempfile.mkstemp(suffix=request.FILES[key].name, dir=serverPath)

        with open(filePath, 'wb') as outFile:
            shutil.copyfileobj(request.FILES[key], outFile)