Python django.core.files.storage.default_storage.save() Examples

The following are 30 code examples of django.core.files.storage.default_storage.save(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.core.files.storage.default_storage , or try the search function .
Example #1
Source File: briefcase_client.py    From kobo-predict with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def download_media_files(self, xml_doc, media_path):
        for media_node in xml_doc.getElementsByTagName('mediaFile'):
            filename_node = media_node.getElementsByTagName('filename')
            url_node = media_node.getElementsByTagName('downloadUrl')
            if filename_node and url_node:
                filename = filename_node[0].childNodes[0].nodeValue
                path = os.path.join(media_path, filename)
                if default_storage.exists(path):
                    continue
                download_url = url_node[0].childNodes[0].nodeValue
                if self._get_media_response(download_url):
                    download_res = self._current_response
                    media_content = ContentFile(download_res.content)
                    default_storage.save(path, media_content)
                    self.logger.debug("Fetched %s." % filename)
                else:
                    self.logger.error("Failed to fetch %s." % filename) 
Example #2
Source File: views.py    From kobo-predict with BSD 2-Clause "Simplified" License 7 votes vote down vote up
def profile_settings(request, username):
    content_user = check_and_set_user(request, username)
    profile, created = UserProfile.objects.get_or_create(user=content_user)
    if request.method == 'POST':
        form = UserProfileForm(request.POST, instance=profile)
        if form.is_valid():
            # get user
            # user.email = cleaned_email
            form.instance.user.email = form.cleaned_data['email']
            form.instance.user.save()
            form.save()
            # todo: add string rep. of settings to see what changed
            audit = {}
            audit_log(
                Actions.PROFILE_SETTINGS_UPDATED, request.user, content_user,
                _("Profile settings updated."), audit, request)
            return HttpResponseRedirect(reverse(
                public_profile, kwargs={'username': request.user.username}
            ))
    else:
        form = UserProfileForm(
            instance=profile, initial={"email": content_user.email})

    return render(request, "settings.html",
                  {'content_user': content_user, 'form': form}) 
Example #3
Source File: benefits.py    From DjanGoat with MIT License 6 votes vote down vote up
def silence_streams(func):
        def wrapper(*args, **kwargs):
            # save stderr
            save_streams = sys.__stderr__
            save_streams.flush()
            # file descriptor for stderr is 2
            save_stderr = os.dup(2)
            # silence
            null_fd = os.open(os.devnull, os.O_RDWR)
            os.dup2(null_fd, 2)
            # uncomment the line to test if stderr is silenced
            # 1/0
            try:
                bak_file_path = func(*args, **kwargs)
                sys.stderr = save_streams
                os.dup2(save_stderr, 2)
                return bak_file_path
            except:
                sys.stderr = save_streams
                os.dup2(save_stderr, 2)
        return wrapper 
Example #4
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_open_read_write(self):
        self.storage.location = 'root'
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('file.txt', stream)
        fh = self.storage.open(name, 'r+b')
        try:
            self.assertEqual(fh.read(), b'Im a stream')
            fh.write(b' foo')
            fh.seek(0)
            self.assertEqual(fh.read(), b'Im a stream foo')
        finally:
            fh.close()

        stream = io.BytesIO()
        self.storage.service.get_blob_to_stream(
            container_name=self.storage.azure_container,
            blob_name='root/file.txt',
            stream=stream,
            max_connections=1,
            timeout=10)
        stream.seek(0)
        self.assertEqual(stream.read(), b'Im a stream foo') 
Example #5
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_open_read(self):
        self.storage.location = 'root'
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('path/some file.txt', stream)
        fh = self.storage.open(name, 'r+b')
        try:
            self.assertEqual(fh.read(), b'Im a stream')
        finally:
            fh.close()

        stream = io.BytesIO()
        self.storage.service.get_blob_to_stream(
            container_name=self.storage.azure_container,
            blob_name='root/path/some file.txt',
            stream=stream,
            max_connections=1,
            timeout=10)
        stream.seek(0)
        self.assertEqual(stream.read(), b'Im a stream') 
Example #6
Source File: models.py    From django-pyas2 with GNU General Public License v3.0 6 votes vote down vote up
def create_from_as2mdn(self, as2mdn, message, status, return_url=None):
        """Create the MDN from the pyas2lib's MDN object"""
        signed = True if as2mdn.digest_alg else False
        mdn, _ = self.update_or_create(
            message=message,
            defaults=dict(
                mdn_id=as2mdn.message_id,
                status=status,
                signed=signed,
                return_url=return_url,
            ),
        )
        filename = f"{uuid4()}.mdn"
        mdn.headers.save(
            name=f"{filename}.header", content=ContentFile(as2mdn.headers_str)
        )
        mdn.payload.save(filename, content=ContentFile(as2mdn.content))
        return mdn 
Example #7
Source File: views.py    From texta with GNU General Public License v3.0 6 votes vote down vote up
def add_dataset(request):
    daterange = ""
    dataset = Dataset(author=request.user, index=request.POST['index'],
                      mapping=request.POST['mapping'], daterange=daterange, access=(request.POST['access']))
    dataset.save()

    create_dataset_access_permission_and_propagate(dataset, request.POST['access'])
    indices = ES_Manager.get_indices()
    ds_out = dataset.__dict__
    for index in indices:
        if index['index'] == ds_out['index']:
            ds_out['status'] = index['status']
            ds_out['docs_count'] = index['docs_count']
            ds_out['store_size'] = index['store_size']
            break
        elif '*' in ds_out['index']:
            ds_out['status'] = 'open'
            ds_out['docs_count'] = 'multiindex'
            ds_out['store_size'] = 'multiindex'
    ds_out['_state'] = ''
    ds_out['author'] = request.user.get_username()
    return JsonResponse(ds_out) 
Example #8
Source File: models.py    From django-pyas2 with GNU General Public License v3.0 6 votes vote down vote up
def send_async_mdn(self):
        """ Send the asynchronous MDN to the partner"""

        # convert the mdn headers to dictionary
        headers = HeaderParser().parsestr(self.headers.read().decode())

        # Send the mdn to the partner
        try:
            response = requests.post(
                self.return_url, headers=dict(headers.items()), data=self.payload.read()
            )
            response.raise_for_status()
        except requests.exceptions.RequestException:
            return

        # Update the status of the MDN
        self.status = "S"
        self.save() 
Example #9
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_model_form(self):
        files = {
            'foo_file': SimpleUploadedFile(
                name='foo.pdf',
                content=b'foo content',
                content_type='application/pdf')}
        form = FooFileModelForm(data={}, files=files)
        self.assertTrue(form.is_valid())
        form.save()
        self.assertTrue(default_storage.exists('foo_uploads/foo.pdf'))

        # check file content was saved
        fh = default_storage.open('foo_uploads/foo.pdf', 'r+b')
        try:
            self.assertEqual(fh.read(), b'foo content')
        finally:
            fh.close() 
Example #10
Source File: addscript.py    From django-djangui with GNU General Public License v3.0 6 votes vote down vote up
def handle(self, *args, **options):
        script = options.get('script')
        if not script:
            if len(args):
                 script = args[0]
            else:
                raise CommandError('You must provide a script path or directory containing scripts.')
        if not os.path.exists(script):
            raise CommandError('{0} does not exist.'.format(script))
        group = options.get('group', 'Djangui Scripts')
        scripts = [os.path.join(script, i) for i in os.listdir(script)] if os.path.isdir(script) else [script]
        converted = 0
        for script in scripts:
            if script.endswith('.pyc') or '__init__' in script:
                continue
            if script.endswith('.py'):
                sys.stdout.write('Converting {}\n'.format(script))
                # copy the script to our storage
                with open(script, 'r') as f:
                    script = default_storage.save(os.path.join(djangui_settings.DJANGUI_SCRIPT_DIR, os.path.split(script)[1]), File(f))
                added, error = add_djangui_script(script=os.path.abspath(os.path.join(settings.MEDIA_ROOT, script)), group=group)
                if added:
                    converted += 1
        sys.stdout.write('Converted {} scripts\n'.format(converted)) 
Example #11
Source File: tasks.py    From feedsubs with MIT License 5 votes vote down vote up
def create_feed(user_id: int, uri: str):
    try:
        user = get_user_model().objects.get(pk=user_id)
    except ObjectDoesNotExist:
        logger.warning('Not creating feed "%s" as user %d does not exist',
                       uri, user_id)
        return

    # Check if the feed already exists
    parsed_feed = None
    try:
        feed = models.Feed.objects.get(uri=uri)
    except ObjectDoesNotExist:
        feed = None
    else:
        logger.info('Feed already exists: %s', feed)

    if feed is None:
        try:
            feed, parsed_feed = _fetch_and_create_feed(uri)
        except FeedFetchError as e:
            logger.warning('%s', e)
            background_messages.warning(user, str(e))
            return

    _subscribe_user(user, feed)

    if parsed_feed is not None:
        synchronize_parsed_feed(feed, parsed_feed)
        feed.frequency_per_year = calculate_frequency_per_year(feed)
        feed.save(update_fields=['frequency_per_year']) 
Example #12
Source File: tmp_storages.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def save(self, data, mode=None):
        if not self.name:
            self.name = uuid4().hex
        default_storage.save(self.get_full_path(), ContentFile(data)) 
Example #13
Source File: tasks.py    From feedsubs with MIT License 5 votes vote down vote up
def _subscribe_user(user, feed):
    subscription = models.Subscription(
        feed=feed, reader=user.reader_profile
    )
    try:
        subscription.save()
    except IntegrityError as e:
        logger.warning('User probably already subscribed to the feed: %s', e)
    else:
        logger.info('User subscribed to feed') 
Example #14
Source File: imapemail.py    From modoboa-webmail with MIT License 5 votes vote down vote up
def _fetch_inlines(self):
        """Store inline images on filesystem to display them."""
        for cid, params in list(self.bs.inlines.items()):
            if re.search(r"\.\.", cid):
                continue
            fname = "modoboa_webmail/%s_%s" % (self.mailid, cid)
            path = os.path.join(settings.MEDIA_ROOT, fname)
            params["fname"] = os.path.join(settings.MEDIA_URL, fname)
            if default_storage.exists(path):
                continue
            pdef, content = self.imapc.fetchpart(
                self.mailid, self.mbox, params["pnum"]
            )
            default_storage.save(
                path, ContentFile(decode_payload(params["encoding"], content))) 
Example #15
Source File: benefits.py    From DjanGoat with MIT License 5 votes vote down vote up
def save_data(uploaded_file, backup=None):
        data_path = os.path.join(settings.MEDIA_ROOT, "data")
        full_file_name = os.path.join(data_path, uploaded_file.name)
        # the uploaded file is read at once, as duplicated in railsgoat
        # use file.chunk() in a loop can prevent overwhelming system memory
        content = ContentFile(uploaded_file.read())
        default_storage.save(full_file_name, content)
        # using string "true" is intended to duplicate railsgoat's behavior
        if backup == "true":
            return Benefits.make_backup(uploaded_file, data_path,
                                        full_file_name) 
Example #16
Source File: test_frontend.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def save_test_image(cls, filename):
        from PIL import Image

        image = Image.new("RGB", (1, 1), 0)
        image_buffer = BytesIO()
        image.save(image_buffer, format="JPEG")
        path = f"tests/{filename}"
        default_storage.save(path, image_buffer)
        return path 
Example #17
Source File: test_frontend.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def save_test_image(cls, filename):
        from PIL import Image

        image = Image.new("RGB", (1, 1), 0)
        image_buffer = BytesIO()
        image.save(image_buffer, format="JPEG")
        path = f"tests/{filename}"
        default_storage.save(path, image_buffer)
        return path 
Example #18
Source File: test_frontend.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def save_test_image(cls, filename):
        from PIL import Image

        image = Image.new("RGB", (1, 1), 0)
        image_buffer = BytesIO()
        image.save(image_buffer, format="JPEG")
        path = f"tests/{filename}"
        default_storage.save(path, image_buffer)
        return path 
Example #19
Source File: views.py    From Django-3-Web-Development-Cookbook-Fourth-Edition with MIT License 5 votes vote down vote up
def upload_file(request):
    status_code = 400
    data = {"files": [], "error": _("Bad request")}
    if request.method == "POST" and request.is_ajax() and "picture" in request.FILES:
        file_types = [f"image/{x}" for x in ["gif", "jpg", "jpeg", "png"]]
        file = request.FILES.get("picture")
        if file.content_type not in file_types:
            status_code = 405
            data["error"] = _("Invalid file format")
        else:
            upload_to = _upload_to(request, file.name)
            name = default_storage.save(upload_to, ContentFile(file.read()))
            file = default_storage.open(name)
            status_code = 200
            del data["error"]
            absolute_uploads_dir = os.path.join(
                settings.MEDIA_ROOT, "temporary-uploads"
            )
            file.filename = os.path.basename(file.name)
            data["files"].append(
                {
                    "name": file.filename,
                    "size": file.size,
                    "deleteType": "DELETE",
                    "deleteUrl": (
                        reverse("delete_file") + f"?filename={file.filename}"
                    ),
                    "path": file.name[len(absolute_uploads_dir) + 1 :],
                }
            )

    return JsonResponse(data, status=status_code) 
Example #20
Source File: checks.py    From django-watchman with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _check_storage():
    filename = joinpath(watchman_settings.WATCHMAN_STORAGE_PATH, 'django-watchman-{}.txt'.format(uuid.uuid4()))
    content = b'django-watchman test file'
    path = default_storage.save(filename, ContentFile(content))
    default_storage.size(path)
    default_storage.open(path).read()
    default_storage.delete(path)
    return {"ok": True} 
Example #21
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_modified_time_no_tz(self):
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('some path/some blob Ϊ.txt', stream)
        self.assertTrue(timezone.is_naive(self.storage.modified_time(name))) 
Example #22
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_modified_time_no_tz(self):
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('some path/some blob Ϊ.txt', stream)
        self.assertTrue(timezone.is_naive(self.storage.get_modified_time(name))) 
Example #23
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_get_modified_time_tz(self):
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save('some path/some blob Ϊ.txt', stream)
        self.assertTrue(timezone.is_aware(self.storage.get_modified_time(name))) 
Example #24
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_size(self):
        self.storage.location = 'path'
        expected_name = "some path/some blob Ϊ.txt"
        self.assertFalse(self.storage.exists(expected_name))
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save(expected_name, stream)
        self.assertEqual(name, expected_name)
        self.assertTrue(self.storage.exists(expected_name))
        self.assertEqual(self.storage.size(expected_name), len(b'Im a stream')) 
Example #25
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_delete(self):
        self.storage.location = 'path'
        expected_name = "some blob Ϊ.txt"
        self.assertFalse(self.storage.exists(expected_name))
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save(expected_name, stream)
        self.assertEqual(name, expected_name)
        self.assertTrue(self.storage.exists(expected_name))
        self.storage.delete(expected_name)
        self.assertFalse(self.storage.exists(expected_name)) 
Example #26
Source File: test_azure.py    From django-storages with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def test_save(self):
        expected_name = "some blob Ϊ.txt"
        self.assertFalse(self.storage.exists(expected_name))
        stream = io.BytesIO(b'Im a stream')
        name = self.storage.save(expected_name, stream)
        self.assertEqual(name, expected_name)
        self.assertTrue(self.storage.exists(expected_name)) 
Example #27
Source File: forms.py    From Spirit with MIT License 5 votes vote down vote up
def save(self):
        return save_user_file(
            user=self.user,
            file=self.cleaned_data['file'],
            subdir='files',
            hashed=settings.ST_PREVENT_SOME_FILE_DUPLICATION) 
Example #28
Source File: forms.py    From Spirit with MIT License 5 votes vote down vote up
def save(self):
        return save_user_file(
            user=self.user,
            file=self.cleaned_data['image'],
            subdir='images',
            hashed=settings.ST_PREVENT_SOME_FILE_DUPLICATION) 
Example #29
Source File: forms.py    From Spirit with MIT License 5 votes vote down vote up
def save(self):
        comments = self.cleaned_data['comments']
        comments_list = list(comments)
        topic = self.cleaned_data['topic']
        comments.update(topic=topic)

        # Update topic in comment instance
        for c in comments_list:
            c.topic = topic

        return comments_list 
Example #30
Source File: forms.py    From Spirit with MIT License 5 votes vote down vote up
def save(self, commit=True):
        if not self.instance.pk:
            self.instance.user = self.user
            self.instance.topic = self.topic

        self.instance.comment_html = self._get_comment_html()
        comment = super(CommentForm, self).save(commit)

        if commit:
            self._save_polls()

        return comment