python 用于处理通过 http 上传文件的脚本 post

python script to handle uploaded file via http post

我正在开发一个 Django 项目,我尝试通过 http post 请求上传文件。

我的上传脚本是:

url=r'http://MYSITEURL:8000/upload'
files={'file':open('1.png','rb')}
r=requests.post(url,files=files)

我的接收方在我的 django 站点中,在 views.py:

def upload_image(request):
from py_utils import open_py_shell;open_py_shell.open_py_shell()

当我执行 request.FILES 时,我可以看到所有 post 详细信息, 我想知道的是如何在收到 post 请求后将其保存在服务器端

您在 request.FILES 中拥有的是 InMemoryUploadedFile。你只需要将它保存在文件系统中的某个地方。

这是取自 Django docs:

的示例方法
def handle_uploaded_file(f):
    with open('some/file/name.txt', 'wb+') as destination:
        for chunk in f.chunks():
            destination.write(chunk)

我认为你可以很好地使用模型。这将是 Django 的正确方法。这是一个例子,models.py file:

from django.db import models
from django.conf import settings

import os
import hashlib


def instanced_file(instance, filename):
    splitted_name = filename.split('.')
    extension = splitted_name[-1]
    return os.path.join('files', hashlib.md5(str(instance.id).encode('UTF-8')).hexdigest() + '.' + extension)

class File(models.Model):
    name = models.FileField('File', upload_to = instanced_file)

    def get_file_url(self):
        return '%s%s' % (settings.MEDIA_URL, self.name)

    def __str__(self):
        return self.name

    def __unicode__(self):
        return self.name

创建模型后创建表单并继续。