Python 常用工具类
'''
文 件 : util.py
说 明 : 常用工具
作 者 : 李光强
时 间 : 2022/4/2/
'''
import os
import re
import sys
import json
import uuid
import random
import hashlib
from datetime import datetime
class Util:
'''常用工具'''
def root_path(self):
'''
Get the physical path of the web root.
'''
# Infer the root path from the run file in the project root (e.g. manage.py)
fn = getattr(sys.modules['__main__'], '__file__')
root_path = os.path.abspath(os.path.dirname(fn))
return root_path
def to_float(self,s):
'''Convert the input string to a float'''
try:
return float(s);
except ValueError:
return False;
def to_int(self,s):
'''Convert the input string to a int'''
try:
return int(s);
except ValueError:
return False;
def to_date(self,s,fmt=None):
'''Convert the input string to a date
@参数 s : 输入日期字符串
@参数 fmt: 输入的日期字符串格式,如%Y-%m-%d
'''
if(not fmt):
fmt='%Y-%m-%d';
print("s=",s,",fmt=",fmt);
try:
return datetime.strptime(s,fmt);
except ValueError:
return False;
def list_json(self,list):
'''
Convert the list of objects to json string.
'''
s = '[';
for x in list:
if s=='[':
s = s+json.dumps(x.__dict__);
else:
s = s+','+json.dumps(x.__dict__);
s = s+"]";
return s;
def random(self,start,end):
'''生成在start~end之间的正整数随机数'''
r = random.random();
return int(start+(end-start)*r);
def dict_obj(self,d):
'''
Convert the dictionary to object.
'''
# checking whether object d is a
# instance of class list
if isinstance(d, list):
d = [self.dict_obj(x) for x in d]
# if d is not a instance of dict then
# directly object is returned
if not isinstance(d, dict):
return d
# declaring a class
class C:
pass
# constructor of the class passed to obj
obj = C()
for k in d:
obj.__dict__[k] = self.dict_obj(d[k])
return obj
def gbk_utf8(s):
'''GBK转让UTF8'''
n = s.decode('gbk');
return n.encode('utf8');
# Function to print sum
def dict_haskey(self, dict, key):
'''
检查dict里是否包括key
参数:
dict - 要查找的字典
key - 关键字
'''
if key in dict.keys():
return True;
else:
return False;
def var_type(self,var):
'''
获取变量类型
Arg:
var 变量
return:
string
str - 字符串
int - 整型
float - 浮点型
list
complex
tuple
dict
bool
bytes
bytearray
time.struct_time
datetime.datetime
'''
s=str(type(var));
# 取单引号里的字符串
pattern = re.compile("'(.*)'", re.S)
m = re.search(pattern,s);
return m.group(1).strip();
def guid(self):
'''create a guid'''
return uuid.uuid1();
def guid_withoutdash(self):
'''
create a guid without dash
'''
return self.myuuid_nodash();
def myuuid(self):
'''
create a uuid
'''
return uuid.uuid1();
def myuuid_nodash(self):
'''
create a uuid without dashes
'''
return str(uuid.uuid1()).replace('-','');
def md5(self,plain_text):
'''MD5加密'''
# 创建md5对象
hl = hashlib.md5()
# Tips
# 此处必须声明encode
# 若写法为hl.update(str) 报错为: Unicode-objects must be encoded before hashing
hl.update(plain_text.encode(encoding='utf-8'))
return hl.hexdigest();