spug/spug_api/libs/utils.py

102 lines
2.9 KiB
Python
Raw Normal View History

2019-11-08 08:53:16 +00:00
from django.http.response import HttpResponse
from django.db.models import QuerySet
from datetime import datetime, date as datetime_date
from decimal import Decimal
import string
import random
import json
# 转换时间格式到字符串
2019-12-19 15:49:40 +00:00
def human_datetime(date=None):
2019-11-08 08:53:16 +00:00
if date:
assert isinstance(date, datetime)
else:
date = datetime.now()
return date.strftime('%Y-%m-%d %H:%M:%S')
# 转换时间格式到字符串(天)
def human_date(date=None):
if date:
assert isinstance(date, datetime)
else:
date = datetime.now()
return date.strftime('%Y-%m-%d')
2019-12-19 16:17:23 +00:00
def human_time(date=None):
if date:
assert isinstance(date, datetime)
else:
date = datetime.now()
return date.strftime('%H:%M:%S')
2019-11-08 08:53:16 +00:00
# 解析时间类型的数据
def parse_time(value):
if isinstance(value, datetime):
return value
if isinstance(value, str):
if len(value) == 10:
return datetime.strptime(value, '%Y-%m-%d')
elif len(value) == 19:
return datetime.strptime(value, '%Y-%m-%d %H:%M:%S')
raise TypeError('Expect a datetime.datetime value')
# 传两个时间得到一个时间差
def human_diff_time(time1, time2):
time1 = parse_time(time1)
time2 = parse_time(time2)
delta = time1 - time2 if time1 > time2 else time2 - time1
if delta.seconds < 60:
text = '%d' % delta.seconds
elif delta.seconds < 3600:
text = '%d' % (delta.seconds / 60)
else:
text = '%d小时' % (delta.seconds / 3600)
return '%d%s' % (delta.days, text) if delta.days else text
def json_response(data='', error=''):
content = AttrDict(data=data, error=error)
if error:
content.data = ''
elif hasattr(data, 'to_dict'):
content.data = data.to_dict()
elif isinstance(data, (list, QuerySet)) and all([hasattr(item, 'to_dict') for item in data]):
content.data = [item.to_dict() for item in data]
return HttpResponse(json.dumps(content, cls=DateTimeEncoder), content_type='application/json')
# 继承自dict实现可以通过.来操作元素
class AttrDict(dict):
def __setattr__(self, key, value):
self.__setitem__(key, value)
def __getattr__(self, item):
return self.__getitem__(item)
def __delattr__(self, item):
self.__delitem__(item)
# 日期json序列化
class DateTimeEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, datetime):
return o.strftime('%Y-%m-%d %H:%M:%S')
elif isinstance(o, datetime_date):
return o.strftime('%Y-%m-%d')
elif isinstance(o, Decimal):
return float(o)
return json.JSONEncoder.default(self, o)
# 生成指定长度的随机数
def generate_random_str(length: int = 4, is_digits: bool = True) -> str:
words = string.digits if is_digits else string.ascii_letters + string.digits
return ''.join(random.sample(words, length))