db.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import csv
  2. import os
  3. from config import DATABASE_FIELDNAMES, REFERRAL_DATABASE_FILE_PATH
  4. from log import logger
  5. def validate_data(data, item=''):
  6. write_data = {}
  7. for i in data:
  8. j = item + i
  9. if isinstance(data[i], str):
  10. write_data[j] = data[i]
  11. elif isinstance(data[i], bool):
  12. write_data[j] = str(data[i])
  13. elif isinstance(data[i], dict):
  14. k = validate_data(data[i], item=j+'_')
  15. for b in k: write_data[b] = k[b]
  16. else:
  17. logger.error(f'code: 38aSUwmk; {type(d)}')
  18. return write_data
  19. def create_db(_file=REFERRAL_DATABASE_FILE_PATH):
  20. with open(_file, 'w', newline='') as f:
  21. writer = csv.writer(f)
  22. writer.writerow(DATABASE_FIELDNAMES)
  23. def create_row(data, _file=REFERRAL_DATABASE_FILE_PATH):
  24. data = validate_data(data)
  25. write_data = [ str(data[fieldname]) for fieldname in DATABASE_FIELDNAMES]
  26. with open(_file, 'a', newline='') as f:
  27. writer = csv.writer(f)
  28. writer.writerow(write_data)
  29. return {
  30. 'row': data
  31. }
  32. def read_all(_file=REFERRAL_DATABASE_FILE_PATH):
  33. with open(_file, 'r', newline='') as f:
  34. reader = csv.reader(f)
  35. data = [ i for i in reader ]
  36. return {
  37. 'rows': data
  38. }
  39. def read(column, row, _file=REFERRAL_DATABASE_FILE_PATH):
  40. with open(_file, 'r', newline='') as f:
  41. reader = csv.reader(f)
  42. data = [ dict(zip(DATABASE_FIELDNAMES, i)) for i in reader ]
  43. return data[row][column]
  44. def update(_file=REFERRAL_DATABASE_FILE_PATH):
  45. pass
  46. def delete(_file=REFERRAL_DATABASE_FILE_PATH):
  47. pass
  48. def init(_file=REFERRAL_DATABASE_FILE_PATH):
  49. if os.path.exists(_file):
  50. data = read_all(_file)
  51. if not data['rows']:
  52. create_db(_file)
  53. logger.info(f'create new database: {_file}')
  54. else:
  55. create_db(_file)