当前位置: 首页>>代码示例>>Python>>正文


Python TemporaryUploadedFile.close方法代码示例

本文整理汇总了Python中django.core.files.uploadedfile.TemporaryUploadedFile.close方法的典型用法代码示例。如果您正苦于以下问题:Python TemporaryUploadedFile.close方法的具体用法?Python TemporaryUploadedFile.close怎么用?Python TemporaryUploadedFile.close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.files.uploadedfile.TemporaryUploadedFile的用法示例。


在下文中一共展示了TemporaryUploadedFile.close方法的4个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: FileWriteTest

# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import close [as 别名]
class FileWriteTest(TestCase):

    def setUp(self):
        self.text = "Spam Spam Spam Spam.\n"
        self.digest = hashlib.sha1(self.text).hexdigest()
        self.tempfile = TemporaryUploadedFile('spam4.txt', 'text/plain',
                                              len(self.text), 'utf-8')
        self.tempfile.file.write(self.text)
        self.tempfile.file.seek(0)

    def test(self):
        new_upload = Upload(file=self.tempfile)
        new_upload.save()

        # Upload has been saved to the database.
        self.assert_(new_upload.pk)

        # Upload contains correct content.
        self.assertEqual(new_upload.file.read(), self.text)

        # Filename is the hash of the file contents.
        self.assert_(new_upload.file.name.startswith(self.digest))

    def tearDown(self):
        self.tempfile.close()  # Also deletes the temp file.

        # Remove the upload in `MEDIA_ROOT`.
        directory = os.path.join(settings.MEDIA_ROOT, '24')
        if os.path.exists(directory):
            shutil.rmtree(directory)
开发者ID:Mondego,项目名称:pyreco,代码行数:32,代码来源:allPythonContent.py

示例2: create_photo_versions

# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import close [as 别名]
def create_photo_versions(sender, instance, **kwargs):
    """Create `PhotoVersion`` objects for the photo object defined by `instance`.

    A version is created for a bounding box defined by each PhotoSize instance.

    """    
    from photo.models import Photo, PhotoSize, PhotoVersion
    photo = instance
    ext = '.jpg'
    t = None
    try:
        pth = photo.image.path
    except NotImplementedError:
        from django.core.files.temp import NamedTemporaryFile
        t = NamedTemporaryFile(suffix=ext)
        ix = photo.image
        if ix.closed:
            # Reload from DB
            photo = Photo.objects.get(pk=photo.pk)
            ix = photo.image
        for d in ix.chunks(4000000):
            t.write(d)
        t.flush()
        t.seek(0)
        pth = t
    for size in PhotoSize.objects.all():
        # Create a suitable filename.
        filename = '%s-%s-%s%s' % (photo.pk, uuid4().hex[::7], slugify(size.name)[:10], ext)
        ctype = guess_type(filename)[0]
        temp_file = TemporaryUploadedFile(name=filename, content_type=ctype, size=0, charset=None)
        if t:
            t.seek(0)
        try:
            version = PhotoVersion.objects.get(photo=photo, size=size)
            remove_model_image(version, 'image')
            version.image = None
        except PhotoVersion.DoesNotExist:
            version = PhotoVersion(photo=photo, size=size)
        if size.do_crop:
            resize_to, crop_box, input_image = get_perfect_fit_resize_crop(size.bounding_box, (photo.width, photo.height))
        else:
            resize_to = size.bounding_box
            crop_box = None
        # Resize to a temporary location.
        resize(pth, resize_to, out_file_path=temp_file, crop=crop_box)
        # Save resized copy to `version` instance.
        temp_file.seek(0) # Prepare file for a re-read.
        version.image.save(name=filename, content=temp_file, save=True)
        temp_file.close()
    if t:
        t.close()
开发者ID:kabirh,项目名称:riotvine,代码行数:53,代码来源:utils.py

示例3: create_customer_image

# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import close [as 别名]
    def create_customer_image(self, fp, anfexi):
        self.customer_image = self.create()
        # Process image (if the uploaded file has an image format)
        try:
            image = Image.open(fp)
        except IOError:
            # An IOError here means the file is not a recognized image format
            generic_file = TemporaryUploadedFile()
            extension = self._get_extension(fp)
            # Store the file as is and don't create a thumbnail
            self.customer_image.document.save(
                '{}-full.{}'.format(
                    anfexi, extension
                ),
                ImageFile(generic_file)
            )
            generic_file.close()
            return self.customer_image

        # Otherwise process images normally
        thumbnail, resize = self._process_image(image)
        # Write images on S3
        thumbnail_file = self._make_temp_file(thumbnail.getvalue())
        image_file = self._make_temp_file(resize.getvalue())
        self.customer_image.thumbnail.save(
            '{}-thumbnail.png'.format(anfexi),
            ImageFile(thumbnail_file), save=False
        )
        thumbnail_file.close()
        self.customer_image.document.save(
            '{}-full.png'.format(anfexi),
            ImageFile(image_file), save=False
        )
        self.customer_image.save()
        image_file.close()
        return self.customer_image
开发者ID:nessvm,项目名称:image-resizing-microservice,代码行数:38,代码来源:managers.py

示例4: UploadProgressCachedHandler

# 需要导入模块: from django.core.files.uploadedfile import TemporaryUploadedFile [as 别名]
# 或者: from django.core.files.uploadedfile.TemporaryUploadedFile import close [as 别名]
class UploadProgressCachedHandler(FileUploadHandler):
    """
    Tracks progress for file uploads.
    The http post request must contain a header or query parameter,
    'X-Progress-ID', which should contain a unique string to identify
    the upload to be tracked.

    Copied from:
    http://djangosnippets.org/snippets/678/

    See views.py for upload_progress function...
    """

    def __init__(self, request=None):
        super(UploadProgressCachedHandler, self).__init__(request)
        self.progress_id = None
        self.cache_key = None

    def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
        """
        """
        self.content_length = content_length
        if 'X-Progress-ID' in self.request.GET:
            self.progress_id = self.request.GET['X-Progress-ID']
        elif 'X-Progress-ID' in self.request.META:
            self.progress_id = self.request.META['X-Progress-ID']
        if self.progress_id:
            self.cache_key = "%s_%s" % (
                self.request.META['REMOTE_ADDR'],
                self.progress_id
            )
            cache.set(self.cache_key, {
                'length': self.content_length,
                'uploaded': 0
            })

    def new_file(self, field_name, file_name, content_type, content_length, charset=None):
        """
        """
        self.field_name = field_name
        self.file_name = file_name
        self.content_type = content_type
        self.content_length = content_length
        self.charset = charset

        self.file = TemporaryUploadedFile(
            self.file_name,
            self.content_type,
            0,
            self.charset
        )

    def receive_data_chunk(self, raw_data, start):
        """
        """
        if self.cache_key:
            data = cache.get(self.cache_key)
            data['uploaded'] += self.chunk_size
            cache.set(self.cache_key, data)
            self.file.write(raw_data)
        return raw_data

    def file_complete(self, file_size):
        """
        """
        self.file.seek(0)
        self.file.size = file_size
        self.file.close()
        return self.file

    def upload_complete(self):
        """
        """
        if self.cache_key:
            cache.delete(self.cache_key)
开发者ID:orzubalsky,项目名称:invisible,代码行数:77,代码来源:handlers.py


注:本文中的django.core.files.uploadedfile.TemporaryUploadedFile.close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。