python类SimpleUploadedFile()的实例源码

models.py 文件源码 项目:django-droidstore 作者: mathuin 项目源码 文件源码 阅读 16 收藏 0 点赞 0 评论 0
def save(self, *args, **kwargs):
        with ZipFile(self.apkfile, 'r') as myzip:
            am = myzip.read('AndroidManifest.xml')
            ap = axmlprinter.AXMLPrinter(am)
            ax = minidom.parseString(ap.getBuff())
            manifest = ax.getElementsByTagName('manifest')[0]
            for (name, value) in list(manifest.attributes.items()):
                if name == 'android:versionName':
                    self.version = value
                elif name == 'package':
                    self.package = value
            # http://stackoverflow.com/questions/7894897/django-saving-an-image-manually-to-an-imagefield-field
            qrimage = qrcode.make('market://search?q=pname:%s' % self.package)
            temp_handle = StringIO()
            qrimage.save(temp_handle, 'png')
            temp_handle.seek(0)
            suf = SimpleUploadedFile('suf', temp_handle.read(), content_type='image/png')
            # pylint: disable-msg=E1101 
            self.qrcodefile.save('save', suf, save=False)
            # pylint: enable-msg=E1101
        super(Product, self).save(*args, **kwargs)
test_models.py 文件源码 项目:samireland.com 作者: samirelanduk 项目源码 文件源码 阅读 20 收藏 0 点赞 0 评论 0
def test_can_delete_images(self):
        media_file = SimpleUploadedFile("test.png", b"\x00\x01\x02\x03")
        image = MediaFile(mediatitle="test", mediafile=media_file)
        image.save()
        self.assertEqual(MediaFile.objects.all().count(), 1)
        self.assertIn(
         datetime.now().strftime("%Y%m%d%H%M%S") + ".png",
         os.listdir(MEDIA_ROOT)
        )

        image.delete()
        self.assertEqual(MediaFile.objects.all().count(), 0)
        time.sleep(1)
        self.assertNotIn(
         datetime.now().strftime("%Y%m%d%H%M%S") + ".png",
         os.listdir(MEDIA_ROOT)
        )
test_admin_views.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def test_add(self):
        video_file = create_test_video_file()
        title = "Test Video"
        response = self.post({
            'title': title,
            'file': SimpleUploadedFile('small.mp4', video_file.read(), "video/mp4"),
        })

        # Should redirect back to index
        self.assertRedirects(response, reverse('wagtailvideos:index'))

        # Check that the video was created
        videos = Video.objects.filter(title=title)
        self.assertEqual(videos.count(), 1)

        # Test that extra fields were populated from post_save signal
        video = videos.first()
        self.assertTrue(video.thumbnail)
        self.assertTrue(video.duration)
        self.assertTrue(video.file_size)

        # Test that it was placed in the root collection
        root_collection = Collection.get_first_root_node()
        self.assertEqual(video.collection, root_collection)
test_admin_views.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_add_no_ffmpeg(self, ffmpeg_installed):
        ffmpeg_installed.return_value = False

        video_file = create_test_video_file()
        title = 'no_ffmpeg'

        response = self.post({
            'title': title,
            'file': SimpleUploadedFile('small.mp4', video_file.read(), "video/mp4"),
        })

        # Should redirect back to index
        self.assertRedirects(response, reverse('wagtailvideos:index'))

        # Check video exists but has no thumb or duration
        videos = Video.objects.filter(title=title)
        self.assertEqual(videos.count(), 1)
        video = videos.first()

        self.assertFalse(video.thumbnail)
        self.assertFalse(video.duration)
test_admin_views.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def test_add_too_large_file(self):
        video_file = create_test_video_file()

        response = self.post({
            'title': "Test video",
            'file': SimpleUploadedFile('small.mp4', video_file.read(), "video/mp4"),
        })

        # Shouldn't redirect anywhere
        self.assertEqual(response.status_code, 200)
        self.assertTemplateUsed(response, 'wagtailvideos/videos/add.html')

        # The form should have an error
        self.assertFormError(
            response, 'form', 'file',
            "This file is too big ({file_size}). Maximum filesize {max_file_size}.".format(
                file_size=filesizeformat(video_file.size),
                max_file_size=filesizeformat(1),
            )
        )
test_admin_views.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_add_with_collections(self):
        root_collection = Collection.get_first_root_node()
        evil_plans_collection = root_collection.add_child(name="Evil plans")

        response = self.post({
            'title': "Test video",
            'file': SimpleUploadedFile('small.mp4', create_test_video_file().read(), "video/mp4"),
            'collection': evil_plans_collection.id,
        })

        # Should redirect back to index
        self.assertRedirects(response, reverse('wagtailvideos:index'))

        # Check that the video was created
        videos = Video.objects.filter(title="Test video")
        self.assertEqual(videos.count(), 1)

        # Test that it was placed in the Evil Plans collection
        video = videos.first()
        self.assertEqual(video.collection, evil_plans_collection)
test_admin_views.py 文件源码 项目:wagtailvideos 作者: takeflight 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def test_add_post_badfile(self):
        """
        This tests that the add view checks for a file when a user POSTs to it
        """
        response = self.client.post(reverse('wagtailvideos:add_multiple'), {
            'files[]': SimpleUploadedFile('small.mp4', b"This is not an video!"),
        }, HTTP_X_REQUESTED_WITH='XMLHttpRequest')

        # Check response
        self.assertEqual(response.status_code, 200)
        self.assertEqual(response['Content-Type'], 'application/json')

        # Check JSON
        response_json = json.loads(response.content.decode())
        self.assertNotIn('video_id', response_json)
        self.assertNotIn('form', response_json)
        self.assertIn('success', response_json)
        self.assertIn('error_message', response_json)
        self.assertFalse(response_json['success'])
        self.assertIn("Not a valid video.", response_json['error_message'])
forms.py 文件源码 项目:pretix-passbook 作者: pretix 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def clean(self, value, *args, **kwargs):
        value = super().clean(value, *args, **kwargs)
        if isinstance(value, UploadedFile):
            try:
                from PIL import Image
            except ImportError:
                return value

            value.open('rb')
            value.seek(0)
            try:
                with Image.open(value) as im, tempfile.NamedTemporaryFile('rb', suffix='.png') as tmpfile:
                    im.save(tmpfile.name)
                    tmpfile.seek(0)
                    return SimpleUploadedFile('picture.png', tmpfile.read(), 'image png')
            except IOError:
                logger.exception('Could not convert image to PNG.')
                raise ValidationError(
                    _('The file you uploaded could not be converted to PNG format.')
                )

        return value
forms.py 文件源码 项目:pretix-espass 作者: esPass 项目源码 文件源码 阅读 18 收藏 0 点赞 0 评论 0
def clean(self, value, *args, **kwargs):
        value = super().clean(value, *args, **kwargs)
        if isinstance(value, UploadedFile):
            try:
                from PIL import Image
            except ImportError:
                return value

            value.open('rb')
            value.seek(0)
            try:
                with Image.open(value) as im, tempfile.NamedTemporaryFile('rb', suffix='.png') as tmpfile:
                    im.save(tmpfile.name)
                    tmpfile.seek(0)
                    return SimpleUploadedFile('picture.png', tmpfile.read(), 'image png')
            except IOError:
                logger.exception('Could not convert image to PNG.')
                raise ValidationError(
                    _('The file you uploaded could not be converted to PNG format.')
                )

        return value
tests.py 文件源码 项目:DjangoBlog 作者: liangliangyy 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_image(self):
        import requests
        rsp = requests.get('https://ss2.baidu.com/6ONYsjip0QIZ8tyhnq/it/u=2909203028,3998034658&fm=96')
        imagepath = os.path.join(settings.BASE_DIR, 'django.jpg')
        with open(imagepath, 'wb') as file:
            file.write(rsp.content)
        with open(imagepath, 'rb') as file:
            imgfile = SimpleUploadedFile('django.jpg', file.read(), content_type='image/jpg')
            form_data = {'django.jpg': imgfile}
            rsp = self.client.post('/upload', form_data, follow=True)

            self.assertEqual(rsp.status_code, 200)
        """
        data = SimpleUploadedFile(imagepath, b'file_content', content_type='image/jpg')
        rsp = self.client.post('/upload', {'django.jpg': data})
        self.assertEqual(rsp.status_code, 200)
        SimpleUploadedFile()
        """
test_plugins.py 文件源码 项目:DjangoCMS 作者: farhan711 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def test_fileplugin_icon_uppercase(self):
        page = api.create_page('testpage', 'nav_playground.html', 'en')
        body = page.placeholders.get(slot="body")
        plugin = File(
            plugin_type='FilePlugin',
            placeholder=body,
            position=1,
            language=settings.LANGUAGE_CODE,
        )
        # This try/except block allows older and newer versions of the
        # djangocms-file plugin to work here.
        try:
            plugin.file.save("UPPERCASE.JPG", SimpleUploadedFile(
                "UPPERCASE.jpg", b"content"), False)
        except ObjectDoesNotExist:  # catches 'RelatedObjectDoesNotExist'
            plugin.source.save("UPPERCASE.JPG", SimpleUploadedFile(
                "UPPERCASE.jpg", b"content"), False)
        plugin.add_root(instance=plugin)
        self.assertNotEquals(plugin.get_icon_url().find('jpg'), -1)
test_reversion_tests.py 文件源码 项目:DjangoCMS 作者: farhan711 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_file_persistence(self):
        content = b'content1'
        with reversion.create_revision():
            # add a file instance
            file1 = FileModel()
            file1.test_file.save('file1.txt', SimpleUploadedFile('file1.txt', content), False)
            file1.save()
            # manually add a revision because we use the explicit way
            # django-cms uses too.
            adapter = reversion.get_adapter(FileModel)
            reversion.revision_context_manager.add_to_context(
                reversion.default_revision_manager, file1,
                adapter.get_version_data(file1))
        # reload the instance from db
        file2 = FileModel.objects.all()[0]
        # delete the instance.
        file2.delete()

        # revert the old version
        file_version = reversion.get_for_object(file1)[0]
        file_version.revert()

        # reload the reverted instance and check for its content
        file1 = FileModel.objects.all()[0]
        self.assertEqual(file1.test_file.file.read(), content)
test_widgets.py 文件源码 项目:gougo 作者: amaozhao 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def test_render_uploaded(self):
        """
        The widget treats UploadedFile as no input.

        Rationale:
        When widget is used in ModelForm and the form (submitted with upload)
        is not valid, widget should discard the value (just like standard
        Django ClearableFileInput does).
        """
        widget = widgets.ImageClearableFileInput()
        base_widget = ClearableFileInput()
        file_name = 'test.jpg'
        # storage=None to get raw content.
        image = self.create_image(None, file_name)
        upload_file = SimpleUploadedFile(file_name, image.getvalue())
        html = widget.render('photo', upload_file)
        base_html = base_widget.render('photo', upload_file)
        self.assertEqual(base_html, html)
        self.assertNotIn(file_name, html)   # Widget is empty.
zip.py 文件源码 项目:gougo 作者: amaozhao 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
def unzip(file_obj):
    """
    Take a path to a zipfile and checks if it is a valid zip file
    and returns...
    """
    files = []
    # TODO: implement try-except here
    zip = ZipFile(file_obj)
    bad_file = zip.testzip()
    if bad_file:
        raise Exception('"%s" in the .zip archive is corrupt.' % bad_file)
    infolist = zip.infolist()
    for zipinfo in infolist:
        if zipinfo.filename.startswith('__'):  # do not process meta files
            continue
        file_obj = SimpleUploadedFile(name=zipinfo.filename, content=zip.read(zipinfo))
        files.append((file_obj, zipinfo.filename))
    zip.close()
    return files
seed.py 文件源码 项目:EvalAI 作者: Cloud-CV 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def create_challenge(title, start_date, end_date, host_team):
    """
    Creates a challenge.
    """
    evaluation_script = open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'string_matching.zip'), 'rb')
    Challenge.objects.create(
        title=title,
        short_description=fake.paragraph(),
        description=fake.paragraph(),
        terms_and_conditions=fake.paragraph(),
        submission_guidelines=fake.paragraph(),
        evaluation_details=fake.paragraph(),
        evaluation_script=SimpleUploadedFile(evaluation_script.name, evaluation_script.read()),
        approved_by_admin=True,
        creator=host_team,
        published=True,
        enable_forum=True,
        anonymous_leaderboard=False,
        start_date=start_date,
        end_date=end_date,
    )
    print("Challenge created with title: {} creator: {} start_date: {} end_date: {}".format(title,
                                                                                            host_team.team_name,
                                                                                            start_date, end_date))
seed.py 文件源码 项目:EvalAI 作者: Cloud-CV 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def create_challenge_phases(challenge, number_of_phases=1):
    """
    Creates challenge phases for the created challenges and returns it.
    """
    challenge_phases = []
    for i in range(number_of_phases):
        name = "{} Phase".format(fake.first_name())
        with open(os.path.join(settings.BASE_DIR, 'examples', 'example1', 'test_annotation.txt'), 'rb') as data_file:
            data = data_file.read()
        data = data or None
        challenge_phase = ChallengePhase.objects.create(
            name=name,
            description=fake.paragraph(),
            leaderboard_public=True,
            is_public=True,
            start_date=challenge.start_date,
            end_date=challenge.end_date,
            challenge=challenge,
            test_annotation=SimpleUploadedFile(fake.file_name(extension="txt"), data, content_type="text/plain"),
            codename="{}{}".format("phase", i + 1),
        )
        challenge_phases.append(challenge_phase)
        print("Challenge Phase created with name: {} challenge: {}".format(name, challenge.title))
    return challenge_phases
test_views.py 文件源码 项目:EvalAI 作者: Cloud-CV 项目源码 文件源码 阅读 17 收藏 0 点赞 0 评论 0
def setUp(self):
        super(BaseChallengePhaseClass, self).setUp()
        try:
            os.makedirs('/tmp/evalai')
        except OSError:
            pass

        with self.settings(MEDIA_ROOT='/tmp/evalai'):
            self.challenge_phase = ChallengePhase.objects.create(
                name='Challenge Phase',
                description='Description for Challenge Phase',
                leaderboard_public=False,
                is_public=True,
                start_date=timezone.now() - timedelta(days=2),
                end_date=timezone.now() + timedelta(days=1),
                challenge=self.challenge,
                test_annotation=SimpleUploadedFile('test_sample_file.txt',
                                                   'Dummy file content', content_type='text/plain'),
                max_submissions_per_day=100000,
                max_submissions=100000,
            )


问题


面经


文章

微信
公众号

扫码关注公众号