python-10-包和模块的概念

本文详细介绍了Python中的高阶函数、函数嵌套、闭包概念,以及计算代码执行时间的方法。接着探讨了装饰器的使用,包括装饰器的定义、优化和常见应用场景。此外,还讲解了模块导入、日志、授权、时间和日期处理等模块的使用。最后,文章通过实例展示了hashlib和hmac模块在数据加密中的应用。
摘要由CSDN通过智能技术生成

目录

01-高阶函数

02-函数的嵌套

03-闭包的概念

04-计算一段代码的执行时间

05-优化计算时间的代码

06-装饰器的使用

Python 函数装饰器

07-装饰器详解

08-装饰器的使用

09-导入模块的语法

10-os模块介绍

11-sys模块

12-math模块

13-random模块

14-datetime模块

15-time模块

16-calendar模块

17-hashlib和hmac模块


01-高阶函数

# 1. 把一个函数当做另一个函数的返回值
def test():
    print('我是test函数')
    return 'hello'


def demo():
    print('我是demo函数')
    return test


def bar():
    print('我是bar函数')
    return test()


a = bar()
# a()  a是一个字符串,不是函数
print(a)

x = test()
print(x)

y = demo()  # y 是test函数
print(y)
z = y()
print(z)  # hello

# 2. 把一个函数当做另一个函数的参数.lambda表达式的使用
# sort  filter   map  reduce
# 3. 在函数内部再定义一个函数
# 1. 把一个函数当做另一个函数的返回值
# 2. 把一个函数当做另一个函数的参数.lambda表达式的使用
# sort  filter   map  reduce
# 3. 在函数内部再定义一个函数

02-函数的嵌套

def outer(x):
    m = 100  # 局部变量
    print('我是outer函数')

    def inner():  # inner函数是定义在outer函数内部的一个函数
        print('我是inner函数')

    if x > 18:
        inner()

    return 'hello'


# print(m)
# inner()
# outer(12)
outer(21)

03-闭包的概念

def outer():
    x = 10  # 在外部函数里定义了一个变量x,是一个局部变量

    def inner():
        # 在内部函数如何修改外部函数的局部变量
        nonlocal x  # 此时,这里的x不再是新增的变量,而是外部的局部变量x
        y = x + 1
        print('inner里的y = ', y)
        x = 20  # 不是修改外部的x变量,而是在inner函数内部又创建了一个新的变量x

    return inner

outer()#这个啥也没有
outer()()
print(outer())
print(outer()())
'''
-------
inner里的y =  11
<function outer.<locals>.inner at 0x03A20F18>
inner里的y =  11
None
'''

04-计算一段代码的执行时间

import time  # time模块可以获取当前的时间

# 代码运行之前,获取一下时间
start = time.time()  # time模块里的time方法,可以获取当前时间的时间戳
# 时间戳是从 1970-01-01 00:00:00 UTC 到现在的秒数
# 从 1970-01-01 00:00:00 UTC ~ 2020-2-21 02:11  UTC
print('start =', start)  # 1582251025.9522343

x = 0
for i in range(1, 100000000):
    x += i

print(x)
# 代码运行完成以后,再获取一下时间
end = time.time()

print('代码运行耗时{}秒'.format(end - start))

05-优化计算时间的代码

import time


def cal_time(fn):
    start = time.time()
    fn()
    end = time.time()
    print('代码运行耗时{}秒'.format(end - start))


def demo():
    x = 0
    for i in range(1, 100000000):
        x += i
    print(x)


def foo():
    print('hello')
    time.sleep(3)
    print('world')


cal_time(demo)
cal_time(foo)

06-装饰器的使用

import time


def cal_time(fn):
    print('我是外部函数,我被调用了!!!')
    print('fn = {}'.format(fn))

    def inner():
        start = time.time()
        fn()
        end = time.time()
        print('代码耗时', end - start)

    return inner


@cal_time  # 第一件事调用cal_time;第二件事把被装饰的函数传递给fn
def demo():
    x = 0
    for i in range(1, 100000000):
        x += i
    print(x)


# 第三件事:当再次调用demo函数时,才是的demo函数已经不再是上面的demo
print('装饰后的demo = {}'.format(demo))
demo()

Python 函数装饰器

分类 编程技术

装饰器(Decorators)是 Python 的一个重要部分。简单地说:他们是修改其他函数的功能的函数。他们有助于让我们的代码更简短,也更Pythonic(Python范儿)。大多数初学者不知道在哪儿使用它们,所以我将要分享下,哪些区域里装饰器可以让你的代码更简洁。 首先,让我们讨论下如何写你自己的装饰器。

这可能是最难掌握的概念之一。我们会每次只讨论一个步骤,这样你能完全理解它。

一切皆对象

首先我们来理解下 Python 中的函数:

def hi(name="yasoob"):
    return "hi " + name
 
print(hi())
# output: 'hi yasoob'
 
# 我们甚至可以将一个函数赋值给一个变量,比如
greet = hi
# 我们这里没有在使用小括号,因为我们并不是在调用hi函数
# 而是在将它放在greet变量里头。我们尝试运行下这个
 
print(greet())
# output: 'hi yasoob'
 
# 如果我们删掉旧的hi函数,看看会发生什么!
del hi
print(hi())
#outputs: NameError
 
print(greet())
#outputs: 'hi yasoob'

在函数中定义函数

刚才那些就是函数的基本知识了。我们来让你的知识更进一步。在 Python 中我们可以在一个函数中定义另一个函数:

def hi(name="yasoob"):
    print("now you are inside the hi() function")
 
    def greet():
        return "now you are in the greet() function"
 
    def welcome():
        return "now you are in the welcome() function"
 
    print(greet())
    print(welcome())
    print("now you are back in the hi() function")
 
hi()
#output:now you are inside the hi() function
#       now you are in the greet() function
#       now you are in the welcome() function
#       now you are back in the hi() function
 
# 上面展示了无论何时你调用hi(), greet()和welcome()将会同时被调用。
# 然后greet()和welcome()函数在hi()函数之外是不能访问的,比如:
 
greet()
#outputs: NameError: name 'greet' is not defined

现在我们知道了可以在函数中定义另外的函数。也就是说:我们可以创建嵌套的函数。现在你需要再多学一点,就是函数也能返回函数。

从函数中返回函数

其实并不需要在一个函数里去执行另一个函数,我们也可以将其作为输出返回出来:

def hi(name="yasoob"):
    def greet():
        return "now you are in the greet() function"
 
    def welcome():
        return "now you are in the welcome() function"
 
    if name == "yasoob":
        return greet
    else:
        return welcome
 
a = hi()
print(a)
#outputs: <function greet at 0x7f2143c01500>
 
#上面清晰地展示了`a`现在指向到hi()函数中的greet()函数
#现在试试这个
 
print(a())
#outputs: now you are in the greet() function

再次看看这个代码。在 if/else 语句中我们返回 greet 和 welcome,而不是 greet() 和 welcome()。为什么那样?这是因为当你把一对小括号放在后面,这个函数就会执行;然而如果你不放括号在它后面,那它可以被到处传递,并且可以赋值给别的变量而不去执行它。 你明白了吗?让我再稍微多解释点细节。

当我们写下 a = hi(),hi() 会被执行,而由于 name 参数默认是 yasoob,所以函数 greet 被返回了。如果我们把语句改为 a = hi(name = "ali"),那么 welcome 函数将被返回。我们还可以打印出 hi()(),这会输出 now you are in the greet() function

将函数作为参数传给另一个函数

def hi():
    return "hi yasoob!"
 
def doSomethingBeforeHi(func):
    print("I am doing some boring work before executing hi()")
    print(func())
 
doSomethingBeforeHi(hi)
#outputs:I am doing some boring work before executing hi()
#        hi yasoob!

现在你已经具备所有必需知识,来进一步学习装饰器真正是什么了。装饰器让你在一个函数的前后去执行代码。

你的第一个装饰器

在上一个例子里,其实我们已经创建了一个装饰器!现在我们修改下上一个装饰器,并编写一个稍微更有用点的程序:

def a_new_decorator(a_func):
 
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
 
        a_func()
 
        print("I am doing some boring work after executing a_func()")
 
    return wrapTheFunction
 
def a_function_requiring_decoration():
    print("I am the function which needs some decoration to remove my foul smell")
 
a_function_requiring_decoration()
#outputs: "I am the function which needs some decoration to remove my foul smell"
 
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)
#now a_function_requiring_decoration is wrapped by wrapTheFunction()
 
a_function_requiring_decoration()
#outputs:I am doing some boring work before executing a_func()
#        I am the function which needs some decoration to remove my foul smell
#        I am doing some boring work after executing a_func()

你看明白了吗?我们刚刚应用了之前学习到的原理。这正是 python 中装饰器做的事情!它们封装一个函数,并且用这样或者那样的方式来修改它的行为。现在你也许疑惑,我们在代码里并没有使用 @ 符号?那只是一个简短的方式来生成一个被装饰的函数。这里是我们如何使用 @ 来运行之前的代码:

@a_new_decorator
def a_function_requiring_decoration():
    """Hey you! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
a_function_requiring_decoration()
#outputs: I am doing some boring work before executing a_func()
#         I am the function which needs some decoration to remove my foul smell
#         I am doing some boring work after executing a_func()
 
#the @a_new_decorator is just a short way of saying:
a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration)

希望你现在对 Python 装饰器的工作原理有一个基本的理解。如果我们运行如下代码会存在一个问题:

print(a_function_requiring_decoration.__name__)
# Output: wrapTheFunction

这并不是我们想要的!Ouput输出应该是"a_function_requiring_decoration"。这里的函数被warpTheFunction替代了。它重写了我们函数的名字和注释文档(docstring)。幸运的是Python提供给我们一个简单的函数来解决这个问题,那就是functools.wraps。我们修改上一个例子来使用functools.wraps:

from functools import wraps
 
def a_new_decorator(a_func):
    @wraps(a_func)
    def wrapTheFunction():
        print("I am doing some boring work before executing a_func()")
        a_func()
        print("I am doing some boring work after executing a_func()")
    return wrapTheFunction
 
@a_new_decorator
def a_function_requiring_decoration():
    """Hey yo! Decorate me!"""
    print("I am the function which needs some decoration to "
          "remove my foul smell")
 
print(a_function_requiring_decoration.__name__)
# Output: a_function_requiring_decoration

现在好多了。我们接下来学习装饰器的一些常用场景。

蓝本规范:

from functools import wraps
def decorator_name(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        if not can_run:
            return "Function will not run"
        return f(*args, **kwargs)
    return decorated
 
@decorator_name
def func():
    return("Function is running")
 
can_run = True
print(func())
# Output: Function is running
 
can_run = False
print(func())
# Output: Function will not run

注意:@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等等的功能。这可以让我们在装饰器里面访问在装饰之前的函数的属性。


使用场景

现在我们来看一下装饰器在哪些地方特别耀眼,以及使用它可以让一些事情管理起来变得更简单。

授权(Authorization)

装饰器能有助于检查某个人是否被授权去使用一个web应用的端点(endpoint)。它们被大量使用于Flask和Django web框架中。这里是一个例子来使用基于装饰器的授权:

from functools import wraps
 
def requires_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        auth = request.authorization
        if not auth or not check_auth(auth.username, auth.password):
            authenticate()
        return f(*args, **kwargs)
    return decorated

日志(Logging)

日志是装饰器运用的另一个亮点。这是个例子:

from functools import wraps
 
def logit(func):
    @wraps(func)
    def with_logging(*args, **kwargs):
        print(func.__name__ + " was called")
        return func(*args, **kwargs)
    return with_logging
 
@logit
def addition_func(x):
   """Do some math."""
   return x + x
 
 
result = addition_func(4)
# Output: addition_func was called

我敢肯定你已经在思考装饰器的一个其他聪明用法了。


带参数的装饰器

来想想这个问题,难道@wraps不也是个装饰器吗?但是,它接收一个参数,就像任何普通的函数能做的那样。那么,为什么我们不也那样做呢? 这是因为,当你使用@my_decorator语法时,你是在应用一个以单个函数作为参数的一个包裹函数。记住,Python里每个东西都是一个对象,而且这包括函数!记住了这些,我们可以编写一下能返回一个包裹函数的函数。

在函数中嵌入装饰器

我们回到日志的例子,并创建一个包裹函数,能让我们指定一个用于输出的日志文件。

from functools import wraps
 
def logit(logfile='out.log'):
    def logging_decorator(func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile,并写入内容
            with open(logfile, 'a') as opened_file:
                # 现在将日志打到指定的logfile
                opened_file.write(log_string + '\n')
            return func(*args, **kwargs)
        return wrapped_function
    return logging_decorator
 
@logit()
def myfunc1():
    pass
 
myfunc1()
# Output: myfunc1 was called
# 现在一个叫做 out.log 的文件出现了,里面的内容就是上面的字符串
 
@logit(logfile='func2.log')
def myfunc2():
    pass
 
myfunc2()
# Output: myfunc2 was called
# 现在一个叫做 func2.log 的文件出现了,里面的内容就是上面的字符串

装饰器类

现在我们有了能用于正式环境的logit装饰器,但当我们的应用的某些部分还比较脆弱时,异常也许是需要更紧急关注的事情。比方说有时你只想打日志到一个文件。而有时你想把引起你注意的问题发送到一个email,同时也保留日志,留个记录。这是一个使用继承的场景,但目前为止我们只看到过用来构建装饰器的函数。

幸运的是,类也可以用来构建装饰器。那我们现在以一个类而不是一个函数的方式,来重新构建logit。

from functools import wraps
 
class logit(object):
    def __init__(self, logfile='out.log'):
        self.logfile = logfile
 
    def __call__(self, func):
        @wraps(func)
        def wrapped_function(*args, **kwargs):
            log_string = func.__name__ + " was called"
            print(log_string)
            # 打开logfile并写入
            with open(self.logfile, 'a') as opened_file:
                # 现在将日志打到指定的文件
                opened_file.write(log_string + '\n')
            # 现在,发送一个通知
            self.notify()
            return func(*args, **kwargs)
        return wrapped_function
 
    def notify(self):
        # logit只打日志,不做别的
        pass

这个实现有一个附加优势,在于比嵌套函数的方式更加整洁,而且包裹一个函数还是使用跟以前一样的语法:

@logit()
def myfunc1():
    pass

现在,我们给 logit 创建子类,来添加 email 的功能(虽然 email 这个话题不会在这里展开)。

class email_logit(logit):
    '''
    一个logit的实现版本,可以在函数调用时发送email给管理员
    '''
    def __init__(self, email='admin@myproject.com', *args, **kwargs):
        self.email = email
        super(email_logit, self).__init__(*args, **kwargs)
 
    def notify(self):
        # 发送一封email到self.email
        # 这里就不做实现了
        pass

简单实例::

class email_logit(logit):
    '''
    一个logit的实现版本,可以在函数调用时发送email给管理员
    '''
    def __init__(self, email='admin@myproject.com', *args, **kwargs):
        self.email = email
        super(email_logit, self).__init__(*args, **kwargs)
 
    def notify(self):
        # 发送一封email到self.email
        # 这里就不做实现了
        pass
import random
from cal_time import cal_time


def insert_sort_gap(li,gap):
    for i in range(gap,len(li)):
        tmp=li[i]
        j= i- gap
        while j>=0 and li[j] >tmp:
            li[j+gap] = li[j]
            j -=gap
        li[j+gap] = tmp
@cal_time
def shell_sort(li):
    d = len(li)//2
    while d>= 1 :
        insert_sort_gap(li,d)
        d//=2

# # li = list (range(1000))
# li = [6,5,6,8,3,9,3]
# import random
# random.shuffle(li)
li = [115,181,95,15,154,1748,13,54]
# print(li)

# shell_sort(li)
# print(li)
# li = [random.randint(0,1000) for i in range(100)]
li2 = [random.randint(0,10000) for i in range(10000)]

shell_sort(li2)
print(li2)

07-装饰器详解

import time


def cal_time(fn):
    print('我是外部函数,我被调用了!!!')
    print('fn = {}'.format(fn))

    def inner(x, *args, **kwargs):  # x = 100000000
        start = time.time()
        s = fn(x)
        end = time.time()
        # print('代码耗时', end - start)
        return s, end - start

    return inner


@cal_time
def demo(n):
    x = 0
    for i in range(1, n):
        x += i
    return x


m = demo(100000000, 'good', y='hello')
print('m的值是', m)

08-装饰器的使用

# 产品经理: 提需求 / 改需求.
# 如果超过22点不让玩儿游戏,如果不告诉时间,默认让玩儿游戏
# 开放封闭原则


def can_play(fn):
    def inner(x, y, *args, **kwargs):
        # print(args)
        # clock = kwargs['clock']
        clock = kwargs.get('clock', 23)
        if clock <= 22:
            fn(x, y)
        else:
            print('太晚了,赶紧睡')

    return inner


@can_play
def play_game(name, game):
    print('{}正在玩儿{}'.format(name, game))


play_game('张三', '王者荣耀', m='hello', n='good', clock=18)
play_game('李四', '吃鸡')

09-导入模块的语法

# 模块:在Python里一个py文件,就可以理解为以模块
# 不是所有的py文件都能作为一个模块来导入
# 如果想要让一个py文件能够被导入,模块名字必须要遵守命名规则
# Python为了方便我们开发,提供了很多内置模块


import time  # 1.使用 import 模块名直接导入一个模块
from random import randint  # 2. from 模块名 import 函数名,导入一个模块里的方法或者变量
from math import *  # 3. from 模块名 import * 导入这个模块里的"所有"方法和变量
import datetime as dt  # 4. 导入一个模块并给这个模块起一个别名
from copy import deepcopy as dp  # 5. from 模块名 import 函数名  as 别名

# 导入这个模块以后,就可以使用这个模块里的方法和变量
print(time.time())

randint(0, 2)  # 生成 [0,2]的随机整数

print(pi)

print(dt.MAXYEAR)

dp(['hello', 'good', [1, 2, 3], 'hi'])

10-os模块介绍

# os全称 OperationSystem操作系统
# os 模块里提供的方法就是用来调用操作系统里的方法
import os

# os.name ==> 获取操作系统的名字    windows系列 ==>nt / 非windows ==>posix
print(os.name)  # nt
print(os.sep)  # 路径的分隔符  windows \   非windows /

# os模块里的 path 经常会使用
# abspath ==> 获取文件的绝对路径
print(os.path.abspath('01-高阶函数.py'))

# isdir判断是否是文件夹
print(os.path.isdir('02-函数的嵌套.py'))  # False
print(os.path.isdir('xxx'))  # True

# isfile 判断是否是文件
print(os.path.isfile('03-闭包的概念.py'))  # True
print(os.path.isfile('xxx'))  # False

# exists 判断是否存在
print(os.path.exists('05-优化计算时间的代码.py'))  # True
print(os.path.exists('mmm.py'))  # False

file_name = '2020.2.21.demo.py'
# print(file_name.rpartition('.'))
print(os.path.splitext(file_name))

# os里其他方法的介绍
# os.getcwd()  # 获取当前的工作目录,即当前python脚本工作的目录
# os.chdir('test') # 改变当前脚本工作目录,相当于shell下的cd命令
# os.rename('毕业论文.txt','毕业论文-最终版.txt') # 文件重命名
# os.remove('毕业论文.txt') # 删除文件
# os.rmdir('demo')  # 删除空文件夹
# os.removedirs('demo') # 删除空文件夹
# os.mkdir('demo')  # 创建一个文件夹
# os.chdir('C:\\') # 切换工作目录
# os.listdir('C:\\') # 列出指定目录里的所有文件和文件夹
# os.name # nt->widonws posix->Linux/Unix或者MacOS
# os.environ # 获取到环境配置
# os.environ.get('PATH') # 获取指定的环境配置

11-sys模块

# sys 系统相关的功能
import sys

print('hello world')
print('呵呵呵呵')

# ['C:\\Users\\chris\\Desktop\\Python基础\\Day10-模块和包\\01-代码',
#  'C:\\Users\\chris\\Desktop\\Python基础\\Day10-模块和包\\01-代码',
#  'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\python37.zip',
#  'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\DLLs',
#  'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\lib',
#  'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37',
#  'C:\\Users\\chris\\AppData\\Roaming\\Python\\Python37\\site-packages',
#  'C:\\Users\\chris\\AppData\\Local\\Programs\\Python\\Python37\\lib\\site-packages']
print(sys.path)  # 结果是一个列表,表示查找模块的路径

# sys.stdin  # 可以像input一样,接收用户的输入。接收用户的输入,和 input 相关

# sys.stdout 和 sys.stderr 默认都是在控制台
# sys.stdout  # 修改sys.stdout 可以改变默认输出位置
# sys.stderr  # 修改sys.stderr 可以改变错误输出的默认位置

sys.exit(100)  # 程序退出,和内置函数exit功能一致

12-math模块

# 数学计算相关的模块
import math

# 2 ** 10   /  pow(2,10)   / math.pow(2,10)
print(math.factorial(6))
print(math.pow(2, 10))  # 1024  幂运算

print(math.floor(12.98))  # 12.向下取整
print(math.ceil(15.0001))  # 16.向上取整
# round()   内置函数,实现四舍五入到指定位数

print(math.sin(math.pi / 6))  # 弧度  π=180°
print(math.cos(math.pi / 3))
print(math.tan(math.pi / 2))

13-random模块

# random模块用来生成一个随机数
import random

# randint(a,b)  用来生成[a,b]的随机整数   等价于 randrange(a,b+1)
print(random.randint(2, 9))

# randrange(a,b) 用来生成 [a,b)的随机整数
print(random.randrange(2, 9))

# random() 用来生成 [0,1)的随机浮点数
print(random.random())

# choice 用来在可迭代对象里随机抽取一个数据
print(random.choice(['zhangsan', 'lisi', 'jack', 'jerry', 'henry', 'tony']))

# sample 用来在可迭代对象里随机抽取 n 个数据
print(random.sample(['zhangsan', 'lisi', 'jack', 'jerry', 'henry', 'tony'], 2))

14-datetime模块

import datetime as dt

# 以一个下划线 _ 开始  _x
# 以两个两个下划线 __ 开始  __x
# 以两个下划线开始,再以连个下划线结束 __x__

# 涉及到四个类 datetime/date/time/timedelta
print(dt.datetime.now())  # 获取当前的日期时间
print(dt.date(2020, 1, 1))  # 创建一个日期
print(dt.time(18, 23, 45))  # 创建一个时间
print(dt.datetime.now() + dt.timedelta(3))  # 计算三天以后的日期时间

# 内置类
# list  tuple  int  str

15-time模块

import time

print(time.time())  # 获取从 1970-01-01 00:00:00 UTC 到现在时间的秒数
print(time.strftime("%Y-%m-%d %H:%M:%S"))  # 按照指定格式输出时间
print(time.asctime())  # Mon Apr 15 20:03:23 2019
print(time.ctime())  # Mon Apr 15 20:03:23 2019

print('hello')
print(time.sleep(10))  # 让线程暂停10秒钟
print('world')

16-calendar模块

import calendar  # 日历模块

calendar.setfirstweekday(calendar.SUNDAY)  # 设置每周起始日期码。周一到周日分别对应 0 ~ 6
print(calendar.firstweekday())  # 返回当前每周起始日期的设置。默认情况下,首次载入calendar模块时返回0,即星期一。

c = calendar.calendar(2020)  # 生成2020年的日历,并且以周日为其实日期码
print(c)  # 打印2019年日历

print(calendar.isleap(1900))  # True.闰年返回True,否则返回False
count = calendar.leapdays(1996, 2010)  # 获取1996年到2010年一共有多少个闰年
print(count)
print(calendar.month(2200, 3))  # 打印2019年3月的日历
calendar  # 日历模块

17-hashlib和hmac模块

import hashlib
import hmac

# 这两个模块都是用来进行数据加密
# hashlib模块里主要支持两个算法  md5 和  sha 加密
# 加密方式: 单向加密:只有加密的过程,不能解密md5/sha   对称加密   非对称加密rsa

# 需要将要加密的内容转换成为二进制
x = hashlib.md5('y239ym23r9b!'.encode('utf8'))  # 生成一个md5对象
# x.update('y239ym23r9b!'.encode('utf8'))
print(x.hexdigest())  # 900150983cd24fb0d6963f7d28e17f72
# 'abc'  ==>  900150983cd24fb0d6963f7d28e17f72


h1 = hashlib.sha1('123456'.encode())
print(h1.hexdigest())  # 7c4a8d09ca3762af61e59520943dc26494f8941b
h2 = hashlib.sha224('123456'.encode())  # 224位  一个十六进制占4位
print(h2.hexdigest())  # f8cdb04495ded47615258f9dc6a3f4707fd2405434fefc3cbf4ef4e6
h3 = hashlib.sha256('123456'.encode())
print(h3.hexdigest())  # 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
h4 = hashlib.sha384('123456'.encode())
print(
    h4.hexdigest())  # 0a989ebc4a77b56a6e2bb7b19d995d185ce44090c13e2984b7ecc6d446d4b61ea9991b76a4c2f04b1b4d244841449454

# hmac 加密可以指定秘钥
h = hmac.new('h'.encode(), '你好'.encode())
result = h.hexdigest()
print(result)  # 获取加密后的结果
python3中digest()和hexdigest()区别
hashlib是涉及安全散列和消息摘要,提供多个不同的加密算法接口,如SHA1、SHA224、SHA256、SHA384、SHA512、MD5等。

其中

hash.digest() 
返回摘要,作为二进制数据字符串值

hash.hexdigest() 
返回摘要,作为十六进制数据字符串值

 


# 这两个模块都是用来进行数据加密
# hashlib模块里主要支持两个算法  md5 和  sha 加密
# 加密方式: 单向加密:只有加密的过程,不能解密md5/sha   对称加密   非对称加密rsa

归纳总结一下,以上的模块方法都得背下来,都是常用的(加密模块了解)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

老板来片烤面包

君子博学于文,赠之以礼,谢君~

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值