python类File()的实例源码

test_models.py 文件源码 项目:edx-enterprise 作者: edx 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_image_type(self, is_valid_image_extension, image_extension):
        """
        Test image type, currently .png is supported in configuration. see apps.py.
        """
        file_mock = mock.MagicMock(spec=File, name="FileMock")
        file_mock.name = "test1" + image_extension
        file_mock.size = 2 * 1024
        branding_configuration = EnterpriseCustomerBrandingConfiguration(
            enterprise_customer=factories.EnterpriseCustomerFactory(),
            logo=file_mock
        )

        if not is_valid_image_extension:
            with self.assertRaises(ValidationError):
                branding_configuration.full_clean()
        else:
            branding_configuration.full_clean()  # exception here will fail the test
utils.py 文件源码 项目:USTC-Software-2017 作者: igemsoftware2017 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def store_temp_file(fd):
    """
    Given a file-like object and dumps it to the temporary directory.

    Returns the temporary file object.
    """
    temp_file = tempfile.NamedTemporaryFile(
        encoding=getattr(fd, 'encoding', None))

    source = FileWrapper(fd)
    for chunk in source.chunks():
        temp_file.write(chunk)

    temp_file.seek(0)

    return temp_file
load_source_file.py 文件源码 项目:oim-cms 作者: parksandwildlife 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def handle(self, *args, **options):
        logger = logger_setup('mgmt_load_source_file')
        if (len(args) < 2):
            raise CommandError('See "./manage.py help load_source_file" for usage')

        if args[0] not in SourceFile.FILE_TYPES:
            raise CommandError('"{}" is not a valid file type. Options are: {}'.format(args[0], ', '.join(SourceFile.FILE_TYPES.keys())))

        file_type = SourceFile.FILE_TYPES[args[0]]

        files = args[1:]
        for f in files:
            if not os.path.isfile(f):
                raise CommandError('"{}" is not a file path, aborting'.format(f))

        for f in files:
            if os.path.getsize(f) > 0:
                source_file, created = SourceFile.objects.get_or_create(file_type=file_type, file_name=os.path.basename(f))
                if not created:
                    source_file.data.delete()
                source_file.data.save(os.path.basename(f), File(open(f, 'rb')), save=True)

                logger.info('SourceFile id {} ({}, {}) updated'.format(source_file.id, args[0], os.path.basename(f)))
            else:
                logger.info('SourceFile id {} IGNORED: File size zero'.format(os.path.basename(f)))
storage.py 文件源码 项目:CSCE482-WordcloudPlus 作者: ggaytan00 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content, name)

        name = self.get_available_name(name, max_length=max_length)
        return self._save(name, content)

    # These methods are part of the public API, with default implementations.
storage.py 文件源码 项目:tissuelab 作者: VirtualPlants 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def save(self, name, content):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content)

        name = self.get_available_name(name)
        name = self._save(name, content)

        # Store filenames with forward slashes, even on Windows
        return force_text(name.replace('\\', '/'))

    # These methods are part of the public API, with default implementations.
models.py 文件源码 项目:djangodm 作者: nescode 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def create_new_thumb(media_path, instance, owner_slug, max_length, max_width):
    filename = os.path.basename(media_path)
    thumb = Image.open(media_path)
    size = (max_length, max_width)
    thumb.thumbnail(size, Image.ANTIALIAS)

    temp_loc = "%s/%s/tmp" %(settings.MEDIA_ROOT, owner_slug)

    if not os.path.exists(temp_loc):
        os.makedirs(temp_loc)

    temp_file_path = os.path.join(temp_loc, filename)
    if os.path.exists(temp_file_path):
        temp_path = os.path.join(temp_loc, "%s" %(random.random()))
        os.makedirs(temp_path)
        temp_file_path = os.path.join(temp_path, filename)

    temp_image = open(temp_file_path, "w")
    thumb.save(temp_image)
    thumb_data = open(temp_file_path, "r")

    thumb_file = File(thumb_data)
    instance.media.save(filename, thumb_file)
    shutil.rmtree(temp_loc, ignore_errors=True)
    return True
components.py 文件源码 项目:nhsuk-content-store 作者: nhsuk 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def transform(self, data):
        path = self.find_biggest_image(data['props']['srcset'])
        name = os.path.basename(path)

        image = Image(
            caption=data['props'].get('caption', ''),
            title=data['props']['alt'] or self.page.title
        )

        # save temp file
        img_temp = NamedTemporaryFile()
        img_temp.write(self.get_image_data_from_file(path))
        img_temp.flush()

        # save file and image
        image.file.save(name, File(img_temp), save=True)
        image.save()

        return {
            'type': 'image',
            'value': image.id
        }
storage.py 文件源码 项目:producthunt 作者: davidgengler 项目源码 文件源码 阅读 39 收藏 0 点赞 0 评论 0
def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content, name)

        name = self.get_available_name(name, max_length=max_length)
        return self._save(name, content)

    # These methods are part of the public API, with default implementations.
storage.py 文件源码 项目:django-rtc 作者: scifiswapnil 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content, name)

        name = self.get_available_name(name, max_length=max_length)
        return self._save(name, content)

    # These methods are part of the public API, with default implementations.
proxy.py 文件源码 项目:django-hierarkey 作者: raphaelm 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def _serialize(self, value: Any) -> str:
        if isinstance(value, str):
            return value
        elif isinstance(value, int) or isinstance(value, float) \
                or isinstance(value, bool) or isinstance(value, decimal.Decimal):
            return str(value)
        elif isinstance(value, list) or isinstance(value, dict):
            return json.dumps(value)
        elif isinstance(value, datetime) or isinstance(value, date) or isinstance(value, time):
            return value.isoformat()
        elif isinstance(value, Model):
            return value.pk
        elif isinstance(value, File):
            return 'file://' + value.name
        else:
            for t in self._h.types:
                if isinstance(value, t.type):
                    return t.serialize(value)

        raise TypeError('Unable to serialize %s into a setting.' % str(type(value)))
test_form.py 文件源码 项目:django-hierarkey 作者: raphaelm 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def test_form_save_unchanged_file(organization):
    val = SimpleUploadedFile("sample_invalid_image.jpg", b"file_content", content_type="image/jpeg")
    form = SampleForm(obj=organization, attribute_name='settings', data={}, files={
        'test_file': val
    })
    assert form.is_valid()
    form.save()

    organization.settings.flush()
    oldname = organization.settings.get('test_file', as_type=File, binary_file=True).name

    form = SampleForm(obj=organization, attribute_name='settings', data={'unaffected': 'on'}, files={})
    assert form.is_valid()
    form.save()

    organization.settings.flush()
    assert organization.settings.get('test_file', as_type=File, binary_file=True).name == oldname
test_form.py 文件源码 项目:django-hierarkey 作者: raphaelm 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_form_delete_file(organization):
    val = SimpleUploadedFile("sample_invalid_image.jpg", b"file_content", content_type="image/jpeg")
    form = SampleForm(obj=organization, attribute_name='settings', data={}, files={
        'test_file': val
    })
    assert form.is_valid()
    form.save()

    organization.settings.flush()
    oldname = organization.settings.get('test_file', as_type=File, binary_file=True).name

    form = SampleForm(obj=organization, attribute_name='settings', data={
        'test_file-clear': 'on'
    })
    assert form.is_valid()
    form.save()

    organization.settings.flush()
    assert not organization.settings.test_file
    assert not os.path.exists(oldname)
storage.py 文件源码 项目:LatinSounds_AppEnviaMail 作者: G3ek-aR 项目源码 文件源码 阅读 13 收藏 0 点赞 0 评论 0
def save(self, name, content, max_length=None):
        """
        Saves new content to the file specified by name. The content should be
        a proper File object or any python file-like object, ready to be read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, 'chunks'):
            content = File(content, name)

        name = self.get_available_name(name, max_length=max_length)
        return self._save(name, content)

    # These methods are part of the public API, with default implementations.
test_downloads.py 文件源码 项目:balafon 作者: ljean 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_download_private_no_permission(self):

        #Create contact for the user
        profile = create_profile_contact(self.user)
        contact = profile.contact

        #Create category
        cat = ArticleCategory.objects.create(name="CAT")

        #create a public doc
        file_ = File(self._get_file())
        doc = mommy.make(Document, is_private=True, file=file_, category=cat)

        #check the url
        private_url = reverse('coop_cms_download_doc', args=[doc.id])
        self.assertEqual(doc.get_download_url(), private_url)

        #login and download
        response = self.client.get(doc.get_download_url(), follow=True)
        self.assertEqual(response.status_code, 200)
        #self.assertEquals(response['Content-Disposition'], "attachment; filename=unittest1.txt")
        self.assertEquals(response['Content-Type'], "text/plain")
test_downloads.py 文件源码 项目:balafon 作者: ljean 项目源码 文件源码 阅读 15 收藏 0 点赞 0 评论 0
def test_download_private_no_contact_defined(self):

        #Create category
        cat = ArticleCategory.objects.create(name="CAT")
        cat_perm = CategoryPermission.objects.create(category=cat)

        #create a public doc
        file_ = File(self._get_file())
        doc = mommy.make(Document, is_private=True, file=file_, category=cat)

        #check the url
        private_url = reverse('coop_cms_download_doc', args=[doc.id])
        self.assertEqual(doc.get_download_url(), private_url)

        #login and download
        response = self.client.get(doc.get_download_url())
        self.assertEqual(response.status_code, 403)
test_import_store.py 文件源码 项目:balafon 作者: ljean 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def test_import_error(self):
        """it should create items properly: default categorie"""
        data_file = File(self._get_file('import_store_fields_no_brand_and_ref_only_1.xls'))

        #by default fields are name,brand,reference,purchase_price,vat_rate
        store_import = mommy.make(
            models.StoreItemImport,
            data=data_file,
            fields='pre_tax_price,vat_rate'
        )

        store_import.import_data()

        self.assertNotEqual(store_import.import_error, '')
        self.assertEqual(store_import.is_successful, False)
        self.assertEqual(store_import.last_import_date.date(), date.today())

        self.assertEqual(models.StoreItem.objects.count(), 0)
setdefaultavatar.py 文件源码 项目:BackendAllStars 作者: belatrix 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def get_employee_list(self):
        default_image = File(open('sample_data/default_avatar.png', 'rb'))
        employees = get_list_or_404(Employee)

        for employee in employees:
            employee.avatar.save('default.png', default_image)
test_views.py 文件源码 项目:kuzgun.io 作者: yigitgenc 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_upload_endpoint_that_return_success(self):
        url = reverse('files:file-upload')
        filename = 'bahtiyar.jpg'

        client = APIClient()
        client.login(username='johndoe', password='johndoe')
        client.credentials(HTTP_CONTENT_DISPOSITION='attachment; filename={}'.format(filename))

        file = DjangoFile(open('/data/{}'.format(filename), 'rb'))

        response = client.post(url, {'name': filename, 'attachment': file})

        file.close()

        self.assertEqual(response.status_code, status.HTTP_201_CREATED)
ingest_tileset.py 文件源码 项目:higlass-server 作者: hms-dbmi 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def handle(self, *args, **options):
        filename = options['filename']
        datatype = options['datatype']
        filetype = options['filetype']
        coordSystem = options['coordSystem']
        coordSystem2 = options['coordSystem2']
        # coord = options['coord']
        uid = options.get('uid') or slugid.nice().decode('utf-8')
        name = options.get('name') or op.split(filename)[1]

        if options['no_upload']:
            if not op.isfile(op.join(settings.MEDIA_ROOT, filename)):
                raise CommandError('File does not exist under media root')
            django_file = filename
        else:
            django_file = File(open(filename, 'rb'))

            # remove the filepath of the filename
            django_file.name = op.split(django_file.name)[1]

        tm.Tileset.objects.create(
            datafile=django_file,
            filetype=filetype,
            datatype=datatype,
            coordSystem=coordSystem,
            coordSystem2=coordSystem2,
            owner=None,
            uuid=uid,
            name=name)
dump.py 文件源码 项目:ecs_sclm 作者: meaningful 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def create_filer_image(self, folder=None):
        file_obj = DjangoFile(open(self.filename, 'rb'), name=self.image_name)
        image = Image.objects.create(owner=self.superuser,
                                     original_filename=self.image_name,
                                     file=file_obj, folder=folder)
        return image


问题


面经


文章

微信
公众号

扫码关注公众号