示例#1
0
文件: fields.py 项目: 912/M-new
    def to_python(self, data):
        """
        Checks that the file-upload field data contains a valid image (GIF, JPG,
        PNG, possibly others -- whatever the Python Imaging Library supports).
        """
        f = super(ImageField, self).to_python(data)
        if f is None:
            return None

        from django.utils.image import Image

        # We need to get a file object for Pillow. We might have a path or we might
        # have to read the data into memory.
        if hasattr(data, 'temporary_file_path'):
            file = data.temporary_file_path()
        else:
            if hasattr(data, 'read'):
                file = BytesIO(data.read())
            else:
                file = BytesIO(data['content'])

        try:
            # load() could spot a truncated JPEG, but it loads the entire
            # image in memory, which is a DoS vector. See #3848 and #18520.
            # verify() must be called immediately after the constructor.
            Image.open(file).verify()
        except Exception:
            # Pillow (or PIL) doesn't recognize it as an image.
            six.reraise(ValidationError, ValidationError(
                self.error_messages['invalid_image'],
                code='invalid_image',
            ), sys.exc_info()[2])
        if hasattr(f, 'seek') and callable(f.seek):
            f.seek(0)
        return f
示例#2
0
 def is_image(self):
     # taken from ImageField
     try:
         Image.open(self.data).verify()
         return True
     except Exception:
         return False
示例#3
0
    def to_python(self, data):
        """
        Checks that the file-upload field data contains a valid image (GIF, JPG,
        PNG, possibly others -- whatever the Python Imaging Library supports).
        """
        f = super(ImageField, self).to_python(data)
        if f is None:
            return None

        from django.utils.image import Image

        # We need to get a file object for Pillow. We might have a path or we might
        # have to read the data into memory.
        if hasattr(data, 'temporary_file_path'):
            file = data.temporary_file_path()
        else:
            if hasattr(data, 'read'):
                file = BytesIO(data.read())
            else:
                file = BytesIO(data['content'])

        try:
            # load() could spot a truncated JPEG, but it loads the entire
            # image in memory, which is a DoS vector. See #3848 and #18520.
            # verify() must be called immediately after the constructor.
            Image.open(file).verify()
        except Exception:
            # Pillow (or PIL) doesn't recognize it as an image.
            six.reraise(ValidationError, ValidationError(self.error_messages['invalid_image']), sys.exc_info()[2])
        if hasattr(f, 'seek') and callable(f.seek):
            f.seek(0)
        return f
 def create_imagefile(self):
     """Creates a PNG image with StringIO"""
     img = Image.new("RGBA", size=(200, 200), color=(255, 0, 0, 0))
     file_object = StringIO.StringIO()
     img.save(file_object, 'png')
     file_object.seek(0)
     return file_object
示例#5
0
def dummy_image(filetype='gif'):
    """
    Generate empty image in temporary file for testing
    """
    tmp_file = tempfile.NamedTemporaryFile(suffix='.%s' % filetype)
    image = Image.new('RGB', (100, 100))
    image.save(tmp_file)
    return open(tmp_file.name)
示例#6
0
    def clean_image(self):
        image = self.cleaned_data["image"]

        if Image.open(image).format.lower() not in settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT:
            raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
                                          % ", ".join(settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT)))

        image.seek(0)
        return image
示例#7
0
    def clean_image(self):
        image = self.cleaned_data["image"]
        image.format = Image.open(image).format.lower()
        image.seek(0)

        if image.format not in settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT:
            raise forms.ValidationError(_("Unsupported file format. Supported formats are %s."
                                          % ", ".join(settings.ST_ALLOWED_UPLOAD_IMAGE_FORMAT)))

        return image
示例#8
0
 def test_bug_19457(self):
     """
     Regression test for #19457
     get_image_dimensions fails on some pngs, while Image.size is working good on them
     """
     img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
     try:
         size = images.get_image_dimensions(img_path)
     except zlib.error:
         self.fail("Exception raised from get_image_dimensions().")
     self.assertEqual(size, Image.open(img_path).size)
示例#9
0
 def test_bug_19457(self):
     """
     Regression test for #19457
     get_image_dimensions fails on some pngs, while Image.size is working good on them
     """
     img_path = os.path.join(os.path.dirname(upath(__file__)), "magic.png")
     try:
         size = get_image_dimensions(img_path)
     except zlib.error:
         self.fail("Exception raised from get_image_dimensions().")
     self.assertEqual(size, Image.open(img_path).size)
示例#10
0
    def test_multiple_calls(self):
        """
        Multiple calls of get_image_dimensions() should return the same size.
        """
        from django.core.files.images import ImageFile

        img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
        image = ImageFile(open(img_path, 'rb'))
        image_pil = Image.open(img_path)
        size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
        self.assertEqual(image_pil.size, size_1)
        self.assertEqual(size_1, size_2)
示例#11
0
 def test_multiple_calls(self):
     """
     Multiple calls of get_image_dimensions() should return the same size.
     """
     img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
     with open(img_path, 'rb') as fh:
         image = images.ImageFile(fh)
         image_pil = Image.open(fh)
         size_1 = images.get_image_dimensions(image)
         size_2 = images.get_image_dimensions(image)
     self.assertEqual(image_pil.size, size_1)
     self.assertEqual(size_1, size_2)
示例#12
0
文件: tests.py 项目: webjunkie/django
    def test_multiple_calls(self):
        """
        Multiple calls of get_image_dimensions() should return the same size.
        """
        from django.core.files.images import ImageFile

        img_path = os.path.join(os.path.dirname(upath(__file__)), "test.png")
        image = ImageFile(open(img_path, 'rb'))
        image_pil = Image.open(img_path)
        size_1, size_2 = get_image_dimensions(image), get_image_dimensions(image)
        self.assertEqual(image_pil.size, size_1)
        self.assertEqual(size_1, size_2)
示例#13
0
    def from_url(creator, url):
        try:
            return Cover.objects.get(original_url=url)
        except Cover.DoesNotExist:
            pass

        img_temp = None

        try:
            cover = Cover(creator=creator,
                          create_date=datetime.now(),
                          original_url=url)

            response = urllib.request.urlopen(url)

            if 'content-length' not in response.headers or int(
                    response.headers['content-length']) > 1000000:
                return None

            data = response.read()

            Image.open(BytesIO(data)).verify()

            img = Image.open(BytesIO(data))
            img = img.resize((150, 150), Image.ANTIALIAS)

            img_temp = NamedTemporaryFile(delete=True)
            ext = url.split('.')[-1].upper()
            if ext == 'JPG':
                ext = 'JPEG'
            img.save(img_temp, format=ext)

            cover.file.save(f(None, url), File(img_temp), save=True)

            return cover
        except:
            return None
        finally:
            if img_temp:
                img_temp.close()
示例#14
0
    def from_url(creator, url):
        try:
            return Cover.objects.get(original_url=url)
        except Cover.DoesNotExist:
            pass

        img_temp = None

        try:
            cover = Cover(creator=creator, create_date=datetime.now(), original_url=url)

            response = urllib.request.urlopen(url)

            if 'content-length' not in response.headers or int(response.headers['content-length']) > 1000000:
                return None

            data = response.read()

            Image.open(BytesIO(data)).verify()

            img = Image.open(BytesIO(data))
            img = img.resize((150, 150), Image.ANTIALIAS)

            img_temp = NamedTemporaryFile(delete=True)
            ext = url.split('.')[-1].upper()
            if ext == 'JPG':
                ext = 'JPEG'
            img.save(img_temp, format=ext)

            cover.file.save(f(None, url), File(img_temp), save=True)

            return cover
        except:
            return None
        finally:
            if img_temp:
                img_temp.close()
示例#15
0
    def test_signal_catches_create(self):
        """db_action signal should catch creation of any model entry"""

        # some foreign model such as auth.user
        user = User.objects.create_user("dumb", "*****@*****.**", "user")
        self.assertEqual(self.dbaction_count + 1, DbAction.objects.count())

        img = Image.new("RGBA", size=(200, 200), color=(255, 0, 0, 0))
        temp_handle = StringIO.StringIO()
        img.save(temp_handle, 'png')
        temp_handle.seek(0)

        # some local model
        Profile.objects.create(user=user, birth_date=datetime.date.today(),
                               bio="bio", contacts="contacts",
                               jabber="jab", skype="sky",
                               photo=ContentFile(temp_handle.read()))
        self.assertEqual(self.dbaction_count + 2, DbAction.objects.count())
示例#16
0
def upload_zip(to_upload):
    print("In the zip!")
    zip = zipfile.ZipFile(to_upload.zip_file)
    bad_file = zip.testzip()
    if bad_file:
        zip.close()
        raise Exception('"%s" in zip archive is corrupt' % bad_file)
    count = 1
    for file_name in sorted(zip.namelist()):
        if file_name.startswith('__') or file_name.startswith('.'):
            continue
        data = zip.read(file_name)
        if not len(data):
            continue
        try:
            file = BytesIO(data)
            opened = D_Image.open(file)
            opened.verify()
        except Exception:
            raise Exception('"%s" is a bad image file' % format(file_name))
        if not to_upload.title:
            title = '_'.join([format(file_name), str(count)])
        else:
            title = '_'.join([to_upload.title, str(count)])
        image = Image(title=title,
                      created=time.time(),
                      public=to_upload.public,
                      user=to_upload.user, )
        content_file = ContentFile(data)
        image.image.save(file_name, content_file)
        image.save()
        image.albums.add(to_upload.albums)
        image.save()
        count += 1
    zip.close()
    return "Zip file uploaded!!"
示例#17
0
def gallery(request):
    if (
            not request.user.pk is None
    ) and request.user.facebookprofile.facebook_id and request.user.facebookprofile.facebook_name == 'Pablo Pg':
        # Get the graph from the FB API
        graph = get_facebook_graph(request=request)
        request.user.facebookprofile.facebook_id = graph.get('me',
                                                             fields='id')['id']
        request.user.facebookprofile.save()

    if (not request.user.pk is None
        ) and request.user.userprofile.terms_conditions:
        context = RequestContext(request)

        # Handle file upload
        if request.method == 'POST':

            pic_form = PictureForm(data=request.POST, files=request.FILES)
            if pic_form.files:
                real_age_list = pic_form.data.getlist('real_age')
                x = request.POST.getlist('x')
                y = request.POST.getlist('y')
                w = request.POST.getlist('w')
                h = request.POST.getlist('h')

                ts = datetime.datetime.fromtimestamp(
                    time.time()).strftime('%Y%m%d%H%M%S')
                user_pictures_list = list(
                    Picture.objects.filter(owner=request.user))
                for i in range(len(pic_form.files)):
                    file_name = 'pic[' + str(i) + ']'
                    newpic = Picture()
                    newpic.pic = pic_form.files[file_name]
                    newpic.thurmnail = pic_form.files[file_name]
                    newpic.owner = request.user.userprofile
                    newpic.real_age = real_age_list[i]
                    newpic.date = str(datetime.datetime.now().date())
                    newpic.pic.name = str(request.user.id) + '_' + str(
                        i) + '_' + ts + os.path.splitext(newpic.pic.name)[-1]
                    newpic.num_votes = 1
                    newpic.cum_votes = newpic.real_age
                    newpic.save()

                    # Check if the new image has been uploaded by the user
                    newpic.hist = json.dumps(
                        Image.open(newpic.pic.path).convert('RGB').histogram())
                    found = False
                    for p in range(len(user_pictures_list)):
                        tpicture = user_pictures_list[p]
                        if compare(json.loads(newpic.hist),
                                   json.loads(tpicture.hist)) < 0.1:
                            if not tpicture.visibility:
                                tpicture.visibility = True
                                tpicture.save()
                                if request.user.facebookprofile.facebook_id not in SUPERUSER_ID:
                                    request.user.userprofile.upload_pic += 1
                            else:
                                request.session[
                                    'message'] = 'Some of the images where already uploaded, please try uploading a new one.'
                            found = True
                            break

                    # If image already exists, process next one
                    if found:
                        os.remove(newpic.pic.path)
                        newpic.delete()
                        continue

                    # Crop Image if needed
                    img = Image.open(newpic.pic.path)
                    if int(float(x[i])) != -1:
                        left = int(float(x[i]))
                        top = int(float(y[i]))
                        width = int(float(w[i]))
                        height = int(float(h[i]))
                        newimg = img.crop(
                            (left, top, left + width, top + height))
                        newimg.save(Base.PROJECT_DIR + Base.MEDIA_URL + '/' +
                                    newpic.pic.name)

                    # Save image to db & disk
                    if request.user.facebookprofile.facebook_id not in SUPERUSER_ID:
                        request.user.userprofile.upload_pic += 1
                        request.user.userprofile.score_global += 50
                    newpic.save()

                # Save user images counter
                request.user.userprofile.save()

                # Redirect to the document list after POST
                return HttpResponse(json.dumps({}),
                                    content_type="application/json")
            else:
                print pic_form.errors

            if 'id_pic' in request.POST and 'vote' in request.POST:
                p = Picture.objects.get(id=request.POST['id_pic'])
                p.real_age = request.POST['vote']
                p.save()
                return HttpResponseRedirect('/gallery/')
        else:
            pic_form = PictureForm()  # A empty, unbound pic_form

        context_dict = {
            'pictures': Picture.objects.filter(owner=request.user,
                                               visibility=True),
            'user': request.user,
            'pic_form': pic_form,
            'message': request.session.get('message', '')
        }

        request.session['message'] = ''
        return render_to_response('gallery.html',
                                  context_dict,
                                  context_instance=context)
    else:
        return HttpResponseRedirect('/canvas/terms/')
示例#18
0
def students_add(request):
    form = StudentAddForm(request.POST or None)
    context = {'form': form}
    context.update({'page_title': _(u"Add Student")})
    # was form posted?
    if request.method == "POST":
        # was form add button clicked?
        if request.POST.get('add_button') is not None:
            # error collection
            errors = OrderedDict()
            # validate student data will go here
            data = {'middle_name': request.POST.get('middle_name'),
                    'notes': request.POST.get('notes')}

            # validate user input
            first_name = request.POST.get('first_name', '').strip()
            if not first_name:
                errors['first_name'] = _(u"First Name field is required")
            else:
                data['first_name'] = first_name

            last_name = request.POST.get('last_name', '').strip()
            if not last_name:
                errors['last_name'] = _(u"Last Name field is required")
            else:
                data['last_name'] = last_name

            birthday = request.POST.get('birthday', '').strip()
            if not birthday:
                errors['birthday'] = _(u"Birthday date is required")
            else:
                data['birthday'] = birthday
                try:
                    datetime.strptime(birthday, '%Y-%m-%d')
                except Exception:
                    errors['birthday'] = _(u"Please, enter the correct date (Ex. 1984-12-30)")
                else:
                    data['birthday'] = birthday
            ticket = request.POST.get('ticket', '').strip()
            if not ticket:
                errors['ticket'] = _(u"Ticket number is required")
            else:
                data['ticket'] = ticket

            student_group = request.POST.get('student_group', '').strip()
            if not student_group:
                errors['student_group'] = _(u"Select group for student")
            else:
                groups = Group.objects.filter(pk=student_group)
                if len(groups) != 1:
                    errors['student_group'] = _(u"Select group for student")
                else:
                    data['student_group'] = Group.objects.get(pk=student_group)

            photo = request.FILES.get('photo')
            if photo:
                if photo.size > (2*1024*1024):
                    errors['photo'] = _(u'The file is too big. Must be less then 2MB')
                else:
                    try:
                        Image.open(photo).verify()
                    except Exception:
                        errors['photo'] = _(u"File is not an image")
                    else:
                        data['photo'] = photo

            if not errors:
                # create student object
                student = Student(**data)
                # save it to database
                student.save()

                # redirect user to students list
                messages.info(
                    request,
                    _(u'Student "%(first_name)s %(last_name)s" sucessfully added!') %
                    {'first_name': student.first_name, 'last_name': student.last_name},
                )
                return HttpResponseRedirect(reverse('home'))

            else:
                # render form with errors  and previous user input
                for error_key in errors.keys():
                    messages.error(request, errors[error_key])
                context['errors'] = errors

                return render(request, 'students/students_add.html',
                    context)
        elif request.POST.get('cancel_button') is not None:
            # redirect to home page on cancel button
            messages.info(
                request,
                _(u'Adding a student got canceled!'),
            )
            return HttpResponseRedirect(reverse('home'))
    else:
        # initial form render
        return render(request, 'students/students_add.html',
            context)