string_util.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. # -*- coding: utf-8 -*-
  2. """
  3. @author: Allen
  4. @Created on: 2023/10/18
  5. @Remark:
  6. """
  7. import hashlib
  8. import random
  9. from decimal import Decimal
  10. CHAR_SET = ("2", "3", "4", "5",
  11. "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H",
  12. "J", "K", "L", "M", "N", "P", "Q", "R", "S", "T", "U", "V",
  13. "W", "X", "Y", "Z")
  14. def random_str(number=16):
  15. """
  16. 返回特定长度的随机字符串(非进制)
  17. :return:
  18. """
  19. result = ""
  20. for i in range(0, number):
  21. inx = random.randint(0, len(CHAR_SET) - 1)
  22. result += CHAR_SET[inx]
  23. return result
  24. def has_md5(str, salt='123456'):
  25. """
  26. md5 加密
  27. :param str:
  28. :param salt:
  29. :return:
  30. """
  31. # satl是盐值,默认是123456
  32. str = str + salt
  33. md = hashlib.md5() # 构造一个md5对象
  34. md.update(str.encode())
  35. res = md.hexdigest()
  36. return res
  37. def format_bytes(size, decimals=2):
  38. """
  39. 格式化字节大小
  40. :param size:
  41. :param decimals:
  42. :return:
  43. """
  44. if isinstance(size, (str)) and size.isnumeric():
  45. size = int(size)
  46. elif not isinstance(size, (int, float, Decimal)):
  47. return size
  48. if size == 0:
  49. return "0 Bytes"
  50. units = ["Bytes", "KB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB"]
  51. i = 0
  52. while size >= 1024:
  53. size /= 1024
  54. i += 1
  55. return f"{round(size, decimals)} {units[i]}"