Skip to main content

File storage backends for blueking PaaS platform

Project description

bkstorages

bkstorages 帮助你在蓝鲸 Django 应用中轻松使用 蓝鲸制品库S3 对象存储 以管理用户上传文件

安装

pip install bkstorages

运行环境要求:Python >= 3.11,Django >= 5.2

添加配置

安装好模块后,在你的 Django 配置文件中添加:

# RGW 相关配置,请修改为蓝鲸为你分配的相关信息
RGW_ACCESS_KEY_ID = ''
RGW_SECRET_ACCESS_KEY = ''
RGW_STORAGE_BUCKET_NAME = ''

# RGW 服务地址,请原样保留
RGW_ENDPOINT_URL = 'http://radosgw.example.com/'

如果要用蓝鲸对象存储服务来保存所有的用户上传文件,请在配置文件中添加:

STORAGES = {
    "default": {
        "BACKEND": "bkstorages.backends.rgw.RGWBoto3Storage",
    },
    "staticfiles": {
        "BACKEND": "django.contrib.staticfiles.storage.StaticFilesStorage",
    },
}

之后项目中所有的 FileFieldImageField 都会将用户文件上传至蓝鲸对象存储服务。

默认情况下,上传新文件会覆盖同名旧文件,你可以通过修改 RGW_FILE_OVERWRITE 配置项来关闭。

Django 4.2 起原先的 DEFAULT_FILE_STORAGE / STATICFILES_STORAGE 配置项已被新的 STORAGES 字典取代,并将在 Django 6.0 移除。本 SDK 仅给出新写法的示例。

关于 Django storage 的更多说明请参考: Django document: File Storage

将静态文件托管到蓝鲸对象存储服务

如果要使用蓝鲸对象存储服务托管静态文件,请将上一节的 STORAGES 中的 staticfiles 项改为 StaticRGWBoto3Storage

STORAGES = {
    "default": {
        "BACKEND": "bkstorages.backends.rgw.RGWBoto3Storage",
    },
    "staticfiles": {
        "BACKEND": "bkstorages.backends.rgw.StaticRGWBoto3Storage",
    },
}

之后每次执行 python manage.py collectstatic 时,django 会自动将所有文件上传到你配置的 bucket 中。

与 RGWBoto3Storage 不同,StaticRGWBoto3Storage 默认修改了以下几个配置:

  • 所有文件会被默认上传至 /static/ 目录下,可通过 RGW_STATIC_LOCATION 参数修改
  • 默认为文件添加以下头信息,可通过 RGW_STATIC_OBJECT_PARAMETERS 参数修改:
    • Cache-Control: max-age=86400

自定静态文件 storage

如果通过修改配置文件满足不了你的需求,你随时可以通过继承 RGWBoto3Storage 的方式来自定义你自己的 storage:

class MyStaticRGWBoto3Storage(RGWBoto3Storage):
    """My Storage class for storing static files
    """
    bucket_name = 'another_bucket'
    location = '/my_static_path'
    object_parameters = {
        # 配置:文件在这个时间后不再被缓存
        'Expires': 'Wed, 30 Nov 2016 04:12:29 GMT',
        # 配置:文件默认缓存时间为一天
        'CacheControl': 'max-age=86400'
    }

# 在 settings 的 STORAGES 中引用自定义类
STORAGES = {
    "default": {
        "BACKEND": "bkstorages.backends.rgw.RGWBoto3Storage",
    },
    "staticfiles": {
        "BACKEND": "custom_backend.MyStaticRGWBoto3Storage",
    },
}

如需使用更丰富的 object_parameters 配置参数,请访问 Boto3 相关文档 查阅相关文档。

修改模板中的静态文件地址

你需要同时修改模板文件中的静态文件地址,才能指向到蓝鲸对象存储服务上的文件。

Django 模板

{% load staticfiles %}
<script type="text/javascript" src="{{ static 'js/settings.js' }}"></script>

Mako 模板

<%!
    from django.templatetags.static import static
%>
<script type="text/javascript" src="${static('js/settings.js')}"></script>

手动使用 RGWBoto3Storage 上传和修改文件

除了将 RGWBoto3Storage 指定为文件存储后端外,你还可以通过 API 来手动使用它来管理文件。

初始化 storage 对象:

from bkstorages.backends.rgw import RGWBoto3Storage


storage = RGWBoto3Storage()

使用 storage 对象上传文件:

# 文件内容必须是字符串(bytes)而非文本(text)。为了兼容 Python2 与 Python3 版本,
# 建议使用 django 提供的工具函数先进行一次转换。
from django.utils.encoding import force_bytes
content = force_bytes('Hello, RGW!')

# 使用 ContentFile
f = ContentFile(content)
storage.save(u'/test/hello', f)

上传文件对象:

from tempfile import NamedTemporaryFile

from django.core.files import File
from django.utils.encoding import force_bytes


with NamedTemporaryFile() as fp:
    fp.write(force_bytes('Temp file'))
    fp.flush()

    f = File(fp)
    storage.save(u'/test/temp_file.txt', f)

查看文件链接:

storage.url('/test/temp_file.txt')

列出目录下所有文件:

storage.listdir('/test')

删除文件:

storage.delete('/test/temp_file.txt')

更多 API 说明请参考:File storage API - Django documentation

文档

  • 模块所有可配置项列表详见项目 Wiki

开发指南

首先安装 poetry ,之后在项目目录下执行 poetry env use python3.11 初始化开发用虚拟环境。然后用 poetry shell 命令激活虚拟环境。

  • 执行 poetry install 安装所有依赖
  • 使用 pytest -s . 执行所有单元测试

使用 nox 执行单元测试

为了测试包在不同 Python 版本下的稳定性,我们使用了 nox 工具。在项目目录下执行 nox 即可执行所有的单元测试。

发布包

首先,执行 poetry build 命令在 dist 目录下生成当前版本的包。然后执行 twine upload dist/* --repository-url {pypi_address} --username {your_name} --password {your_token} 将其上传到 pypi 服务器上。

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

bkstorages-3.1.0.tar.gz (20.4 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

bkstorages-3.1.0-py3-none-any.whl (22.8 kB view details)

Uploaded Python 3

File details

Details for the file bkstorages-3.1.0.tar.gz.

File metadata

  • Download URL: bkstorages-3.1.0.tar.gz
  • Upload date:
  • Size: 20.4 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for bkstorages-3.1.0.tar.gz
Algorithm Hash digest
SHA256 db9947bfb437c8778d149555c983c83f2dc7c8556a9ed14f1766d5d133e0be09
MD5 e09dc28f645f1a40742eedca19607f02
BLAKE2b-256 99ffbaf8da469bfff18757ad7455e748e2b00db0ee7ac283e1e80d80a151173e

See more details on using hashes here.

File details

Details for the file bkstorages-3.1.0-py3-none-any.whl.

File metadata

  • Download URL: bkstorages-3.1.0-py3-none-any.whl
  • Upload date:
  • Size: 22.8 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.2.0 CPython/3.12.13

File hashes

Hashes for bkstorages-3.1.0-py3-none-any.whl
Algorithm Hash digest
SHA256 846069d9ec427af5088b87ce67a365e9b81fe25a137171bb0918d88beee1c32f
MD5 5cee638d4f684465aa1692e890a3b536
BLAKE2b-256 8408ccf1685ae7bdad69c9ba576ccafde828b0b0a58bf0f6b97753fa955b39ca

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page