1 import base64, time, os, configparser, uuid, datetime
2 from hashlib import md5
3
4
5 def get_img_base64(path):
6 """
7 图片转base64
8 :param path: 图片路径
9 :return: str(base64)
10 """
11 with open(path, 'rb') as f:
12 str = base64.b64encode(f.read())
13 return str
14
15 def save_img(response, path):
16 """
17 将response的图片保存
18 :param response:
19 :param path: 图片路径
20 """
21 with open(path, 'wb') as f:
22 f.write(response.read())
23
24 def get_hash_md5(str, salt=''):
25 """
26 md5加密
27 :param str: 密码
28 :param salt: 加盐
29 :return: md5
30 """
31 if salt:
32 str = str + salt
33 hash_md5 = md5()
34 hash_md5.update(str.encode('utf-8'))
35 return hash_md5.hexdigest()
36
37 def get_time_stamp_s():
38 """
39 获取时间戳(秒)
40 :return: str(秒时间戳)
41 """
42 t = time.time() # int
43 return str(int(t))
44
45 def get_time_stamp_ms():
46 """
47 获取时间戳(毫秒)
48 :return: str(毫秒时间戳)
49 """
50 t = time.time()
51 nowTime = lambda:int(round(t * 1000)) # int
52 return str(nowTime())
53
54 def get_now():
55 """
56 获取当前时间
57 :return: yyyy-MM-dd HH:mm:ss.SSS
58 """
59 return datetime.datetime.now()
60
61 def read_config():
62 """
63 读取配置文件
64 :return:
65 """
66 dir_now = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
67 conf = configparser.ConfigParser()
68 conf.read(dir_now+'/config.ini')
69 return conf
70
71 def querySet_to_json(querySet):
72 """
73 querySet转json
74 :param querySet:
75 :return:
76 """
77 from django.core import serializers
78 return serializers.serialize('json',querySet)
79
80 def executeQuery(sql):
81 """
82 将sql转化为dict
83 :param sql:
84 :return:dict
85 """
86 from django.db import connection
87 cursor = connection.cursor() # 获得一个游标(cursor)对象
88 cursor.execute(sql)
89 rawData = cursor.fetchall()
90
91 col_names = [desc[0] for desc in cursor.description]
92
93 result = []
94 for row in rawData:
95 objDict = {}
96 # 把每一行的数据遍历出来放到Dict中
97 for index, value in enumerate(row):
98 objDict[col_names[index]] = value
99
100 result.append(objDict)
101
102 return result
103
104
105 def get_uuid():
106 """
107 获取uuid
108 :return:uuid
109 """
110 return str(uuid.uuid4()).replace('-', '')