zoukankan      html  css  js  c++  java
  • 模块相关

    加密:hashlib

      hashlib模块用于加密的相关操作,代替了md5模块和sha模块,主要提供SHA1,SHA224,SHA256,SHA384,SHA512,MD5算法

    import hashlib
    # ############   md5   ################
    hash = hashlib.md5()
    hash.update(bytes('123456', encoding='utf-8'))    #将字节用md5加密
    print(hash.hexdigest())         #得到加密后的密文
    print(hash.digest())
    
    # ############   sha1   ################
    hash = hashlib.sha1()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
    
    # ############   sha256   ################
    hash  = hashlib.sha256()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
    
    # ############   sha384   ################
    hash = hashlib.sha384()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
    
    # ############   sha512   ################
    hash = hashlib.sha256()
    hash.update(bytes('admin', encoding='utf-8'))
    print(hash.hexdigest())
    hashlib加密

      以上加密算法不可逆,但是可以通过撞库的方式反解,所以需要对加密算法自定义key再加密.

    # ############   md5(加盐)   ################
    SALT = b'159654'
    def md5(pwd):
        #实例化对象
        obj = hashlib.md5(SALT)
        #写入要加密的字节
        obj.update(pwd.encode('utf-8'))
        #获取密文
        return obj.hexdigest()
    user = input('请输入用户名:')
    pwd = input('请输入密码:')
    #此处测试,将用户名设置为admin,密码为123456,实际使用中一定不要用弱口令
    if user == 'admin' and md5(pwd) == 'd849b096e540f82f95556811f5743a74':  #此密文为123456加盐后的密文
        print('登录成功')
    else:
        print('登录失败')
    
    # ############   md5(加盐)   ################
    SALT = b'159654'
    hash = hashlib.md5(SALT)
    hash.update(bytes('123456', encoding='utf-8'))
    print(hash.hexdigest())
    加盐

      python内部还内置hmac模块.hmac模块内部会对我们创建的key和内容进行进一步的处理然后再加密.

    import hmac
    h = hmac.new(bytes('159654', encoding='utf-8'))
    h.update(bytes('123456', encoding='utf-8'))
    print(h.hexdigest())
    hmac

    日志:logging

      logging模块用于编写记录日志并且线程安全的模块

      单日志文件:

    import logging
    logging.basicConfig(filename='log.txt',
                        format='%(asctime)s - %(name)s - %(levelname)s - %(module)s:    %(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S %p',
                        level=10)
    logging.debug('debug')
    logging.info('info')
    logging.warning('warning')
    logging.error('error')
    logging.critical('critical')
    logging.log(10, 'log')
    单文件日志
    CRITICAL = 50
    FATAL = CRITICAL
    ERROR = 40
    WARNING = 30
    WARN = WARNING
    INFO = 20
    DEBUG = 10
    NOTSET = 0
    日志等级

      只有当前等级大于等于日志等级时,日志文件才会记录.

    上面的方法,只能将日志文件记录在单文件中,想要设置多个日志文件,logging.basicConfig无法完成,需要自定义文件和日志操作对象.

      多日志文件:

    #定义文件
    file_1 = logging.FileHandler('file_1.log', 'a', encoding='utf-8')
    fmt = logging.Formatter(fmt='%(asctime)s - %(name)s - %(levelname)s - %(module)s:   %(message)s')
    file_1.setFormatter(fmt)
    
    file_2 = logging.FileHandler('file_2.log', 'a', encoding='utf-8')
    fmt = logging.Formatter()
    file_2.setFormatter(fmt)
    #定义日志
    logger1 = logging.Logger('log1', level=logging.ERROR)
    logger1.addHandler(file_1)
    logger1.addFilter(file_2)
    #写日志
    logger1.critical('123456')
    多日志文件1
    #定义文件
    file_2_1 = logging.FileHandler('12_1.log', 'a')
    fmt = logging.Formatter()
    file_2_1.setFormatter(fmt)
    #定义日志
    logger2 = logging.Logger('s2', level=logging.INFO)
    logger2.addFilter(file_2_1)
    多日志文件2

      使用logger1写日志文件时,会将相应的内容写入file_1.log和file_2.log文件中

      使用logger2写日志文件时,会将相应的内容写入l2_1.log文件中

    约束

      通过主动抛异常约束,必须实现某功能

    class BaseMessage(object):
        def send(self, x1):
            '''
            必须继承BaseMessage,然后其中必须编写send方法,用于完成具体的功能
            '''
            raise NotImplementedError('send()必须被重新编写')
    class Email(BaseMessage):
        def send(self, x1):
            '''必须继承BaseMessage,然后其中编写send方法,用于完成具体的功能'''
            pass
    obj = Email()
    obj.send(1)
    主动抛异常约束

      如果派生类没有对基类方法进行重新编写,就会抛异常.  

      还可以通过抽象类和抽象方法进行约束

    from abc import ABCMeta,abstractmethod
    class Base(metaclass=ABCMeta):  #抽象类
        def f1(self):
            print(123)
    
        @abstractmethod
        def f2(self):               #抽象方法
            pass
    
    class Foo(Base):
        def f2(self):
            print(666)
    
    obj = Foo()
    obj.f2()
    通过抽象类抽象方法约束

    自定义异常:

    #自定义异常
    class MyException(Exception):
        def __init__(self, code, msg):
            self.code = code
            self.msg = msg
    try:
        raise MyException(1000, '操作异常')
    except KeyError as obj:
        print(obj, 1111)
    except MyException as obj:
        print(obj, 2222)
    except Exception as obj:
        print(obj, 3333)
    
    #自定义异常
    class MyException(Exception):
        def __init__(self, code, msg):
            self.code = code
            self.msg = msg
    try:
        raise MyException(1000, '操作异常')
    except MyException as obj:
        print(obj.code, obj.msg)
    自定义异常
  • 相关阅读:
    第五周作业
    关于结对编程的理解
    第四周作业
    总结
    总结
    总结
    总结
    总结
    判断树、判断表
    总结
  • 原文地址:https://www.cnblogs.com/Virous1887/p/9567187.html
Copyright © 2011-2022 走看看