前言:
又到每日分享Python小技巧的时光了,今天给大家分享的是Python接口常用封装函数。相信对于封装,大家都不陌生吧,今天就
用四个小案例来给大家展示,废话不多说,直接上代码:
1.封装上传图片的函数
1
2
3
4
5
6
7
8
9
10
11
12
13
|
. def upload_image(pathName, pathRoute, pathType, keyName = None ): ''' :param pathName: 图片名称 :param pathRoute: 图片路径 :param pathType: 图片类型 :param keyName: 文件名称 :return: ''' file = open (pathRoute, 'rb' ) files = { keyName: (pathName, file , pathType) } return files |
2. 封装车牌号的函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
|
def chepaihao( len = '6' ): char0 = '京津沪渝冀豫云辽黑湘皖鲁新苏浙赣鄂桂甘晋蒙陕吉闽赣粤青藏川宁琼' char1 = 'ABCDEFGHJKLMNPQRSTUVWXYZ' # 车牌号中没有I和O,可自行百度 char2 = '1234567890ABCDEFGHJKLMNPQRSTUVWXYZ' char3 = '1234567890' len0 = len (char0) - 1 len1 = len (char1) - 1 len2 = len (char2) - 1 len3 = len (char3) - 1 # while True: code = '' index0 = random.randint( 1 ,len0) index1 = random.randint( 1 , len1) code + = char0[index0] code + = char1[index1] code + = ' ' for i in ran ## 标题ge(1, 5): index2 = random.randint( 1 , len2) code + = char2[index2] index3 = random.randint( 1 ,len3) code + = char3[index3] # test = re.match('^.\w.[A-Z]\d{4}$|^.\w.\d[A-Z]\d{3}$|^.\w.\d{2}[A-Z]\d{2}$|^.\w.\d{3}[A-Z]\d$|^.\w.\d{5}$',code) print (code) return code |
3. 封装生成UUid 函数
1
2
3
4
|
# 生成UUid def uuid_(): uid = uuid.uuid1() return uid. hex |
4. 封装连接数据库的函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
|
import pymysql # 获取连接方法 def get_db_conn(): conn = pymysql.connect(host = '地址' , port = 000 , # 端口号 user = 'name' , passwd = '23456' , db = '3454' , # 库名 cursorclass = pymysql.cursors.DictCursor) return conn # 封装数据库查询单条操作 def query_db(sql): conn = get_db_conn() cur = conn.cursor() cur.execute(sql) conn.commit() result = cur.fetchone() cur.close() conn.close() return result # 封装数据库查询所有操作 def query_all(sql): conn = get_db_conn() cur = conn.cursor() cur.execute(sql) conn.commit() result = cur.fetchall() cur.close() conn.close() return result # 封装更改数据库操作 def change_db(sql): conn = get_db_conn() cur = conn.cursor() try : cur.execute(sql) conn.commit() except Exception as e: conn.rollback() finally : cur.close() conn.close() # 封装数据库新增所有操作 def insert_into(sql): conn = get_db_conn() cur = conn.cursor() cur.execute(sql) conn.commit() result = cur.fetchall() conn.close() return result |
最后:
这几个都是比较常用的封装函数,大家可以收藏起来以备不时之需。今天的分享到这里就结束了,更多的内容需要关注才能及时
到此这篇关于分享四个python接口常用封装函数的文章就介绍到这了,更多相关python接口封装函数内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/xff123456_/article/details/124343883