1. 程式人生 > >python第四天練習題

python第四天練習題

error else ont sts lin org 時間格式 修飾 exists

# 一:編寫函數,(函數執行的時間是隨機的)
# import time
# import random
# def fun1():
# time.sleep(random.randrange(1, 3))
# print(random.randrange(1, 3))
# fun1()
# 二:編寫裝飾器,為函數加上統計時間的功能
# import time
# import random
# def timer(func):
# # func = fun1
# def wrapper():
# star_time = time.time()
# func()

# stop_time = time.time()
# print(‘執行時間:%s‘ % (stop_time - star_time))
# return wrapper
# @timer
# def fun1():
# time.sleep(random.randrange(1, 3))
# print(‘welcome to the page‘)
# fun1()
# 三:編寫裝飾器,為函數加上認證的功能
# import time
# import random
# def check(func):
# ‘‘‘
# 修飾器:增加認證功能!

# :return:
# ‘‘‘
# def wrapper(*args,**kwargs):
# usrname=input("Please input your name: ").strip()
# pwd=input("Please input your pwd: ").strip()
# if usrname == "ling" and pwd == "123":
# print("Login successful!")
# func(*args,**kwargs)
# else:

# print("Login error!")
# return wrapper
# @check
# def name(usr):
# ‘‘‘
# 函數執行時間是隨機的。
# :return:
# ‘‘‘
# time.sleep(random.randrange(3,6))
# print("%s,welcome to the page!" %(usr))
# name("ling")
# 四:編寫裝飾器,為多個函數加上認證的功能(用戶的賬號密碼來源於文件),要求登錄成功一次,後續的函數都無需再輸入用戶名和密碼
# 註意:從文件中讀出字符串形式的字典,可以用eval(‘{"name":"egon","password":"123"}‘)轉成字典格式
# db=‘db.txt‘
# login_status={‘user‘:None,‘status‘:False}
# def auth(auth_type=‘file‘):
# def auth2(func):
# def wrapper(*args,**kwargs):
# if login_status[‘user‘] and login_status[‘status‘]:
# return func(*args,**kwargs)
# if auth_type == ‘file‘:
# with open(db,encoding=‘utf-8‘) as f:
# dic=eval(f.read())
# name=input(‘username: ‘).strip()
# password=input(‘password: ‘).strip()
# if name in dic and password == dic[name]:
# login_status[‘user‘]=name
# login_status[‘status‘]=True
# res=func(*args,**kwargs)
# return res
# else:
# print(‘username or password error‘)
# elif auth_type == ‘sql‘:
# pass
# else:
# pass
# return wrapper
# return auth2
#
# @auth()
# def index():
# print(‘index‘)
#
# @auth(auth_type=‘file‘)
# def home(name):
# print(‘welcome %s to home‘ %name)
# index()
# home(‘egon‘)
# 五:編寫裝飾器,為多個函數加上認證功能,要求登錄成功一次,在超時時間內無需重復登錄,超過了超時時間,則必須重新登錄
# import time,random
# user={‘user‘:None,‘login_time‘:None,‘timeout‘:0.000003,}
#
# def timmer(func):
# def wrapper(*args,**kwargs):
# s1=time.time()
# res=func(*args,**kwargs)
# s2=time.time()
# print(‘%s‘ %(s2-s1))
# return res
# return wrapper
#
#
# def auth(func):
# def wrapper(*args,**kwargs):
# if user[‘user‘]:
# timeout=time.time()-user[‘login_time‘]
# if timeout < user[‘timeout‘]:
# return func(*args,**kwargs)
# name=input(‘name>>: ‘).strip()
# password=input(‘password>>: ‘).strip()
# if name == ‘egon‘ and password == ‘123‘:
# user[‘user‘]=name
# user[‘login_time‘]=time.time()
# res=func(*args,**kwargs)
# return res
# return wrapper
#
# @auth
# def index():
# time.sleep(random.randrange(3))
# print(‘welcome to index‘)
#
# @auth
# def home(name):
# time.sleep(random.randrange(3))
# print(‘welcome %s to home ‘ %name)
#
# index()
# home(‘egon‘)

# 六:編寫下載網頁內容的函數,要求功能是:用戶傳入一個url,函數返回下載頁面的結果
# from urllib.request import urlopen
#
# def get(url):
# return urlopen(url).read()
# print(get(‘https://www.baidu.com‘))

# 七:為題目五編寫裝飾器,實現緩存網頁內容的功能:
# 具體:實現下載的頁面存放於文件中,如果文件內有值(文件大小不為0),就優先從文件中讀取網頁內容,否則,就去下載,然後存到文件中
# import requests
# import os
# cache_file=‘cache.txt‘
# def make_cache(func):
# def wrapper(*args,**kwargs):
# if not os.path.exists(cache_file):
# with open(cache_file,‘w‘):pass
#
# if os.path.getsize(cache_file):
# with open(cache_file,‘r‘,encoding=‘utf-8‘) as f:
# res=f.read()
# else:
# res=func(*args,**kwargs)
# with open(cache_file,‘w‘,encoding=‘utf-8‘) as f:
# f.write(res)
# return res
# return wrapper
#
# @make_cache
# def get(url):
# return requests.get(url).text
# res=get(‘https://www.baidu.com‘)
# print(res)

# 擴展功能:用戶可以選擇緩存介質/緩存引擎,針對不同的url,緩存到不同的文件中
# import requests,os,hashlib
# engine_settings={
# ‘file‘:{‘dirname‘:‘./db‘},
# ‘mysql‘:{
# ‘host‘:‘127.0.0.1‘,
# ‘port‘:3306,
# ‘user‘:‘root‘,
# ‘password‘:‘123‘},
# ‘redis‘:{
# ‘host‘:‘127.0.0.1‘,
# ‘port‘:6379,
# ‘user‘:‘root‘,
# ‘password‘:‘123‘},
# }
#
# def make_cache(engine=‘file‘):
# if engine not in engine_settings:
# raise TypeError(‘egine not valid‘)
# def deco(func):
# def wrapper(url):
# if engine == ‘file‘:
# m=hashlib.md5(url.encode(‘utf-8‘))
# cache_filename=m.hexdigest()
# cache_filepath=r‘%s/%s‘ %(engine_settings[‘file‘][‘dirname‘],cache_filename)
#
# if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
# return open(cache_filepath,encoding=‘utf-8‘).read()
#
# res=func(url)
# with open(cache_filepath,‘w‘,encoding=‘utf-8‘) as f:
# f.write(res)
# return res
# elif engine == ‘mysql‘:
# pass
# elif engine == ‘redis‘:
# pass
# else:
# pass
#
# return wrapper
# return deco
#
# @make_cache(engine=‘file‘)
# def get(url):
# return requests.get(url).text
#
# # print(get(‘https://www.python.org‘))
# print(get(‘https://www.baidu.com‘))
# 八:還記得我們用函數對象的概念,制作一個函數字典的操作嗎,來來來,我們有更高大上的做法,在文件開頭聲明一個空字典,然後在每個函數前加上裝飾器,完成自動添加到字典的操作
# route_dic={}
#
# def make_route(name):
# def deco(func):
# route_dic[name]=func
# return deco
# @make_route(‘select‘)
# def func1():
# print(‘select‘)
#
# @make_route(‘insert‘)
# def func2():
# print(‘insert‘)
#
# @make_route(‘update‘)
# def func3():
# print(‘update‘)
#
# @make_route(‘delete‘)
# def func4():
# print(‘delete‘)
#
# print(route_dic)

# 九 編寫日誌裝飾器,實現功能如:一旦函數f1執行,則將消息2017-07-21 11:12:11 f1 run寫入到日誌文件中,日誌文件路徑可以指定
# 註意:時間格式的獲取
# import time
# time.strftime(‘%Y-%m-%d %X‘)
# import time
# import os
#
# def logger(logfile):
# def deco(func):
# if not os.path.exists(logfile):
# with open(logfile,‘w‘):pass
#
# def wrapper(*args,**kwargs):
# res=func(*args,**kwargs)
# with open(logfile,‘a‘,encoding=‘utf-8‘) as f:
# f.write(‘%s %s run\n‘ %(time.strftime(‘%Y-%m-%d %X‘),func.__name__))
# return res
# return wrapper
# return deco
#
# @logger(logfile=‘aaaaaaaaaaaaaaaaaaaaa.log‘)
# def index():
# print(‘index‘)
#
# index()





























python第四天練習題