用函数生成随机时间
def randtime(a,b):
start=time.mktime(a)
end=time.mktime(b)
t=random.randint(start,end)
return time.strftime("%Y-%M-%d %H:%m:%S",time.localtime(t))
a=(1976,1,1,0,0,0,0,0,0)
b=(2099,12,31,23,59,59,0,0,0)
rtime=randtime(a,b)
print(rtime)
编写装饰器,为函数加上统计时间的功能
def outer(func):
def inter(*args, **kwargs):
stime = time.time()
res = func(*args, **kwargs)
etime = time.time()
dtime = etime - stime
print("函数执行耗时:{}".format(dtime))
return res
return inter
@outer
def func1():
print("start...")
time.sleep(1)
print("end...")
func1()
编写装饰器,为函数加上认证的功能
def auth(func):
def inter(*args, **kwargs):
db = [["admin", 123], ["test", 222]]
sum = 0
tag = True
while tag:
if sum == 3:
print("连续三次输错密码,程序退出...")
return
user_name = input("请输入用户名:").strip()
pasword = input("请输入密码:").strip()
for i in db:
if user_name == i[0] and pasword == str(i[1]):
print("认证成功")
tag = False
break
else:
print("认证失败,请重新输入")
sum += 1
res = func(*args, **kwargs)
return res
return inter
@auth
def func1():
print("start...")
time.sleep(1)
print("end...")
func1()
编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函
数都无需再输入用户名和密码
is_login = False
def get_db():
data = {}
with open("db.txt","rt",encoding="utf-8") as f:
data=eval(f.read())
return data
def auth(func):
def inter(*args, **kwargs):
global is_login
if not is_login:
db = get_db()
tag = True
while tag:
user_name = input("请输入用户名或按b退出:").strip()
pasword = input("请输入密码:").strip()
if user_name == "b":
return
if user_name == db["name"] and pasword == db["password"]:
print("认证成功")
is_login = True
tag = False
break
else:
print("认证失败,请重新输入")
res = func(*args, **kwargs)
return res
return inter
@auth
def func1():
print("func1 start...")
time.sleep(1)
print("end...")
@auth
def func2():
print("func2 start...")
time.sleep(1)
print("end...")
while True:
print("""
1 函数1
2 函数2
""")
a = input("请输入指令或按b退出:").strip()
if a=="1":
func1()
elif a == "2":
func2()
elif a =="b":
break
else:
print("指令错误")
编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时
间,则必须重新登录
a = datetime.datetime.now()
is_login = [False, a]
def get_db():
data = {}
with open("db.txt", "rt", encoding="utf-8") as f:
data = eval(f.read())
return data
def auth(func):
def inter(*args, **kwargs):
global is_login
login_time = is_login[1]
now_time = datetime.datetime.now()
diff_time = int((login_time - now_time).total_seconds())
if not is_login[0] and diff_time <= 0:
db = get_db()
tag = True
while tag:
user_name = input("请输入用户名或按b退出:").strip()
pasword = input("请输入密码:").strip()
if user_name == "b":
return
if user_name == db["name"] and pasword == db["password"]:
print("认证成功,60秒有效")
is_login[1] = login_time + datetime.timedelta(seconds=60)
tag = False
break
else:
print("认证失败,请重新输入")
res = func(*args, **kwargs)
return res
return inter
@auth
def func1():
print("func1 start...")
time.sleep(1)
print("end...")
@auth
def func2():
print("func2 start...")
time.sleep(1)
print("end...")
while True:
print("""
1 函数1
2 函数2
""")
a = input("请输入指令或按b退出:").strip()
if a == "1":
func1()
elif a == "2":
func2()
elif a == "b":
break
else:
print("指令错误")
编写日志装饰器,实现功能如:一旦函数 f1 执行,则将消息 2017-07-21 11:12:11 f1 run 写入到日
志文件中,日志文件路径可以指定
def f1():
with open("log.txt","at",encoding="utf-8") as f:
for i in range(20):
strs = "{time} run\n".format(time=time.strftime('%Y-%m-%d %X'))
f.write(strs)
f1()
编写下载网页内容的函数,要求功能是:用户传入一个 url,函数返回下载页面的结果
def save(url):
filename = "{name}.html".format(name=url.replace("/", "").replace(".", "").replace(":", ""))
with open(filename, "wb") as f:
f.write(get_url(url))
url = input("请输入网址:").strip()
if len(url) < 10:
print("长度不正确")
else:
save(url)