File size: 782 Bytes
0a1b571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from pathlib import Path
from tempfile import mkdtemp, mkstemp
from threading import Lock
from urllib.parse import ParseResult

from fastapi import Request


class TempFile:
    path = Path(mkdtemp())
    path_depth = 3
    name_length = 16

    _lock = Lock()

    @classmethod
    def create(cls, ext: str = ".tmp"):
        descriptor, str_path = mkstemp(suffix=ext, dir=str(cls.path))
        return descriptor, Path(str_path)

    @classmethod
    def to_url(cls, request: Request, path: Path) -> str:
        assert cls.path
        return ParseResult(
            scheme=request.url.scheme,
            netloc=request.url.netloc,
            path=f"/temp/{path.relative_to(cls.path)}",
            params="",
            query="",
            fragment="",
        ).geturl()