ext.py 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. import hashlib
  2. import mimetypes
  3. import urllib.parse
  4. def is_pdf(filename, file):
  5. """
  6. 判断文件是否为PDF格式,支持中文名和特殊字符。
  7. :param filename: 文件名
  8. :param file: 文件对象
  9. :return: 如果文件是PDF格式,则返回True,否则返回False
  10. """
  11. try:
  12. # 对文件名进行URL解码,处理特殊字符
  13. decoded_filename = urllib.parse.unquote(filename)
  14. # 检查MIME类型
  15. mime_type, _ = mimetypes.guess_type(decoded_filename)
  16. print(f"Detected MIME type: {mime_type}")
  17. # 某些情况下mime_type可能为None,需要特殊处理
  18. if mime_type is None:
  19. # 只检查文件内容的PDF标识
  20. file_start = file.read(5)
  21. file.seek(0) # 重置文件指针
  22. return file_start.startswith(b'%PDF-')
  23. if mime_type != 'application/pdf':
  24. return False
  25. # 检查文件内容的PDF标识
  26. file_start = file.read(5)
  27. file.seek(0) # 重置文件指针
  28. if not file_start.startswith(b'%PDF-'):
  29. return False
  30. return True
  31. except Exception as e:
  32. print(f"Error checking PDF format: {str(e)}")
  33. # 发生错误时,仍然尝试通过文件头判断
  34. try:
  35. file_start = file.read(5)
  36. file.seek(0)
  37. return file_start.startswith(b'%PDF-')
  38. except:
  39. return False
  40. def url_is_pdf(file):
  41. """
  42. 判断文件是否为PDF格式。
  43. :param file: 文件对象
  44. :return: 如果文件是PDF格式,则返回True,否则返回False
  45. """
  46. # 检查文件内容
  47. file_start = file.read(5)
  48. file.seek(0)
  49. if not file_start.startswith(b'%PDF-'):
  50. return False
  51. return True
  52. def calculate_file_hash(file, algorithm='sha256'):
  53. """
  54. 计算给定文件的哈希值。
  55. :param file: 文件对象
  56. :param algorithm: 哈希算法的名字,如:'sha256', 'md5', 'sha1'等
  57. :return: 文件的哈希值
  58. """
  59. hash_func = getattr(hashlib, algorithm)()
  60. block_size = 65536 # 64KB chunks
  61. # with open(file_path, 'rb') as file:
  62. buffer = file.read(block_size)
  63. while len(buffer) > 0:
  64. hash_func.update(buffer)
  65. buffer = file.read(block_size)
  66. file.seek(0)
  67. return hash_func.hexdigest()
  68. def singleton_func(cls):
  69. instance = {}
  70. def _singleton(*args, **kwargs):
  71. if cls not in instance:
  72. instance[cls] = cls(*args, **kwargs)
  73. return instance[cls]
  74. return _singleton