| 1 |
import os |
| 2 |
|
| 3 |
from django.core.files.storage import FileSystemStorage |
| 4 |
|
| 5 |
from django_pgschemas.routing.info import DomainInfo |
| 6 |
from django_pgschemas.schema import get_current_schema |
| 7 |
from django_pgschemas.settings import get_pathname_function |
| 8 |
|
| 9 |
|
| 10 |
class TenantFileSystemStorage(FileSystemStorage): |
| 11 |
""" |
| 12 |
Tenant aware file system storage. Appends the tenant identifier to the base |
| 13 |
location and base URL. |
| 14 |
""" |
| 15 |
|
| 16 |
def get_schema_path_identifier(self) -> str: |
| 17 |
schema = get_current_schema() |
| 18 |
|
| 19 |
if schema is None: |
| 20 |
return "" |
| 21 |
|
| 22 |
path_identifier = schema.schema_name |
| 23 |
|
| 24 |
if hasattr(schema, "schema_pathname"): |
| 25 |
path_identifier = schema.schema_pathname() |
| 26 |
|
| 27 |
elif pathname_function := get_pathname_function(): |
| 28 |
path_identifier = pathname_function(schema) |
| 29 |
|
| 30 |
return path_identifier |
| 31 |
|
| 32 |
@property # To avoid caching of tenant |
| 33 |
def base_location(self) -> str: |
| 34 |
""" |
| 35 |
Appends base location with the schema path identifier. |
| 36 |
""" |
| 37 |
file_folder = self.get_schema_path_identifier() |
| 38 |
location = os.path.join(super().base_location, file_folder) |
| 39 |
|
| 40 |
if not location.endswith("/"): |
| 41 |
location += "/" |
| 42 |
|
| 43 |
return location |
| 44 |
|
| 45 |
@property # To avoid caching of tenant |
| 46 |
def location(self) -> str: |
| 47 |
return super().location |
| 48 |
|
| 49 |
@property # To avoid caching of tenant |
| 50 |
def base_url(self) -> str: |
| 51 |
""" |
| 52 |
Optionally appends base URL with the schema path identifier. |
| 53 |
If the current schema is already using a folder, no path identifier is |
| 54 |
appended. |
| 55 |
""" |
| 56 |
schema = get_current_schema() |
| 57 |
url_folder = self.get_schema_path_identifier() |
| 58 |
|
| 59 |
# Specific case of domain+folder routing |
| 60 |
if ( |
| 61 |
url_folder |
| 62 |
and schema |
| 63 |
and isinstance(schema.routing, DomainInfo) |
| 64 |
and schema.routing.folder |
| 65 |
): |
| 66 |
# Since we're already prepending all URLs with schema, there is no |
| 67 |
# need to make the differentiation here |
| 68 |
url_folder = "" |
| 69 |
|
| 70 |
parent_base_url = super().base_url.strip("/") |
| 71 |
url = "/".join(["", parent_base_url, url_folder]) |
| 72 |
|
| 73 |
if not url.endswith("/"): |
| 74 |
url += "/" |
| 75 |
|
| 76 |
return url |