utils.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. """provide fake data obj"""
  2. from datetime import datetime, timedelta
  3. import itertools
  4. import random
  5. from faker import Faker
  6. from faker.providers import DynamicProvider
  7. from sqlalchemy.orm import Session
  8. from db.models.subjects import Subject
  9. from db.models.trains import Train
  10. from db.models.hand_peripherals import HandPeripheral
  11. from db.models.daily_stats import DailyStats
  12. from db.repository import subjects as db_rep_sub
  13. from schemas.subjects import SubjectCreate
  14. class FakerManager:
  15. """init fake obj"""
  16. def __init__(self, lang="zh-cn"):
  17. self.fake = Faker(lang)
  18. self.load_provider()
  19. def load_provider(self):
  20. self.fake.add_provider(self.get_gender_provider())
  21. self.fake.add_provider(self.get_parts_provider())
  22. self.fake.add_provider(self.get_train_rank_provider())
  23. @staticmethod
  24. def get_gender_provider():
  25. return DynamicProvider(provider_name="subject_gender",
  26. elements=["男", "女"])
  27. @staticmethod
  28. def get_parts_provider():
  29. parts_list = []
  30. for num in range(1, 5):
  31. parts_list.extend(
  32. list(itertools.combinations(["左手", "右手", "左腿", "右腿"], num)))
  33. parts_provider = DynamicProvider(provider_name="rehabilitation_parts",
  34. elements=parts_list)
  35. return parts_provider
  36. @staticmethod
  37. def get_train_rank_provider():
  38. return DynamicProvider(provider_name="train_rank",
  39. elements=["简单", "中等", "困难"])
  40. def get_random_position(subject):
  41. return random.choice(subject.rehabilitation_parts)
  42. def generate_delay_datetime(delay_years: int):
  43. today = datetime.today()
  44. delay_time = timedelta(days=365*delay_years)
  45. delay_datetime = today + delay_time
  46. return delay_datetime.strftime("%Y-%m-%d")
  47. def clear_db_table(db: Session):
  48. db.query(Subject).delete()
  49. db.query(Train).delete()
  50. db.query(HandPeripheral).delete()
  51. db.query(DailyStats).delete()
  52. db.commit()
  53. fake = FakerManager().fake