又到每日分享Python小技巧的时光了,今天给大家分享的是Python接口常用封装函数。相信对于封装,大家都不陌生吧,今天就
用四个小案例来给大家展示,废话不多说,直接上代码。
1.封装上传图片的函数Python学习交流Q群:906715085####
.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. 封装车牌号的函数
def chepaihao(len='6'):
Python学习交流Q群:906715085###
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 函数
# 生成UUid
def uuid_():
uid = uuid.uuid1()
return uid.hex
4. 封装连接数据库的函数
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
最后
这几个都是比较常用的封装函数,大家可以收藏起来以备不时之需。今天的分享到这里就结束了,更多的内容需要关注才能及时
看到。喜欢的小伙伴记得点赞收藏。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)