Storage Module for Ellar
Project description
Introduction
The EllarStorage Module enriches your Ellar application with robust support for managing both cloud and
local file storage.
Leveraging the capabilities of the Apache libcloud
package
to simplify file storage operations within your Ellar-powered projects.
Installation
$(venv) pip install ellar-storage
This library drew inspiration from sqlalchemy-file.
Usage
To integrate EllarStorage into your project, follow the standard Ellar project structure and then configure the module as follows:
StorageModule
Similar to other Ellar modules, the StorageModule
can be configured directly where it's used or through the application configuration.
StorageModule.setup
You can set up the StorageModule
using the setup
method. Here's a quick example:
import os
from pathlib import Path
from ellar.common import Module
from ellar.core import ModuleBase
from ellar_storage import StorageModule, get_driver, Provider
BASE_DIRS = Path(__file__).parent
@Module(modules=[
StorageModule.setup(
files={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
},
images={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
},
documents={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
},
default="files"
)
])
class ApplicationModule(ModuleBase):
pass
In this example, after application initialization, folders for files
, images
, and documents
will be created in the specified directory. Each folder is configured to be managed by a local storage driver. You can explore other supported storage drivers.
StorageModule.register_setup
Alternatively, you can move the storage configuration to the application config:
## project_name/root_module.py
from ellar.common import Module
from ellar.core import ModuleBase
from ellar_storage import StorageModule
@Module(modules=[StorageModule.register_setup()])
class ApplicationModule(ModuleBase):
pass
Then, in config.py
, you can define the storage configurations:
import os
from pathlib import Path
from ellar.core.conf import ConfigDefaultTypesMixin
from ellar_storage import get_driver, Provider
BASE_DIRS = Path(__file__).parent
class DevelopmentConfig(ConfigDefaultTypesMixin):
DEBUG = True
STORAGE_CONFIG = dict(
storages=dict(
files={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
},
images={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
},
documents={
"driver": get_driver(Provider.LOCAL),
"options": {"key": os.path.join(BASE_DIRS, "media")},
}
),
default="files"
)
StorageService
At the end of the StorageModule
setup, StorageService
is registered into the Ellar DI system. Here's a quick example of how to use it:
## project_name/server.py
import os
from ellar.app import AppFactory
from ellar.common import datastructures, constants
from ellar.core import LazyModuleImport as lazyLoad
from ellar_storage import StorageService
application = AppFactory.create_from_app_module(
lazyLoad("project_name.root_module:ApplicationModule"),
config_module=os.environ.get(
constants.ELLAR_CONFIG_MODULE, "carapp.config:DevelopmentConfig"
),
)
storage_service: StorageService = application.injector.get(StorageService)
# Example: save a file in the 'files' folder
storage_service.save(
file=datastructures.ContentFile(b"We can now save files in the 'files' folder", name="file.txt"), upload_storage='files')
# Example: save a file in the 'images' folder
storage_service.save(
file=datastructures.ContentFile(b"We can now save files in the 'images' folder", name="image.txt"), upload_storage='images')
# Example: save a file in the 'documents' folder
storage_service.save(
file=datastructures.ContentFile(b"We can now save files in the 'documents' folder", name="docs.txt"), upload_storage='documents')
StorageService in Route Functions
You can inject StorageService
into your controllers or route functions. For instance:
In Controller:
from ellar.common import ControllerBase, Controller
from ellar_storage import StorageService
@Controller()
class FileManagerController(ControllerBase):
def __init__(self, storage_service: StorageService):
self._storage_service = storage_service
In Route Function:
from ellar.common import UploadFile, Inject, post
from ellar_storage import StorageService
@post('/upload')
def upload_file(self, file: UploadFile, storage_service: Inject[StorageService]):
pass
See Sample Project
API Reference
StorageService
- save(self, file: UploadFile, upload_storage: Optional[str] = None) -> StoredFile: Saves a file from an
UploadFile
object. - save_async(self, file: UploadFile, upload_storage: Optional[str] = None) -> StoredFile: Asynchronously saves a file from an
UploadFile
object. - save_content(self, **kwargs) -> StoredFile: Saves a file from content/bytes or through a file path.
- save_content_async(self, **kwargs) -> StoredFile: Asynchronously saves a file from content/bytes or through a file path.
- get(self, path: str) -> StoredFile: Retrieves a saved file if the specified
path
exists. Thepath
can be in the formatcontainer/filename.extension
orfilename.extension
. - get_async(self, path: str) -> StoredFile: Asynchronously retrieves a saved file if the specified
path
exists. - delete(self, path: str) -> bool: Deletes a saved file if the specified
path
exists. - delete_async(self, path: str) -> bool: Asynchronously deletes a saved file if the specified
path
exists. - get_container(self, name: Optional[str] = None) -> Container: Gets a
libcloud.storage.base.Container
instance for a configured storage setup.
StoredFile
StoredFile
is a file-like object returned from saving and retrieving files.
It extends some libcloud
Object methods and has a reference to the
libcloud
Object retrieved from the storage container.
Key attributes include:
- name: File name
- size: File size
- filename: File name
- content_type: File content type
- object:
libcloud
Object reference - read(self, n: int = -1, chunk_size: Optional[int] = None) -> bytes: Reads file content
- get_cdn_url(self) -> Optional[str]: Gets file CDN URL
- as_stream(self, chunk_size: Optional[int] = None) -> Iterator[bytes]: Creates a file stream
- delete(self) -> bool: Deletes the file from the container
License
Ellar is MIT licensed.
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
Built Distribution
Hashes for ellar_storage-0.1.1-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 64c0a93753ebb31b7f6fe0d44282c85e8889565aefaa9c86e58c847c0b2ae444 |
|
MD5 | 762d333be482b5a0760632a8f3cf9b22 |
|
BLAKE2b-256 | 760d9cd02156348996338832598cc15f1fb974cbd68a165043deeb115894aa30 |