python实用函数

拼接网址函数

url = 'http://localhost.com'
# 拼接网址函数
def makeurl(*res):
    lst_res = list(res)
    for i in range(0,len(lst_res)):
        res = lst_res[i]
        if res.endswith('/') or res.startswith('/'):
           lst_res[i] == res.strip('/')
           
    lst_res.insert(0,url)
    return '/'.join(lst_res)
url = makeurl('ceshi','logins')

请求重试装饰器

# 连接重试装饰器
def retry(exception=Timeout,max_times=3):
    def inner(func):
        def warp(*args,**kwargs):
            for try_time in range(max_times):
                try:
                    return func(*args,**kwargs)
                except exception as e:
                    if try_time == max_times -1:
                        raise e
                    time.sleep(3)
                    print('重试上一次请求')
                    continue
        return warp
    return inner

复制文件

# 复制文件
def copy_file(source_file, des_file):
    """复制文件"""
    from shutil import copyfile
    import sys
    try:
        copyfile(source_file, des_file)
    except IOError as e:
        print("Unable to copy file. %s" % e)
        raise e
    except Exception as e:
        print("Unexpected error:", sys.exc_info())
        raise e
copy_file(source_file, des_file)

创建文件夹

# 创建文件夹
def makedir(path):
    # 去除首尾空格
    path = path.strip()
    # 去除尾部 \ 符号
    path.rstrip('\\')
    if not os.path.exists(path):
        os.makedirs(path)
    return path

创建日志

import logging
import os.path
from logging.handlers import TimedRotatingFileHandler

path = r"C:\Users\24119\Desktop\test"


def mkdir(path):
    path = path.replace(" ", "")
    if not os.path.exists(path):
        os.makedirs(path)
    return path

# 日志文件生成准确定位错误
def config_log(basedir=None):
    if not basedir:
        basedir = os.path.abspath('')

    filename = os.path.join(basedir, 'info.log')

    log_file_handler = TimedRotatingFileHandler(filename=filename, encoding='utf-8', when="D", interval=2,
                                                backupCount=30)
    #  formatter,定义了最终log信息的顺序,结构和内容
    fmt = logging.Formatter(fmt='%(asctime)s %(levelname)-8s %(message)s', datefmt='%Y-%m-%d %H:%M:%S')
    log_file_handler.setFormatter(fmt)
    logging.basicConfig(level=logging.INFO, handlers=[log_file_handler])

log_dir = os.path.abspath("")
config_log(log_dir)
logging.warning("wqdwad")#警告
logging.info("123")#信息

url编码

import urllib.parse
encode = urllib.parse.quote("发动机")
print(encode)  #%E5%8F%91%E5%8A%A8%E6%9C%BA
decode = urllib.parse.unquote("%E5%8F%91%E5%8A%A8%E6%9C%BA")
print(decode)  #发动机
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值