QRCode.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import qrcode
  2. from random import uniform
  3. from module.WorkWithDB import connect, list_ussued_passes
  4. from datetime import datetime
  5. from sqlalchemy import select
  6. def make(id_propusk: int, path_qr_image: str) -> str:
  7. number_pass = _random_number_pass()
  8. qr = qrcode.make(str(number_pass))
  9. qr.save(path_qr_image)
  10. _save_ussued_passed(id_propusk, number_pass)
  11. return path_qr_image
  12. def _random_number_pass() -> int:
  13. rand = int(uniform(0.0, 65534))
  14. if rand in _get_ussued_passes():
  15. return _random_number_pass()
  16. return rand
  17. def _get_ussued_passes() -> tuple[int]:
  18. with connect() as conn:
  19. result = conn.execute(
  20. select(
  21. list_ussued_passes.c.used_pass
  22. ).select_from(list_ussued_passes).where(
  23. list_ussued_passes.c.created > _get_now_day()
  24. )
  25. ).all()
  26. if result:
  27. return tuple(x.used_pass for x in result)
  28. else:
  29. return ()
  30. def _get_now_day() -> int:
  31. return datetime(
  32. year=datetime.now().year,
  33. month=datetime.now().month,
  34. day=datetime.now().day
  35. )
  36. def _save_ussued_passed(id_propusk: int, number_pass: int) -> bool:
  37. try:
  38. with connect() as conn:
  39. conn.execute(
  40. list_ussued_passes.insert.values(**{
  41. 'used_pass': number_pass,
  42. 'id_propusk': id_propusk
  43. })
  44. )
  45. return True
  46. except:
  47. return False