Example #1
1
    def from_file(filename, page, fileobj=None, newpath=None, upload=None, **kwargs):

        if not newpath:
            newpath = g.images_path

        # We dont' want drive letters or other path elements showing up here...
        # Unfortunately, basename only handles path seperators from the
        # platform it's running on (ie. on unix, it fails to handle windows
        # paths, so we have to convert the path seperators to match the local
        # platform.
        from communityalmanac.lib.helpers import normalize_filename
        filename = normalize_filename(filename)

        _, ext = os.path.splitext(filename)
        mimetype, _ = mimetypes.guess_type(filename)

        if not mimetype.startswith('image/'):
            raise ValueError(u'Invalid image file %s' % filename)

        if upload is not None:
            upload.make_file()
            fileobj = upload.file

        assert fileobj is not None, 'Programming error: file object not set'
        image_data = fileobj.read()
        new_uuid = str(uuid.uuid4())
        path = os.path.join(newpath, new_uuid) + ext
        with open(path, 'w') as f:
            f.write(image_data)

        image = Image(**kwargs)
        page.media.append(image)
        image.order = len(page.media)
        image.path = path
        image.create_scales(newpath)
        image.filename = filename
        return image