uuid7으로 필드 및 처리관련 수정
This commit is contained in:
1 parent
aa8d9d7c14
commit
32ae5530b6
26 files changed
+2346
-901
No files matched your search
+67
-20
@@ -4,24 +4,71 @@ Common Utility Functions
|
||||
공통으로 사용되는 유틸리티 함수들을 정의합니다.
|
||||
|
||||
사용 예시:
|
||||
from app.utils.common import generate_task_id, generate_ksuid
|
||||
from app.utils.common import generate_task_id, generate_uuid
|
||||
|
||||
# task_id 생성
|
||||
task_id = await generate_task_id(session=session, table_name=Project)
|
||||
|
||||
# ksuid 생성
|
||||
ksuid = await generate_ksuid(session=session, table_name=User)
|
||||
# uuid 생성
|
||||
user_uuid = await generate_uuid(session=session, table_name=User)
|
||||
|
||||
Note:
|
||||
페이지네이션 기능은 app.utils.pagination 모듈을 사용하세요:
|
||||
from app.utils.pagination import PaginatedResponse, get_paginated
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Optional, Type
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
from svix_ksuid import Ksuid
|
||||
|
||||
|
||||
def _generate_uuid7_string() -> str:
|
||||
"""UUID7 문자열을 생성합니다.
|
||||
|
||||
UUID7 구조 (RFC 9562):
|
||||
- 48 bits: Unix timestamp (밀리초)
|
||||
- 4 bits: 버전 (7)
|
||||
- 12 bits: 랜덤
|
||||
- 2 bits: variant (10)
|
||||
- 62 bits: 랜덤
|
||||
- 총 128 bits -> 36자 (하이픈 포함)
|
||||
|
||||
Returns:
|
||||
36자리 UUID7 문자열 (xxxxxxxx-xxxx-7xxx-yxxx-xxxxxxxxxxxx)
|
||||
"""
|
||||
# 현재 시간 (밀리초)
|
||||
timestamp_ms = int(time.time() * 1000)
|
||||
|
||||
# 랜덤 바이트 (10바이트 = 80비트)
|
||||
random_bytes = os.urandom(10)
|
||||
|
||||
# UUID7 바이트 구성 (16바이트 = 128비트)
|
||||
# 처음 6바이트: 타임스탬프 (48비트)
|
||||
uuid_bytes = timestamp_ms.to_bytes(6, byteorder="big")
|
||||
|
||||
# 다음 2바이트: 버전(7) + 랜덤 12비트
|
||||
# 0x7000 | (random 12 bits)
|
||||
rand_a = int.from_bytes(random_bytes[0:2], byteorder="big")
|
||||
version_rand = (0x7000 | (rand_a & 0x0FFF)).to_bytes(2, byteorder="big")
|
||||
uuid_bytes += version_rand
|
||||
|
||||
# 다음 2바이트: variant(10) + 랜덤 62비트의 앞 6비트
|
||||
# 0x80 | (random 6 bits) + random 8 bits
|
||||
rand_b = random_bytes[2]
|
||||
variant_rand = bytes([0x80 | (rand_b & 0x3F)]) + random_bytes[3:4]
|
||||
uuid_bytes += variant_rand
|
||||
|
||||
# 나머지 6바이트: 랜덤
|
||||
uuid_bytes += random_bytes[4:10]
|
||||
|
||||
# 16진수로 변환
|
||||
hex_str = uuid_bytes.hex()
|
||||
|
||||
# UUID 형식으로 포맷팅 (8-4-4-4-12)
|
||||
return f"{hex_str[:8]}-{hex_str[8:12]}-{hex_str[12:16]}-{hex_str[16:20]}-{hex_str[20:32]}"
|
||||
|
||||
|
||||
async def generate_task_id(
|
||||
@@ -35,16 +82,16 @@ async def generate_task_id(
|
||||
table_name: task_id 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
|
||||
Returns:
|
||||
str: 생성된 ksuid 문자열
|
||||
str: 생성된 UUID7 문자열 (36자)
|
||||
|
||||
Usage:
|
||||
# 단순 ksuid 생성
|
||||
# 단순 UUID7 생성
|
||||
task_id = await generate_task_id()
|
||||
|
||||
# 테이블에서 중복 검사 후 생성
|
||||
task_id = await generate_task_id(session=session, table_name=Project)
|
||||
"""
|
||||
task_id = str(Ksuid())
|
||||
task_id = _generate_uuid7_string()
|
||||
|
||||
if session is None or table_name is None:
|
||||
return task_id
|
||||
@@ -58,41 +105,41 @@ async def generate_task_id(
|
||||
if existing is None:
|
||||
return task_id
|
||||
|
||||
task_id = str(Ksuid())
|
||||
task_id = _generate_uuid7_string()
|
||||
|
||||
|
||||
async def generate_ksuid(
|
||||
async def generate_uuid(
|
||||
session: Optional[AsyncSession] = None,
|
||||
table_name: Optional[Type[Any]] = None,
|
||||
) -> str:
|
||||
"""고유한 ksuid를 생성합니다.
|
||||
"""고유한 UUID7을 생성합니다.
|
||||
|
||||
Args:
|
||||
session: SQLAlchemy AsyncSession (optional)
|
||||
table_name: user_ksuid 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
table_name: user_uuid 컬럼이 있는 SQLAlchemy 테이블 클래스 (optional)
|
||||
|
||||
Returns:
|
||||
str: 생성된 ksuid 문자열
|
||||
str: 생성된 UUID7 문자열 (36자)
|
||||
|
||||
Usage:
|
||||
# 단순 ksuid 생성
|
||||
ksuid = await generate_ksuid()
|
||||
# 단순 UUID7 생성
|
||||
new_uuid = await generate_uuid()
|
||||
|
||||
# 테이블에서 중복 검사 후 생성
|
||||
ksuid = await generate_ksuid(session=session, table_name=User)
|
||||
new_uuid = await generate_uuid(session=session, table_name=User)
|
||||
"""
|
||||
ksuid = str(Ksuid())
|
||||
new_uuid = _generate_uuid7_string()
|
||||
|
||||
if session is None or table_name is None:
|
||||
return ksuid
|
||||
return new_uuid
|
||||
|
||||
while True:
|
||||
result = await session.execute(
|
||||
select(table_name).where(table_name.user_ksuid == ksuid)
|
||||
select(table_name).where(table_name.user_uuid == new_uuid)
|
||||
)
|
||||
existing = result.scalar_one_or_none()
|
||||
|
||||
if existing is None:
|
||||
return ksuid
|
||||
return new_uuid
|
||||
|
||||
ksuid = str(Ksuid())
|
||||
new_uuid = _generate_uuid7_string()
|
||||
@@ -5,14 +5,14 @@ Azure Blob Storage에 파일을 업로드하는 클래스를 제공합니다.
|
||||
파일 경로 또는 바이트 데이터를 직접 업로드할 수 있습니다.
|
||||
|
||||
URL 경로 형식:
|
||||
- 음악: {BASE_URL}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{task_id}/image/{파일명}
|
||||
- 음악: {BASE_URL}/{user_uuid}/{task_id}/song/{파일명}
|
||||
- 영상: {BASE_URL}/{user_uuid}/{task_id}/video/{파일명}
|
||||
- 이미지: {BASE_URL}/{user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
사용 예시:
|
||||
from app.utils.upload_blob_as_request import AzureBlobUploader
|
||||
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
|
||||
# 파일 경로로 업로드
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
@@ -79,14 +79,15 @@ class AzureBlobUploader:
|
||||
"""Azure Blob Storage 업로드 클래스
|
||||
|
||||
Azure Blob Storage에 음악, 영상, 이미지 파일을 업로드합니다.
|
||||
URL 형식: {BASE_URL}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
URL 형식: {BASE_URL}/{user_uuid}/{task_id}/{category}/{file_name}?{SAS_TOKEN}
|
||||
|
||||
카테고리별 경로:
|
||||
- 음악: {task_id}/song/{file_name}
|
||||
- 영상: {task_id}/video/{file_name}
|
||||
- 이미지: {task_id}/image/{file_name}
|
||||
- 음악: {user_uuid}/{task_id}/song/{file_name}
|
||||
- 영상: {user_uuid}/{task_id}/video/{file_name}
|
||||
- 이미지: {user_uuid}/{task_id}/image/{file_name}
|
||||
|
||||
Attributes:
|
||||
user_uuid: 사용자 고유 식별자 (UUID)
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
|
||||
@@ -100,17 +101,24 @@ class AzureBlobUploader:
|
||||
".bmp": "image/bmp",
|
||||
}
|
||||
|
||||
def __init__(self, task_id: str):
|
||||
def __init__(self, user_uuid: str, task_id: str):
|
||||
"""AzureBlobUploader 초기화
|
||||
|
||||
Args:
|
||||
user_uuid: 사용자 고유 식별자 (UUID)
|
||||
task_id: 작업 고유 식별자
|
||||
"""
|
||||
self._user_uuid = user_uuid
|
||||
self._task_id = task_id
|
||||
self._base_url = azure_blob_settings.AZURE_BLOB_BASE_URL
|
||||
self._sas_token = azure_blob_settings.AZURE_BLOB_SAS_TOKEN
|
||||
self._last_public_url: str = ""
|
||||
|
||||
@property
|
||||
def user_uuid(self) -> str:
|
||||
"""사용자 고유 식별자 (UUID)"""
|
||||
return self._user_uuid
|
||||
|
||||
@property
|
||||
def task_id(self) -> str:
|
||||
"""작업 고유 식별자"""
|
||||
@@ -126,12 +134,12 @@ class AzureBlobUploader:
|
||||
# SAS 토큰 앞뒤의 ?, ', " 제거
|
||||
sas_token = self._sas_token.strip("?'\"")
|
||||
return (
|
||||
f"{self._base_url}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
f"{self._base_url}/{self._user_uuid}/{self._task_id}/{category}/{file_name}?{sas_token}"
|
||||
)
|
||||
|
||||
def _build_public_url(self, category: str, file_name: str) -> str:
|
||||
"""공개 URL 생성 (SAS 토큰 제외)"""
|
||||
return f"{self._base_url}/{self._task_id}/{category}/{file_name}"
|
||||
return f"{self._base_url}/{self._user_uuid}/{self._task_id}/{category}/{file_name}"
|
||||
|
||||
async def _upload_bytes(
|
||||
self,
|
||||
@@ -253,7 +261,7 @@ class AzureBlobUploader:
|
||||
async def upload_music(self, file_path: str) -> bool:
|
||||
"""음악 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -262,7 +270,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_music(file_path="my_song.mp3")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -279,7 +287,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""음악 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/song/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/song/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -289,7 +297,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_music_bytes(audio_bytes, "my_song")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -315,7 +323,7 @@ class AzureBlobUploader:
|
||||
async def upload_video(self, file_path: str) -> bool:
|
||||
"""영상 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -324,7 +332,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_video(file_path="my_video.mp4")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -341,7 +349,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""영상 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/video/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/video/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -351,7 +359,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_video_bytes(video_bytes, "my_video")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -377,7 +385,7 @@ class AzureBlobUploader:
|
||||
async def upload_image(self, file_path: str) -> bool:
|
||||
"""이미지 파일을 Azure Blob Storage에 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_path: 업로드할 파일 경로
|
||||
@@ -386,7 +394,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
success = await uploader.upload_image(file_path="my_image.png")
|
||||
print(uploader.public_url)
|
||||
"""
|
||||
@@ -406,7 +414,7 @@ class AzureBlobUploader:
|
||||
) -> bool:
|
||||
"""이미지 바이트 데이터를 Azure Blob Storage에 직접 업로드합니다.
|
||||
|
||||
URL 경로: {task_id}/image/{파일명}
|
||||
URL 경로: {user_uuid}/{task_id}/image/{파일명}
|
||||
|
||||
Args:
|
||||
file_content: 업로드할 파일 바이트 데이터
|
||||
@@ -416,7 +424,7 @@ class AzureBlobUploader:
|
||||
bool: 업로드 성공 여부
|
||||
|
||||
Example:
|
||||
uploader = AzureBlobUploader(task_id="task-123")
|
||||
uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
with open("my_image.png", "rb") as f:
|
||||
content = f.read()
|
||||
success = await uploader.upload_image_bytes(content, "my_image.png")
|
||||
@@ -445,17 +453,17 @@ class AzureBlobUploader:
|
||||
# import asyncio
|
||||
#
|
||||
# async def main():
|
||||
# uploader = AzureBlobUploader(task_id="task-123")
|
||||
# uploader = AzureBlobUploader(user_uuid="user-abc", task_id="task-123")
|
||||
#
|
||||
# # 음악 업로드 -> {BASE_URL}/task-123/song/my_song.mp3
|
||||
# # 음악 업로드 -> {BASE_URL}/user-abc/task-123/song/my_song.mp3
|
||||
# await uploader.upload_music("my_song.mp3")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 영상 업로드 -> {BASE_URL}/task-123/video/my_video.mp4
|
||||
# # 영상 업로드 -> {BASE_URL}/user-abc/task-123/video/my_video.mp4
|
||||
# await uploader.upload_video("my_video.mp4")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
# # 이미지 업로드 -> {BASE_URL}/task-123/image/my_image.png
|
||||
# # 이미지 업로드 -> {BASE_URL}/user-abc/task-123/image/my_image.png
|
||||
# await uploader.upload_image("my_image.png")
|
||||
# print(uploader.public_url)
|
||||
#
|
||||
|
||||
Reference in new issue
Block a user