django-storages获取上传的网址

时间:2019-08-07 11:24:35

标签: django python-django-storages

我正在使用 Django 2.x 中的django-storages手动上传文件,而没有任何模型。

这是我使用Django REST Framework(DRF)的实现

class MediaListCreateView(generics.ListCreateAPIView):
    """
    List and create media
    """
    serializer_class = MediaSerializer
    parser_classes = [FileUploadParser]
    upload_path = 'uploads/media/'

    def post(self, request, *args, **kwargs):
        if 'file' not in request.data:
            raise ParseError('Empty content')

        file = request.data.get('file')

        file_ = default_storage.open('{}{}'.format(self.upload_path, file.name), 'w')
        file_.write(file.read())
        file_.close()

        return Response('Success', status=status.HTTP_200_OK)

文件保存在 S3存储桶中,但是现在我想在响应中返回上载文件的完整URL来代替Success

如何获取上传文件的完整URL?

settings

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    os.path.join(os.path.dirname(BASE_DIR), 'static_my_project')
]

STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'static_root')

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static_cdn', 'media_root')

STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage'

DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage'
AWS_STORAGE_BUCKET_NAME = os.environ.get('S3_STORAGE', 'my_bucket')
AWS_DEFAULT_ACL = 'public-read'

0 个答案:

没有答案