Python django.core.files.storage.FileSystemStorage() Examples

The following are 30 code examples for showing how to use django.core.files.storage.FileSystemStorage(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.core.files.storage , or try the search function .

Example 1
Project: Gerapy   Author: Gerapy   File: views.py    License: MIT License 7 votes vote down vote up
def project_upload(request):
    """
    upload project
    :param request: request object
    :return: json
    """
    if request.method == 'POST':
        file = request.FILES['file']
        file_name = file.name
        fs = FileSystemStorage(PROJECTS_FOLDER)
        zip_file_name = fs.save(file_name, file)
        logger.debug('zip file name %s', zip_file_name)
        # extract zip file
        with zipfile.ZipFile(join(PROJECTS_FOLDER, zip_file_name), 'r') as zip_ref:
            zip_ref.extractall(PROJECTS_FOLDER)
        logger.debug('extracted files to %s', PROJECTS_FOLDER)
        return JsonResponse({'status': True}) 
Example 2
Project: django-docker-s3   Author: testdrivenio   File: views.py    License: MIT License 6 votes vote down vote up
def image_upload(request):
    if request.method == 'POST':
        image_file = request.FILES['image_file']
        image_type = request.POST['image_type']
        if settings.USE_S3:
            if image_type == 'private':
                upload = UploadPrivate(file=image_file)
            else:
                upload = Upload(file=image_file)
            upload.save()
            image_url = upload.file.url
        else:
            fs = FileSystemStorage()
            filename = fs.save(image_file.name, image_file)
            image_url = fs.url(filename)
        return render(request, 'upload.html', {
            'image_url': image_url
        })
    return render(request, 'upload.html') 
Example 3
Project: Pytition   Author: pytition   File: views.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def image_upload(request):
    pytitionuser = get_session_user(request)

    if request.method != "POST":
        return HttpResponseForbidden()

    file = request.FILES.get('file', '')
    if file == '':
        return HttpResponseForbidden()

    storage = FileSystemStorage()
    path = os.path.join(storage.location, pytitionuser.username, file.name)
    name = storage._save(path, file)
    newrelpath = os.path.relpath(name, storage.location)

    return JsonResponse({'location': storage.base_url + newrelpath})

# /transfer_petition/<int:petition_id>
# Transfer a petition to another org or user 
Example 4
Project: django-drf-filepond   Author: ImperialCollegeLondon   File: test_signals.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_del_tmp_upload_file(self):
        # Create a temporary file
        tmp_dir = mkdtemp(prefix='django_test_')
        self.assertTrue(os.path.exists(tmp_dir),
                        'Test temp file was not created.')
        tmp_dir_split = tmp_dir.rsplit(os.sep, 1)
        _, path = mkstemp(suffix='.txt', prefix='django_test_', text=True)
        self.assertTrue(os.path.exists(path),
                        'Test temp file was not created.')

        # Mock a TemporaryUpload instance object
        tu = Mock(spec=TemporaryUpload)
        upload_file = Mock(spec=SimpleUploadedFile)
        models.storage = Mock(spec=FileSystemStorage)
        models.storage.location = tmp_dir_split[0]

        upload_file.path = path
        tu.upload_id = tmp_dir_split[1]
        tu.file = upload_file
        delete_temp_upload_file(None, tu)
        self.assertFalse(os.path.exists(path), 'Test temp file was not '
                         'removed by the signal handler.') 
Example 5
Project: django-drf-filepond   Author: ImperialCollegeLondon   File: test_process_view.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_process_invalid_storage_location(self):
        old_storage = views.storage
        views.storage = FileSystemStorage(location='/django_test')
        (encoded_form, content_type) = self._get_encoded_form('testfile.dat')

        rf = RequestFactory()
        req = rf.post(reverse('process'),
                      data=encoded_form, content_type=content_type)
        pv = views.ProcessView.as_view()
        response = pv(req)
        views.storage = old_storage
        self.assertEqual(response.status_code, 500, 'Expecting 500 error due'
                         ' to invalid storage location.')
        self.assertEqual(
            response.data,
            'The file upload path settings are not configured correctly.',
            ('Expecting error showing path settings are configured '
             'incorrectly.')) 
Example 6
Project: django-drf-filepond   Author: ImperialCollegeLondon   File: test_process_view.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_store_upload_with_storage_outside_BASE_DIR_without_enable(self):
        old_storage = views.storage
        views.storage = FileSystemStorage(location='/tmp/uploads')
        (encoded_form, content_type) = self._get_encoded_form('testfile.dat')

        rf = RequestFactory()
        req = rf.post(reverse('process'),
                      data=encoded_form, content_type=content_type)
        pv = views.ProcessView.as_view()
        response = pv(req)
        views.storage = old_storage
        self.assertEqual(response.status_code, 500, 'Expecting 500 error due'
                         ' to invalid storage location.')
        self.assertEqual(
            response.data,
            'The file upload path settings are not configured correctly.',
            ('Expecting error showing path settings are configured '
             'incorrectly.')) 
Example 7
Project: django-drf-filepond   Author: ImperialCollegeLondon   File: test_process_view.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def test_store_upload_with_storage_outside_BASE_DIR_with_enable(self):
        old_storage = views.storage
        old_UPLOAD_TMP = drf_filepond_settings.UPLOAD_TMP

        drf_filepond_settings.ALLOW_EXTERNAL_UPLOAD_DIR = True

        views.storage = FileSystemStorage(location='/tmp/uploads')
        drf_filepond_settings.UPLOAD_TMP = '/tmp/uploads'

        (encoded_form, content_type) = self._get_encoded_form('testfile.dat')

        rf = RequestFactory()
        req = rf.post(reverse('process'),
                      data=encoded_form, content_type=content_type)
        pv = views.ProcessView.as_view()
        response = pv(req)
        views.storage = old_storage
        drf_filepond_settings.UPLOAD_TMP = old_UPLOAD_TMP
        drf_filepond_settings.ALLOW_EXTERNAL_UPLOAD_DIR = False
        self.assertEqual(response.status_code, 200, 'Expecting upload to be '
                         'successful.') 
Example 8
def enqueue_image(person, user, image_url):
    r = requests.get(
        image_url,
        headers={
            'User-Agent': USER_AGENT,
        },
        stream=True
    )
    if not r.status_code == 200:
        message = "HTTP status code {0} when downloading {1}"
        raise Exception(message.format(r.status_code, image_url))
    storage = FileSystemStorage()
    suggested_filename = \
        'queued_image/{d.year}/{d.month:02x}/{d.day:02x}/ci-upload'.format(
            d=date.today()
        )
    storage_filename = storage.save(suggested_filename, r.raw)
    QueuedImage.objects.create(
        why_allowed=QueuedImage.OTHER,
        justification_for_use="Downloaded from {0}".format(image_url),
        decision=QueuedImage.UNDECIDED,
        image=storage_filename,
        person_id=person.id,
        user=user
    ) 
Example 9
def enqueue_image(person, user, image_url):
    r = requests.get(
        image_url,
        headers={
            'User-Agent': USER_AGENT,
        },
        stream=True
    )
    if not r.status_code == 200:
        message = "HTTP status code {0} when downloading {1}"
        raise Exception(message.format(r.status_code, image_url))
    storage = FileSystemStorage()
    suggested_filename = \
        'queued_image/{d.year}/{d.month:02x}/{d.day:02x}/ci-upload'.format(
            d=date.today()
        )
    storage_filename = storage.save(suggested_filename, r.raw)
    QueuedImage.objects.create(
        why_allowed=QueuedImage.OTHER,
        justification_for_use="Downloaded from {0}".format(image_url),
        decision=QueuedImage.UNDECIDED,
        image=storage_filename,
        person_id=person.id,
        user=user
    ) 
Example 10
Project: django-plotly-dash   Author: GibbsConsulting   File: finders.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        # get all registered apps

        self.locations = []
        self.storages = OrderedDict()

        self.ignore_patterns = ["*.py", "*.pyc",]

        for app_config in apps.get_app_configs():

            path_directory = os.path.join(app_config.path, 'assets')

            if os.path.isdir(path_directory):

                storage = FileSystemStorage(location=path_directory)

                storage.prefix = full_asset_path(app_config.name, "")

                self.locations.append(app_config.name)
                self.storages[app_config.name] = storage

        super(DashAppDirectoryFinder, self).__init__()

    #pylint: disable=redefined-builtin 
Example 11
Project: GTDWeb   Author: lanbing510   File: storage.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super(StaticFilesStorage, self).__init__(location, base_url,
                                                 *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None 
Example 12
Project: GTDWeb   Author: lanbing510   File: collectstatic.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage) 
Example 13
Project: kobo-predict   Author: awemulya   File: views.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def export_download(request, username, id_string, export_type, filename):
    owner = get_object_or_404(User, username__iexact=username)
    xform = get_object_or_404(XForm, id_string__exact=id_string, user=owner)
    helper_auth_helper(request)
    if not has_forms_permission(xform, owner, request):
        return HttpResponseForbidden(_(u'Not shared.'))

    # find the export entry in the db
    export = get_object_or_404(Export, xform=xform, filename=filename)

    if (export_type == Export.GDOC_EXPORT or export_type == Export.EXTERNAL_EXPORT) \
            and export.export_url is not None:
        return HttpResponseRedirect(export.export_url)

    ext, mime_type = export_def_from_filename(export.filename)

    audit = {
        "xform": xform.id_string,
        "export_type": export.export_type
    }
    audit_log(
        Actions.EXPORT_DOWNLOADED, request.user, owner,
        _("Downloaded %(export_type)s export '%(filename)s' "
          "on '%(id_string)s'.") %
        {
            'export_type': export.export_type.upper(),
            'filename': export.filename,
            'id_string': xform.id_string,
        }, audit, request)
    if request.GET.get('raw'):
        id_string = None

    default_storage = get_storage_class()()
    if not isinstance(default_storage, FileSystemStorage):
        return HttpResponseRedirect(default_storage.url(export.filepath))
    basename = os.path.splitext(export.filename)[0]
    response = response_with_mimetype_and_name(
        mime_type, name=basename, extension=ext,
        file_path=export.filepath, show_date=False)
    return response 
Example 14
Project: bioforum   Author: reBiocoder   File: storage.py    License: MIT License 5 votes vote down vote up
def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super().__init__(location, base_url, *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None 
Example 15
Project: bioforum   Author: reBiocoder   File: collectstatic.py    License: MIT License 5 votes vote down vote up
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage) 
Example 16
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def delete_file(self, request, **kwargs):
        """
        Delete a file from session\n
            Params:
                - filename: str
        """
        session_id = self.get_object().pk
        file_name = request.POST.get('filename')

        if not file_name:
            raise APIException('Provide a file name.')

        try:
            storage = FileSystemStorage(
                location=os.path.join(
                    settings.MEDIA_ROOT,
                    settings.FILEBROWSER_DOCUMENTS_DIRECTORY,
                    session_id))

            if storage.exists(file_name):
                storage.delete(file_name)
                file_tasks = Task.objects \
                    .filter(metadata__session_id=session_id) \
                    .filter(metadata__file_name=file_name)
                for file_task in file_tasks:
                    if file_task.metadata.get('file_name') == file_name:
                        purge_task(file_task.id)
                Document.objects \
                    .filter(upload_session_id=session_id, name=file_name) \
                    .delete()
                return Response('Deleted')
            raise APIException("File doesn't exist")

        except Exception as e:
            raise APIException(str(e))


# --------------------------------------------------------
# Project Clustering Views
# -------------------------------------------------------- 
Example 17
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: storage.py    License: MIT License 5 votes vote down vote up
def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super().__init__(location, base_url, *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None 
Example 18
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: collectstatic.py    License: MIT License 5 votes vote down vote up
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage) 
Example 19
Project: wagtail   Author: wagtail   File: dummy_external_storage.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        self.wrapped = FileSystemStorage(*args, **kwargs) 
Example 20
Project: openwisp-utils   Author: openwisp   File: staticfiles.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, app_names=None, *args, **kwargs):
        self.locations = []
        self.storages = collections.OrderedDict()
        for dependency in self.dependencies:
            module = importlib.import_module(dependency)
            path = f'{os.path.dirname(module.__file__)}/static'
            if os.path.isdir(path):
                self.locations.append(('', path))
        for prefix, root in self.locations:
            filesystem_storage = FileSystemStorage(location=root)
            filesystem_storage.prefix = prefix
            self.storages[root] = filesystem_storage 
Example 21
def __init__(self, apps, schema_editor):
        self.apps = apps
        self.schema_editor = schema_editor
        self.image_storage = FileSystemStorage()
        Election = self.get_model_class('elections', 'Election')
        self.election_cache = {
            e.slug: e for e in Election.objects.all()
        }
        self.uk_mapit_data = {} 
Example 22
Project: yournextrepresentative   Author: mysociety   File: popolo_extra.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def create_from_file(
            self, image_filename, ideal_relative_name, base_kwargs, extra_kwargs
    ):
        # Import the file to media root and create the ORM
        # objects.
        storage = FileSystemStorage()
        desired_storage_path = join('images', ideal_relative_name)
        with open(image_filename, 'rb') as f:
            storage_filename = storage.save(desired_storage_path, f)
        image = Image.objects.create(image=storage_filename, **base_kwargs)
        return ImageExtra.objects.create(base=image, **extra_kwargs) 
Example 23
def __init__(self, *args, **kwargs):
        super(Command, self).__init__(*args, **kwargs)
        self.image_storage = FileSystemStorage() 
Example 24
Project: django-s3file   Author: codingjoe   File: checks.py    License: MIT License 5 votes vote down vote up
def storage_check(app_configs, **kwargs):
    if isinstance(default_storage, FileSystemStorage):
        return [
            Error(
                'FileSystemStorage should not be used in a production environment.',
                hint='Please verify your DEFAULT_FILE_STORAGE setting.',
                id='s3file.E001',
            )
        ]
    return [] 
Example 25
Project: django-on-docker   Author: testdrivenio   File: views.py    License: MIT License 5 votes vote down vote up
def image_upload(request):
    if request.method == "POST" and request.FILES["image_file"]:
        image_file = request.FILES["image_file"]
        fs = FileSystemStorage()
        filename = fs.save(image_file.name, image_file)
        image_url = fs.url(filename)
        print(image_url)
        return render(request, "upload.html", {
            "image_url": image_url
        })
    return render(request, "upload.html") 
Example 26
Project: openhgsenti   Author: drexly   File: storage.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super(StaticFilesStorage, self).__init__(location, base_url,
                                                 *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None 
Example 27
Project: openhgsenti   Author: drexly   File: collectstatic.py    License: Apache License 2.0 5 votes vote down vote up
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage) 
Example 28
Project: c3nav   Author: c3nav   File: finders.py    License: Apache License 2.0 5 votes vote down vote up
def list(self, ignore_patterns):
        result = []
        for prefix, path in logo_paths.items():
            if not path:
                continue
            basedir, filename = os.path.split(path)
            storage = FileSystemStorage(location=basedir)
            storage.prefix = prefix
            result.append((filename, storage))
        if settings.FAVICON_PACKAGE and os.path.isdir(settings.FAVICON_PACKAGE):
            storage = FileSystemStorage(location=settings.FAVICON_PACKAGE)
            storage.prefix = 'favicon_package'
            result += [(filename, storage) for filename in favicon_package_files]
        return result 
Example 29
Project: python2017   Author: bpgc-cte   File: storage.py    License: MIT License 5 votes vote down vote up
def __init__(self, location=None, base_url=None, *args, **kwargs):
        if location is None:
            location = settings.STATIC_ROOT
        if base_url is None:
            base_url = settings.STATIC_URL
        check_settings(base_url)
        super(StaticFilesStorage, self).__init__(location, base_url,
                                                 *args, **kwargs)
        # FileSystemStorage fallbacks to MEDIA_ROOT when location
        # is empty, so we restore the empty value.
        if not location:
            self.base_location = None
            self.location = None 
Example 30
Project: python2017   Author: bpgc-cte   File: collectstatic.py    License: MIT License 5 votes vote down vote up
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage)