zoukankan      html  css  js  c++  java
  • 模块 -- 序列化 hashlib sha logging (加密 加盐 )

    模块:  一个py文件就是一个模块

    模块分类:

        1:内置模块,登录模块,时间模块,sys模块,os模块等等

        2: 扩展模块,

        3:自定义模块,自己写的py文件

    python 开发效率之高:python的模块非常多, 第三方库

    序列化模块

    序列化:创造一个序列  ------>特殊处理(序列化)的字符串

    序列化又分为3个

      1,

      json适用于不同语言之间的 ,,  它有四个功能: dumps,loads,dump,load, 四个功能成对存在

    json: 数据通过网络发送给别人   写入文件也用到 json 

    被 json序列化的字符串:

      ①可以直接通过网络互相传输

      ②可以在各个语言中通用

      

    import json
    dic = {'alex':['123','321','阿达']}
    print(str(dic))                   #  基础数据类型  str 里面如果有引导就是单引号
    ret = json.dumps(dic)       #换成了双引号     json的str类型  特殊的
    print(ret,type(ret))
    import json 
    li = ['张三','王五','老土']
    f = open('haha',encoding = 'utf-8',mode = 'w')
    json.dump(li,f)          ##将序列化的字符串存储到文件中,  写进文件后是 bytes类型
    f.close
    import json
    li = ['老二','老三','老四']
    f = open('xixi',encoding = 'utf-8')
    ret = json.load(f)                     #    读出了内容
    print(ret)
    f.close()
    import json             (把多个序列化的字符串写入到同一个文件中)
    dic = {"alex":('women','women','老女人')}
    dic2 = {"alex1":('women','women','老女人')}
    dic3 = {"alex2":('women','women','老女人')}
    
    with open('json_files',encoding = 'utf-8',mode = 'a') as f1:
        s1 = json.dumps(dic,ensure_ascii = False)    #后面的ensure 是需要加的 
        f1.write(s1+'
    ')
        s2 = json.dumps(dic2,ensure_ascii = False)
        f1.write(s2+'
    ')
        s3 =json.dumps(dic3,ensure_ascii = False)
        f1.write(s3 +'
    ')
    把上面的三个字典 加入到一个文件里面
    
    with open('json_files',encoding = 'utf-8') as f2:
         for line in f2:
                dic = json.loads(line)
                print(dic,type(dic))        ##把里面的内容打印出来, 并判断类型

      

    import json
    data = {'username':['李华','二愣子'],'sex':'male','age':16}
    json_dic2 = json.dumps(data,sort_keys=True,indent=2,separators=(',',':'),ensure_ascii=False)
    print(json_dic2)
    得到结果: ##sort_keys 排序 indent:缩进 , separators以什么分开,键值对以什么分开
    {
      "age":16,
      "sex":"male",
      "username":[
        "李华",
        "二愣子"
      ]
    }
    Serialize obj to a JSON formatted str.(字符串表示的json对象) 
    Skipkeys:默认值是False,如果dict的keys内的数据不是python的基本类型(str,unicode,int,long,float,bool,None),设置为False时,就会报TypeError的错误。此时设置成True,则会跳过这类key 
    ensure_ascii:,当它为True的时候,所有非ASCII码字符显示为uXXXX序列,只需在dump时将ensure_ascii设置为False即可,此时存入json的中文即可正常显示。) 
    If check_circular is false, then the circular reference check for container types will be skipped and a circular reference will result in an OverflowError (or worse). 
    If allow_nan is false, then it will be a ValueError to serialize out of range float values (nan, inf, -inf) in strict compliance of the JSON specification, instead of using the JavaScript equivalents (NaN, Infinity, -Infinity). 
    indent:应该是一个非负的整型,如果是0就是顶格分行显示,如果为空就是一行最紧凑显示,否则会换行且按照indent的数值显示前面的空白分行显示,这样打印出来的json数据也叫pretty-printed json 
    separators:分隔符,实际上是(item_separator, dict_separator)的一个元组,默认的就是(‘,’,’:’);这表示dictionary内keys之间用“,”隔开,而KEY和value之间用“:”隔开。
    default(obj) is a function that should return a serializable version of obj or raise TypeError. The default simply raises TypeError. 
    sort_keys:将数据根据keys的值进行排序。 
    To use a custom JSONEncoder subclass (e.g. one that overrides the .default() method to serialize additional types), specify it with the cls kwarg; otherwise JSONEncoder is used.

      2, 

      pickle  只用于python语言之间的,  可支持python所有的数据类型

      缺点: 只能在Python语言中进行数据传输.

      序列化模块,python语言网络交互使用的,他支持所有的python数据类型 

      也是有四个方法 和json一样:

      dumps,loads,         用于网络传输,多个数据读写一个文件

        import pickle

        dic1 = {'name':'alex'}

        s1 = pickle.dumps(dic1)     序列化过程

        dic = pickle.loads(s1)         反序列化过程

      

      dump,load              文件操作,(单个数据读写一个文件)

      多个数据读写一个文件的应用:

        代码 02 序列化模块.py中

          循环,try....

    import pickle
    
    dic = {"alex": ('women','women','老女人')}
    dic2 = {"alex1": ('women','women','老女人')}
    dic3 = {"alex2": ('women','women','老女人')}
    
    with open('pickle_files',mode = 'wb') as f1:
            pickle.dump(dic,f1)
            pickle.dump(dic2,f1)
            pickle.dump(dic3,f1)
    
    把上面字典加入到了文件夹里, 反正是看不懂的那种
    
    
    with open('pickle_files',mode = 'rb') as f2:
            while True:
                    try:
                        print(pickle.load(f2))
                    except EOFError:
                        break
    把里面的东西打印出来,  本来是一个一个往外打,这样写, 假如里面有3个  打印第4个不会报错,break结束

     

      

      3,

      shelve   只是python  小工具(文件方面)        可以了解一下

    import shelve
    f = shelve.open('shelve_file')
    f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
    f.close()
    
    
    import shelve
    f1 = shelve.open('shelve_file')
    existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
    f1.close()
    print(existing)

     hashlib模块 

       1,是一对算法的合集,它包含很多算法,(加密的)

        2,hashlib的过程就是将字符串转化成数字的过程

        3,hashlib 对相同的字符串转化成的数字相同

        4,不同的电脑对相同的字符串进行加密,转换成的数字相同.

    那么用在哪里呢????

             密文(密码)

        将密码用算法加密放置到数据库,每次取出验证

             文件校验.

    初识   hashlib

           ①  md5  加密算法     常用算法,可以满足一般的常用需求

           ②   sha   加密算法    级别高一些, 数字越大级别越高,加密的效率越低,越安全

    md5:

    s1 = '12345325'
    ret = hashlib.md5()               # 创建一个md5对象
    ret.update(s1.encode('utf-8'))      #调用此update方法对参数进行加密    是byte类型
    print(ret.hexdigest())            #得到加密后的结果,   定长(长度都一样)
    
    s2 = 'alex12fdsl,.afjsdl;fjksdal;fkdsal;fld;lsdkflas;dkfsda;3'
    ret = hashlib.md5()    #创建一个md5对象
    ret.update(s2.encode('utf-8'))  #调用此update方法对参数进行加密     byte类型
    print(ret.hexdigest())            #得到加密后的结果     定长

     无论字符串多长,返回都是定长的数字

    同一字符串,md5值相同

    但是呢,总有一些闲人去试你的密码,  也叫撞库,因为撞库,所以相对不安全,如何解决呢?

    需要加盐

    s3 = '123456'
    ret = hashlib.md5('@$1*(^&@^2wqe'.encode('utf-8'))  #创建一个md5对象,加盐
    ret.update(s3.encode('utf-8'))  #调用此update方法对参数进行加密   byte类型
    print(ret.hexdigest())      #得到加密后的结果.    定长
    
    如果黑客盗取到你的固定盐'@$1*(^&@^2wqe'内容
    那就变成随机的盐:
    
    username = '爽妹'
    password = '123456'
    
    ret = hashlib.md5(username[::1].encode('utf-8'))
    ret.update(password.encode('utf-8'))
    print(ret.hexdigest())

    sha 系列

    hashlib.shal()             #shal与md5 级别相同 但是shal比md5 更安全一些

    ret = hashlib.shal()

    ret.update('123456'.encode('utf-8'))

    print(ret.hexdigest())                  #7c4a8d09ca3762af61e59520943dc26494f8941b

    ret = hashlib.sha512()         # 级别最高  效率低,安全性最大

    ret.update('123456'.encode'utf-8')

    print(ret.hexdigest())            ##得到的结果很长很长

    文件校验

    对于小文件可以,但是超大的文件内存受不了,

    def func(file_name):
         with open(file_name,mode = 'rb') as f1:
                 ret = hashlib.md5()
                 ret.update(f1.read())
                 return ret.hexdigest()
    
    print(func('hashlib_file'))
    print(func('hashlib_file1'))
    
    s1 = 'I am 旭哥, 都别惹我.... 不服你试试'
    ret = hashlib.md5()
    ret.update(s1.encode('utf-8'))
    print(ret.hexdigest())  # 15f614e4f03312320cc5cf83c8b2706f
    
    
    
    s1 = 'I am 旭哥, 都别惹我.... 不服你试试'
    ret = hashlib.md5()
    ret.update('I am'.encode('utf-8'))
    ret.update(' 旭哥, '.encode('utf-8'))
    ret.update('都别惹我....'.encode('utf-8'))
    ret.update(' 不服你试试'.encode('utf-8'))
    print(ret.hexdigest())  # 15f614e4f03312320cc5cf83c8b2706f
    
    
    
    def func(file_name):
        with open(file_name,mode='rb') as f1:
            ret = hashlib.md5()
            while True:
                content = f1.read(1024)
                if content:
                    ret.update(content)
                else:
                    break
            return ret.hexdigest()
    print(func('hashlib_file'))
    print(func('hashlib_file1'))

    hashlib 用在密文,或者文件的校验

    md5:   普通的,加盐的,动态加盐的

    sha:     普通的,加盐的,动态加盐的

    文件的校验: 小文件,大文件

    configparser  模块

    帮助你操作(创建,增,删,改,查)一个配置文件
     创建一个文件.
     import configparser
    
     config = configparser.ConfigParser()#
     config["DEFAULT"] = {'ServerAliveInterval': '45',
                           'Compression': 'yes',
                          'CompressionLevel': '9',
                          'ForwardX11':'yes'
                          }
    config['bitbucket.org'] = {'User':'hg'}
    
    config['topsecret.server.com'] = {'Host Port':'50022','ForwardX11':'no'}
    
    
    
    # 顺序:创建一个对象,然后将文件读到内存中,在进行相应的操作.
    #
    # print(config.sections())        #   ['bitbucket.org', 'topsecret.server.com']
    # # #为什么没有 DEFAULT,它是特殊的,可以看做成一个全局的.
    # print('111' in config) # False
    # print('bitbucket.org' in config) # True
    # 判断节名是否在配置文件中 上面的方法
    
    # 对配置文件中的节对应的项 取值
    # print(config['bitbucket.org']["user"])  # hg
    #
    # print(config['DEFAULT']['Compression']) #yes
    #
    # print(config['topsecret.server.com']['ForwardX11'])  #no
    #
    #
    # print(config['bitbucket.org'])          #<Section: bitbucket.org> 可迭代对象
    # print(config['bitbucket.org']['forwardx11'])          #<Section: bitbucket.org> 可迭代对象
    #
    # for key in config['bitbucket.org']:     # 注意,有default会默认default的键
    #     print(key)
    # #
    # print(config.options('bitbucket.org'))  # 同for循环,找到'bitbucket.org'下所有键
    #
    # print(config.items('bitbucket.org'))    #找到'bitbucket.org'下所有键值对
    #
    # print(config.get('bitbucket.org','compression')) # yes       get方法Section下的key对应的value
    
    # 增删改
    # import configparser
    #
    # config = configparser.ConfigParser()
    # # config.read('new2.ini')
    # # config.add_section('日天')
    # config.remove_section('bitbucket.org')
    # config.remove_option('topsecret.server.com',"forwardx11")
    #
    #
    # config.set('topsecret.server.com','k1','11111')
    # config.set('yuan','k2','22222')
    #
    # config.write(open('new2.ini', "w")

       

    logging    模块 

    log 日志:
    什么时候用到日志?
    生活中:
    1, 公司员工信息工号等等需要日志.
    2, 淘宝,京东 你的消费信息,浏览记录等等都记录日志中,个性化推荐.
    3, 头条个性化设置(爱好记录的日志中).

    工作上:
    运维人员,任何员工对服务器做过的任何操作,都会记录到日志中.
    如果你要是从事运维开发的工作,各处都需要日志.
    debug模式,需要依靠日志的.
    定时收集信息,也要记录日志.

    logging 模块是辅助你记录日志的,不是自动记录日志的.
    低配版,logging
    高配版,logger 对象

    低配版::
    import logging
    等级是一层一层升高的.
    logging.basicConfig(level=logging.ERROR)
    # level=logging.DEBUG 设置显示报错的级别.
    logging.debug('debug message')   # 调试信息
    logging.info('info message')    # 正常信息
    logging.warning('warning message')  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
    logging.error('error message')  # 错误信息.
    logging.critical('critical message') # 严重错误信息.
    
    用法实例:
    try:
        num = input('>>>请输入')
        num = int(num)
    except ValueError:
        logging.error('出现了 %s' % ValueError)
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s',
                        )
    # level=logging.DEBUG 设置显示报错的级别.
    logging.debug('debug message')   # 调试信息
    logging.info('info message')    # 正常信息
    logging.warning('warning message')  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
    logging.error('error message')  # 错误信息.
    logging.critical('critical message') # 严重错误信息.
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(filename)s (line:%(lineno)d) %(levelname)s %(message)s',
                        # datefmt='%a, %d %b %Y %H:%M:%S',  # 设置时间格式
                        filename='low_logging.log',
                        # filemode='w',
                        )
    logging.warning('warning 警告错误!!!!')  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
    logging.error('error message')  # 错误信息.
    logging.critical('critical message') # 严重错误信息.
    level=logging.DEBUG 设置显示报错的级别.
    try:
        num = input('>>>请输入')
        num = int(num)
    except Exception as e:
        logging.warning(e)  # 警告信息:代码虽然不报错,但是警告你写的不规范,必须改.
        logging.error(e)  # 错误信息.
        logging.critical(e) # 严重错误信息.
    low logging 缺点:
    # 1,写入文件 打印日志不能同时进行.
    # 2 ,写入文件时文件编码方式为gbk..

          

  • 相关阅读:
    div+css与table布局
    自动刷新网页效果
    Spring框架之Filter应用,filter可以使用spring注入资源
    http://localhost:8080/hohode
    java jacob 操作word 文档,进行写操作,如生成表格,添加 图片(这个不错,可以拿来直接用,非常好)
    java 填充word中的表格
    360抢票
    easyui 时间段校验,开始时间小于结束时间,并且时间间隔不能超过30天
    java操作word示例
    FastStone Capture 注册码 序列号
  • 原文地址:https://www.cnblogs.com/liuafan/p/9270408.html
Copyright © 2011-2022 走看看