utils.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. # Copyright: (c) OpenSpug Organization. https://github.com/openspug/spug
  2. # Copyright: (c) <spug.dev@gmail.com>
  3. # Released under the AGPL-3.0 License.
  4. from django.http.response import HttpResponse
  5. from django.db.models import QuerySet
  6. from datetime import datetime, date as datetime_date
  7. from decimal import Decimal
  8. import string
  9. import random
  10. import json
  11. # 转换时间格式到字符串
  12. def human_datetime(date=None):
  13. if date:
  14. assert isinstance(date, datetime)
  15. else:
  16. date = datetime.now()
  17. return date.strftime('%Y-%m-%d %H:%M:%S')
  18. # 转换时间格式到字符串(天)
  19. def human_date(date=None):
  20. if date:
  21. assert isinstance(date, datetime)
  22. else:
  23. date = datetime.now()
  24. return date.strftime('%Y-%m-%d')
  25. def human_time(date=None):
  26. if date:
  27. assert isinstance(date, datetime)
  28. else:
  29. date = datetime.now()
  30. return date.strftime('%H:%M:%S')
  31. # 解析时间类型的数据
  32. def parse_time(value):
  33. if isinstance(value, datetime):
  34. return value
  35. if isinstance(value, str):
  36. if len(value) == 10:
  37. return datetime.strptime(value, '%Y-%m-%d')
  38. elif len(value) == 19:
  39. return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
  40. raise TypeError('Expect a datetime.datetime value')
  41. # 传两个时间得到一个时间差
  42. def human_diff_time(time1, time2):
  43. time1 = parse_time(time1)
  44. time2 = parse_time(time2)
  45. delta = time1 - time2 if time1 > time2 else time2 - time1
  46. if delta.seconds < 60:
  47. text = '%d秒' % delta.seconds
  48. elif delta.seconds < 3600:
  49. text = '%d分' % (delta.seconds / 60)
  50. else:
  51. text = '%d小时' % (delta.seconds / 3600)
  52. return '%d天%s' % (delta.days, text) if delta.days else text
  53. def json_response(data='', error=''):
  54. content = AttrDict(data=data, error=error)
  55. if error:
  56. content.data = ''
  57. elif hasattr(data, 'to_dict'):
  58. content.data = data.to_dict()
  59. elif isinstance(data, (list, QuerySet)) and all([hasattr(item, 'to_dict') for item in data]):
  60. content.data = [item.to_dict() for item in data]
  61. return HttpResponse(json.dumps(content, cls=DateTimeEncoder), content_type='application/json')
  62. # 继承自dict,实现可以通过.来操作元素
  63. class AttrDict(dict):
  64. def __setattr__(self, key, value):
  65. self.__setitem__(key, value)
  66. def __getattr__(self, item):
  67. try:
  68. return self.__getitem__(item)
  69. except KeyError:
  70. raise AttributeError(item)
  71. def __delattr__(self, item):
  72. self.__delitem__(item)
  73. # 日期json序列化
  74. class DateTimeEncoder(json.JSONEncoder):
  75. def default(self, o):
  76. if isinstance(o, datetime):
  77. return o.strftime('%Y-%m-%d %H:%M:%S')
  78. elif isinstance(o, datetime_date):
  79. return o.strftime('%Y-%m-%d')
  80. elif isinstance(o, Decimal):
  81. return float(o)
  82. return json.JSONEncoder.default(self, o)
  83. # 生成指定长度的随机数
  84. def generate_random_str(length: int = 4, is_digits: bool = True) -> str:
  85. words = string.digits if is_digits else string.ascii_letters + string.digits
  86. return ''.join(random.sample(words, length))
  87. def get_request_real_ip(headers: dict):
  88. x_real_ip = headers.get('x-forwarded-for')
  89. if not x_real_ip:
  90. x_real_ip = headers.get('x-real-ip', '')
  91. return x_real_ip.split(',')[0]