Django文件下载链接

Django文件下载链接生成,并设置下载有效期。

import os
from typing import Tuple, Union

from django.core import signing


class PathToUrl:
    EXPIRE = 8 * 60 * 60  # 8H
    SIGNER = signing.TimestampSigner()

    @classmethod
    def the_base_url(cls, frontend: str = "OP"):
        base_url = (
            "/operation-portal/media_backend" if frontend == "OP" else "/media_backend"
        )
        return base_url

    @classmethod
    def dump(
        cls, full_file_path: str, frontend: str = "OP"
    ) -> Tuple[Union[str, None], Union[str, None]]:
        if not full_file_path:
            return None, None
        base_url = cls.the_base_url(frontend=frontend)
        file_name = os.path.basename(full_file_path)
        data = {
            "path": full_file_path,
            "name": file_name,
        }
        secret = cls.SIGNER.sign_object(data)
        file_url = f"{base_url}/{secret}/{file_name}"
        return file_url, file_name

    @classmethod
    def load(cls, secret: str) -> Union[dict, None]:
        try:
            data = cls.SIGNER.unsign_object(secret, max_age=cls.EXPIRE)
        except signing.SignatureExpired:
            return None
        except Exception as e:
            return None
        return data

你可能感兴趣的:(Django,Django,文件下载)