当前位置: 首页>>代码示例>>Python>>正文


Python storage.FileSystemStorage方法代码示例

本文整理汇总了Python中django.core.files.storage.FileSystemStorage方法的典型用法代码示例。如果您正苦于以下问题:Python storage.FileSystemStorage方法的具体用法?Python storage.FileSystemStorage怎么用?Python storage.FileSystemStorage使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在django.core.files.storage的用法示例。


在下文中一共展示了storage.FileSystemStorage方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: image_upload

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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') 
开发者ID:testdrivenio,项目名称:django-docker-s3,代码行数:21,代码来源:views.py

示例2: image_upload

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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 
开发者ID:pytition,项目名称:Pytition,代码行数:21,代码来源:views.py

示例3: test_del_tmp_upload_file

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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.') 
开发者ID:ImperialCollegeLondon,项目名称:django-drf-filepond,代码行数:24,代码来源:test_signals.py

示例4: test_process_invalid_storage_location

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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.')) 
开发者ID:ImperialCollegeLondon,项目名称:django-drf-filepond,代码行数:20,代码来源:test_process_view.py

示例5: test_store_upload_with_storage_outside_BASE_DIR_without_enable

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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.')) 
开发者ID:ImperialCollegeLondon,项目名称:django-drf-filepond,代码行数:20,代码来源:test_process_view.py

示例6: test_store_upload_with_storage_outside_BASE_DIR_with_enable

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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.') 
开发者ID:ImperialCollegeLondon,项目名称:django-drf-filepond,代码行数:23,代码来源:test_process_view.py

示例7: enqueue_image

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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
    ) 
开发者ID:mysociety,项目名称:yournextrepresentative,代码行数:27,代码来源:ar_elections_2015_import_candidates.py

示例8: __init__

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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 
开发者ID:GibbsConsulting,项目名称:django-plotly-dash,代码行数:26,代码来源:finders.py

示例9: project_upload

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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}) 
开发者ID:Gerapy,项目名称:Gerapy,代码行数:19,代码来源:views.py

示例10: __init__

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:15,代码来源:storage.py

示例11: is_local_storage

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
def is_local_storage(self):
        return isinstance(self.storage, FileSystemStorage) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:4,代码来源:collectstatic.py

示例12: export_download

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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 
开发者ID:awemulya,项目名称:kobo-predict,代码行数:42,代码来源:views.py

示例13: __init__

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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 
开发者ID:reBiocoder,项目名称:bioforum,代码行数:14,代码来源:storage.py

示例14: delete_file

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
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
# -------------------------------------------------------- 
开发者ID:LexPredict,项目名称:lexpredict-contraxsuite,代码行数:42,代码来源:v1.py

示例15: __init__

# 需要导入模块: from django.core.files import storage [as 别名]
# 或者: from django.core.files.storage import FileSystemStorage [as 别名]
def __init__(self, *args, **kwargs):
        self.wrapped = FileSystemStorage(*args, **kwargs) 
开发者ID:wagtail,项目名称:wagtail,代码行数:4,代码来源:dummy_external_storage.py


注:本文中的django.core.files.storage.FileSystemStorage方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。