short_url_service.py 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637
  1. import string
  2. import random
  3. from sqlalchemy.orm import Session
  4. from app.models.short_url import ShortUrl
  5. class ShortUrlService:
  6. @staticmethod
  7. def generate_short_key(length: int = 8) -> str:
  8. """生成随机短 Key(由字母+数字组成)"""
  9. chars = string.ascii_letters + string.digits
  10. return ''.join(random.choices(chars, k=length))
  11. @staticmethod
  12. def create_short_url(db: Session, long_url: str) -> ShortUrl:
  13. """创建短链接"""
  14. # 检查是否已经存在相同的长链接
  15. existing = db.query(ShortUrl).filter(ShortUrl.long_url == long_url).first()
  16. if existing:
  17. return existing
  18. # 生成唯一 short_key
  19. short_key = ShortUrlService.generate_short_key()
  20. while db.query(ShortUrl).filter(ShortUrl.short_key == short_key).first():
  21. short_key = ShortUrlService.generate_short_key()
  22. db_obj = ShortUrl(short_key=short_key, long_url=long_url)
  23. db.add(db_obj)
  24. db.commit()
  25. db.refresh(db_obj)
  26. return db_obj
  27. @staticmethod
  28. def get_long_url(db: Session, short_key: str) -> str:
  29. """通过短 key 获取原始长链接"""
  30. record = db.query(ShortUrl).filter(ShortUrl.short_key == short_key).first()
  31. return record.long_url if record else ""