| 12345678910111213141516171819202122232425262728293031323334353637383940 |
- import string
- import random
- from sqlalchemy.orm import Session
- from app.core.biz_exception import NotFoundError, PermissionDeniedError, BizLogicError
- from app.models.short_url import ShortUrl
- class ShortUrlService:
- @staticmethod
- def generate_short_key(length: int = 8) -> str:
- """生成随机短 Key(由字母+数字组成)"""
- chars = string.ascii_letters + string.digits
- return ''.join(random.choices(chars, k=length))
- @staticmethod
- def create_short_url(db: Session, long_url: str) -> ShortUrl:
- """创建短链接"""
- # 检查是否已经存在相同的长链接
- existing = db.query(ShortUrl).filter(ShortUrl.long_url == long_url).first()
- if existing:
- raise BizLogicError("Short url already exist")
- # 生成唯一 short_key
- short_key = ShortUrlService.generate_short_key()
- while db.query(ShortUrl).filter(ShortUrl.short_key == short_key).first():
- short_key = ShortUrlService.generate_short_key()
- db_obj = ShortUrl(short_key=short_key, long_url=long_url)
- db.add(db_obj)
- db.commit()
- db.refresh(db_obj)
- return db_obj
- @staticmethod
- def get_long_url(db: Session, short_key: str) -> str:
- """通过短 key 获取原始长链接"""
- record = db.query(ShortUrl).filter(ShortUrl.short_key == short_key).first()
- if not record:
- raise NotFoundError("Short url not found")
- return record.long_url
|