常用函数与高阶函数
- python中的加密工具:hashlib—不可逆;base64—通用型,可解密
import hashlib,base64
import time
# hashlib不可逆的加密函数
# 基础签名
base_sign = 'like'
def custom():
# time.time() 时间戳是float型,要转换成int型
a_timestamp = int(time.time())
_token = '%s%s' % (base_sign,a_timestamp)
print(_token)
# 生成hash对象:传入的参数要求是比特类型的,需要编码
hashobj = hashlib.sha1(_token.encode('utf-8'))
# 生成16进制加密字符串
a_token = hashobj.hexdigest()
print(a_token)
return a_token,a_timestamp
# 服务端,需要传入两个参数
# 请求方服务的认证token,请求方生成token的时间戳
def b_service_check(token,timestamp):
_token = "%s%s" % (base_sign,timestamp)
b_token = hashlib.sha1(_token.encode('utf-8')).hexdigest()
if token == b_token:
return True
else:
return False
if __name__=='__main__':
c_token,timestamp = custom()
# result = b_service_check(c_token,timestamp)
time.sleep(1)
result = b_service_check(c_token, int(time.time()))
if result==True:
print('a服务合法,服务器B正常响应')
else:
print('a服务不合法,拒绝请求响应')

import base64
# base64通用加密函数
replace01 = '%'
replace02 = '$'
def encode(data):
if isinstance(data,str):
data = data.encode('utf-8') # 需要转换为比特类型
elif isinstance(data,bytes):
data = data
else:
raise TypeError('data need bytes or str')
re = base64.encodebytes(data) #对比特类型进行加密
re02 = re.decode('utf-8') # bytes类型转换为字符串类型
print(re02)
re03 = re02.replace('a',replace01).replace('w',replace02)
print(re03,type(re03))
return re03.encode('utf-8')
def decode(data):
if not isinstance(data,bytes):
raise TypeError('data need bytes')
# 需要替换的比特类型
replace02_b = replace02.encode('utf-8')
replace01_b = replace01.encode('utf-8')
print(replace01_b,replace02_b)
# 还原回原始的base64加密后数据,注意替换的字符必须比特类型
re = data.replace(replace01_b,b'a').replace(replace02_b,b'w')
print(re,type(re))
# # base64解密之后为比特型
re02 = base64.decodebytes(re)
print(re02,type(re02))
# 解密之后的数据进行解码为字符串
re03 = re02.decode('utf-8')
return re03
# return base64.decodebytes(re).decode('utf-8')
if __name__ == "__main__":
result = encode('hello~ 小云')
print(result)
# print(base64.decodebytes(result))
# print(base64.decodebytes(result).decode('utf-8'))
de_re = decode(result)
print(de_re)

- python中的日志模块logging
- 日志等级:debug info warnning error critical
- logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(filename)s [line:%(lineno)s] %(levelname)s %(message)s')
In [2]: import logging
In [3]: logging.basicConfig(level=logging.DEBUG,format='%(asctime)s %(f
...: ilename)s [line:%(lineno)s] %(levelname)s %(message)s')
In [4]: logging.info('你好,小牧')
2022-04-02 22:16:02,449 <ipython-input-4-a48175ba1273> [line:1] INFO 你,小牧
In [5]: logging.error('程序出错了')
2022-04-02 22:19:50,062 <ipython-input-5-e67376584deb> [line:1] ERROR 程序出错了
In [6]: logging.debug
Out[6]: <function logging.debug(msg, *args, **kwargs)>
In [7]: logging.warn
Out[7]: <function logging.warn(msg, *args, **kwargs)>
In [8]: logging.error('aaa')
2022-04-02 22:20:56,727 <ipython-input-8-33ea3a9649fd> [line:1] ERROR aaa
In [9]: logging.ERROR
Out[9]: 40
In [10]: logging.DEBUG
Out[10]: 10
In [11]: logging.WARN
Out[11]: 30
import logging,os
def init_log(path):
if os.path.exists(path):
mode = 'a'
else:
mode = 'w'
logging.basicConfig(
level=logging.INFO,
format='%(asctime)s %(filename)s [line:%(lineno)s] %(levelname)s %(message)s',
filename= path,
filemode= mode
)
return logging
# logging.basicConfig(level=logging.DEBUG,
# format='%(asctime)s %(filename)s [line:%(lineno)s] %(levelname)s %(message)s'
current_path = os.getcwd()
path = os.path.join(current_path,'back.log')
log = init_log(path)
log.info('这是第一个日志信息,test')
log.warning('这是一个警告')
log.error('这是一个重大的错误信息')
log.debug('这是一个debug')

In [1]: abs
Out[1]: <function abs(x, /)>
In [2]: abs(-13)
Out[2]: 13
In [3]: abs(2)
Out[3]: 2
In [4]: re = all(['a' in 'lain',Ture,None])
-----------------------------------------------------------------------
NameError Traceback (most recent call last)
Input In [4], in <cell line: 1>()
----> 1 re = all(['a' in 'lain',Ture,None])
NameError: name 'Ture' is not defined
In [5]: re = all(['a' in 'lain',True,None])
In [6]: re
Out[6]: False
In [7]: re = all(['a' in 'lain',True,12,len('123')])
In [8]: re
Out[8]: True
In [9]: python = ['django','flask','tornada']
In [10]: for index,item in enumerate(python):
...: print(index,item)
...:
0 django
1 flask
2 tornada
# food = input('你喜欢吃什么水果:')
# print(food)
#
# help(input)
class Test(object):
a = 1
b = 2
def __init__(self):
self.a = self.a
self.b = self.b
test = Test()
print(test.a)
# vars返回实例化的字典信息
result = vars(test)
print(result)
# hasattr判断对象中是否有某个属性,返回Ture或者false
print(hasattr(test,'a'))
print(hasattr(test,'c'))
print(hasattr(list,'a'))
print(hasattr(list,'append'))
# 为实例化对象,添加属性与值
setattr(test,'c','wewe')
print(test.c)
print(vars(test))
# getattr通过对象获取属性
print(getattr(list,'append'))
print(getattr(test,'c'))
a = ['',None,True,0]
print(any(a))
print(all(a))

- random.random 模块.函数
- random.random random.uniform random.randint
- random.choice random.sample random.randrange
import random
gifts = ['phone','book','car','现金1000元','Mac']
def choice_gifts():
gift = random.choice(gifts)
print('你抽到的礼物是%s' % gift)
def choice_gift_new():
count = random.randrange(0,100,2)
if 0<= count <=40:
print('你中了200元')
elif 40< count <=70:
print('你中了一台电视')
elif 70< count <=90:
print('你中了一台mac电脑')
elif count> 90:
print('你中了一辆车')
if __name__ == '__main__':
choice_gifts()
choice_gift_new()

迭代器
- 全部取完之后就会报错,停止运行StopIteration
- 按需加载(类似取苹果)
- 迭代器的生成方法:for循环生成法-yield;for循环-行生成迭代器 程序正常退出,不会报错
# 迭代器:提高效率,节省内存消耗
iter_obj = iter((1,2,3))
# print(next(iter_obj))
# print(next(iter_obj))
# print(next(iter_obj))
# print(next(iter_obj))
# iter中的内容读取完之后,就不能再进行读取了,报错 StopIteration
def _next(iter_obj):
try:
return next(iter_obj)
except StopIteration:
return None
# print(_next(iter_obj))
# print(_next(iter_obj))
# print(_next(iter_obj))
# print(_next(iter_obj))
# 不会报错,相对更友好
for i in iter_obj:
print(i)
# 第二种: yield生成迭代器
def make_iter():
for i in range(5):
yield i
iter_obj2 = make_iter()
print('===',type(iter_obj2))
for i in iter_obj2:
print(i)
print('-----')
# 迭代器会把数据每一次放到内存中,被读取之后,内存就被释放
# 完整的读取完一个迭代器数据后,该迭代器就会被清空了,就没有数据了
for i in iter_obj2:
print(i)
print('第三种生成迭代器方法')
iter_obj3 = (i for i in range(4))
for i in iter_obj3:
print(i)
print('-----')
for i in iter_obj3:
print(i)

- 高级函数,filter map reduce
- filter 对循环根据过滤条件进行过滤,返回一个filter对象
- map 对列表中的每个成员依次执行函数,将执行结果放到新的list中,返回map对象(True/None)
- reduce 对循环前后两个数据进行累加,返回数值
- from funtools import reduce
from functools import reduce
books = ['python','java','C++','golang','flask']
re01 = filter(lambda x:'a'in x,books)
print(re01,list(re01))
print(books)
def filter_func(item):
if 'a' in item:
return True
filter_re = filter(filter_func,books)
print(filter_re,tuple(filter_re),type(filter_re))
# map把对应的结果进行True,false的变更
map_re = map(filter_func,books)
print(map_re,list(map_re),type(map_re))
# from functools import reduce
reduce_re = reduce(lambda x,y:x+y,[3,2,4])
print(reduce_re)
reduce_re = reduce(lambda x,y:x*y,[3,2,4])
print(reduce_re)
reduce_re = reduce(lambda x,y:x+y,books)
print(reduce_re)
731



被折叠的 条评论
为什么被折叠?



