前言:
又到每日分享Python小技巧的时光了,今天给大家分享的是Python接口常用封装函数。相信对于封装,大家都不陌生吧,今天就
用四个小案例来给大家展示,废话不多说, 直接上代码:
1.封装上传图片的函数
.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'): ? ? 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
最后:
这几个都是比较常用的封装函数,大家可以收藏起来以备不时之需。今天的分享到这里就结束了,更多的内容需要关注才能及时
到此这篇关于分享四个python接口常用封装函数的文章就介绍到这了,更多相关python接口封装函数内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
查看更多关于分享四个python接口常用封装函数的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did17943