database.py 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. """Database module"""
  2. from datetime import datetime, timedelta
  3. from app import SESSION
  4. from app.models import State, Region, StateRegion
  5. def get_current_regions(state_id):
  6. """Get latest professor from database"""
  7. session = SESSION()
  8. current_regions = session.query(Region) \
  9. .join(Region.state_regions) \
  10. .filter(StateRegion.state_id == state_id) \
  11. .filter(StateRegion.until_date_time == None) \
  12. .all()
  13. session.close()
  14. return current_regions
  15. def save_regions(state_id, regions):
  16. """Save residents to database"""
  17. session = SESSION()
  18. region_ids = []
  19. state = session.query(State).get(state_id)
  20. if state is None:
  21. state = save_state(session, state_id)
  22. for region_dict in regions:
  23. region = session.query(Region).get(region_dict['id'])
  24. if region is None:
  25. region = save_region(session, region_dict)
  26. region_ids.append(region.id)
  27. state_region = session.query(StateRegion) \
  28. .filter(StateRegion.state_id == state.id) \
  29. .filter(StateRegion.region_id == region.id) \
  30. .filter(StateRegion.until_date_time == None) \
  31. .first()
  32. if not state_region:
  33. state_region = StateRegion()
  34. state_region.state_id = state.id
  35. state_region.region_id = region.id
  36. state_region.from_date_time = datetime.now().replace(second=0, minute=0)
  37. session.add(state_region)
  38. session.commit()
  39. saved_state_regions = session.query(StateRegion) \
  40. .filter(StateRegion.state_id == state.id) \
  41. .filter(StateRegion.until_date_time == None) \
  42. .all()
  43. for saved_state_region in saved_state_regions:
  44. if saved_state_region.region_id not in region_ids:
  45. saved_state_region.until_date_time = datetime.now().replace(second=0, minute=0)
  46. session.commit()
  47. session.close()
  48. def save_state(session, state_id):
  49. """Save state to database"""
  50. state = State()
  51. state.id = state_id
  52. state.name = 'UNKNOWN'
  53. session.add(state)
  54. session.commit()
  55. return state
  56. def save_region(session, region_dict):
  57. """Save region to database"""
  58. region = Region()
  59. region.id = region_dict['id']
  60. region.name = region_dict['name']
  61. session.add(region)
  62. session.commit()
  63. return region