upload_util.py 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. import os
  2. import random
  3. from datetime import datetime
  4. from fastapi import UploadFile
  5. from core.settings import upload_settings
  6. class UploadUtil:
  7. """
  8. 上传工具类
  9. """
  10. @classmethod
  11. def generate_random_number(cls):
  12. """
  13. 生成3位数字构成的字符串
  14. :return: 3位数字构成的字符串
  15. """
  16. random_number = random.randint(1, 999)
  17. return f'{random_number:03}'
  18. @classmethod
  19. def check_file_exists(cls, filepath: str):
  20. """
  21. 检查文件是否存在
  22. :param filepath: 文件路径
  23. :return: 校验结果
  24. """
  25. return os.path.exists(filepath)
  26. @classmethod
  27. def check_file_extension(cls, file: UploadFile):
  28. """
  29. 检查文件后缀是否合法
  30. :param file: 文件对象
  31. :return: 校验结果
  32. """
  33. file_extension = file.filename.rsplit('.', 1)[-1]
  34. if file_extension in upload_settings.DEFAULT_ALLOWED_EXTENSION:
  35. return True
  36. return False
  37. @classmethod
  38. def check_file_timestamp(cls, filename: str):
  39. """
  40. 校验文件时间戳是否合法
  41. :param filename: 文件名称
  42. :return: 校验结果
  43. """
  44. timestamp = filename.rsplit('.', 1)[0].split('_')[-1].split(upload_settings.upload_machine)[0]
  45. try:
  46. datetime.strptime(timestamp, '%Y%m%d%H%M%S')
  47. return True
  48. except ValueError:
  49. return False
  50. @classmethod
  51. def check_file_machine(cls, filename: str):
  52. """
  53. 校验文件机器码是否合法
  54. :param filename: 文件名称
  55. :return: 校验结果
  56. """
  57. if filename.rsplit('.', 1)[0][-4] == upload_settings.upload_machine:
  58. return True
  59. return False
  60. @classmethod
  61. def check_file_random_code(cls, filename: str):
  62. """
  63. 校验文件随机码是否合法
  64. :param filename: 文件名称
  65. :return: 校验结果
  66. """
  67. valid_code_list = [f'{i:03}' for i in range(1, 999)]
  68. if filename.rsplit('.', 1)[0][-3:] in valid_code_list:
  69. return True
  70. return False
  71. @classmethod
  72. def generate_file(cls, filepath: str):
  73. """
  74. 根据文件生成二进制数据
  75. :param filepath: 文件路径
  76. :yield: 二进制数据
  77. """
  78. with open(filepath, 'rb') as response_file:
  79. yield from response_file
  80. @classmethod
  81. def delete_file(cls, filepath: str):
  82. """
  83. 根据文件路径删除对应文件
  84. :param filepath: 文件路径
  85. """
  86. os.remove(filepath)