Python练习--函数

一:编写函数,(函数执行的时间是随机的)

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
import time,random

def print_time():
    time.sleep(random.randrange(0,3))
    print(random.randrange(0,3))
print_time()


二:编写装饰器,为函数加上统计时间的功能

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth

import time

def timmer(func):
    def wrapper(*args,**kwargs):
        start_time = time.time()
        res = func(*args,**kwargs)
        stop_time = time.time()
        print('函数运行时间是:%s' %(stop_time-start_time))
        return res
    return wrapper

@timmer
def foo():
    time.sleep(2)
    print('这个是foo运行的结果')

foo()


三:编写装饰器,为函数加上认证的功能

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth

def auth(dirver='file'):
    def auth2(func):
        def wrapper(*args,**kwargs):
            name = input("user:")
            pwd = input("pwd:")

            if dirver == 'file':
                if name == 'egon' and pwd == '123':
                    print('登录成功')
                    res = func(*args,**kwargs)
                    return res
                else:
                    res = '用户名或密码错误!'
                    print(res)
            elif dirver == 'ldap':
                print('ldap')
        return wrapper
    return auth2

@auth(dirver='file')
def foo(name):
    print(name)

foo('egon')

四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
db = 'db.txt'
login_status = {'user':None,'status':False}
def auth(auth_type='file'):
    def auth2(func):
        def warpper(*args,**kwargs):
            if login_status['user'] and login_status['status']:
                return func(*args,**kwargs)
            if auth_type == 'file':
                tag = True
                while tag:
                    with open(db,'r',encoding='utf-8') as read_f:
                        dic = eval(read_f.read())
                    name = input('请输入用户名:').strip()
                    passwd = input('请输入密码:').strip()
                    if name in dic and passwd == dic[name]:
                        login_status['user'] = name
                        login_status['status'] = True
                        res = func(*args,**kwargs)
                        tag = False
                        return res
                    else:
                        print('您输入的用户名或密码错误!')
            elif auth_type == 'mysql':
                pass
        return warpper
    return auth2



def index():
    print('欢迎来到首页')

@auth()
def home(name):
    print('欢迎来到%s的首页' %name)

@auth()
def  shopping(name):
    print('欢迎来到%s的购物车' %name)

@auth()
def order(name):
    print('欢迎来到%s的订单列表' %name)

index()
home('stealth')
shopping('stealth')
order('stealth')

五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
import time,random
db = 'db.txt'
login_status = {'user':None,'status':False,'login_time':None,'timeout':2}

def timeer(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(auth_type='file'):
    def auth2(func):
        def warpper(*args,**kwargs):
            if auth_type == 'file':
                if login_status['user']:
                    timeout = time.time()-login_status['login_time']
                    if timeout < login_status['timeout']:
                        return func(*args, **kwargs)
                tag = True
                while tag:
                    with open(db,'r',encoding='utf-8') as read_f:
                        dic = eval(read_f.read())
                    name = input('请输入用户名:').strip()
                    passwd = input('请输入密码:').strip()
                    if name in dic and passwd == dic[name]:
                        login_status['user'] = name
                        login_status['status'] = True
                        login_status['login_time'] = time.time()
                        res = func(*args,**kwargs)
                        tag = False
                        return res
                    else:
                        print('您输入的用户名或密码错误!')
            elif auth_type == 'mysql':
                pass
        return warpper
    return auth2


@auth()
def index():
    time.sleep(random.randrange(3))
    print('欢迎来到首页')

@auth()
def home(name):
    time.sleep(random.randrange(3))
    print('欢迎来到%s的首页' %name)

@auth()
def  shopping(name):
    time.sleep(random.randrange(3))
    print('欢迎来到%s的购物车' %name)

@auth()
def order(name):
    time.sleep(random.randrange(3))
    print('欢迎来到%s的订单列表' %name)

index()
home('stealth')
shopping('stealth')
order('stealth')

六:编写下载网页内容的函数,要求功能是:用户传入一个url,函数返回下载页面的结果

from urllib.request import urlopen


def index(url):
    def get():
        return urlopen(url).read()

    return get


baidu = index('http://www.baidu.com')
print(baidu().decode('utf-8'))

七:为题目五编写装饰器,实现缓存网页内容的功能:
具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中

扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
import hashlib,os,requests
engine_setting = {
    'file':{'dirname':'c:\db'},
    'mysql':{
        'host':'127.0.0.1',
        'port':3306,
        'user':'root',
        'password':'pass123',
        'database':'web_cache'},
    'redis':{
        'host':'127.0.0.1',
        'port':6379,
        'user':'root',
        'password':'pass123'}
}

def make_cache(engine='file'):
    if engine not in engine_setting:
        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_setting['file']['dirname'],cache_filename)
                if os.path.exists(cache_filepath) and os.path.getsize(cache_filepath):
                    with open(cache_filepath,'r',encoding='utf-8') as read_f:
                        return read_f.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.baidu.com'))
print(get('https://map.baidu.com'))

 

八:还记得我们用函数对象的概念,制作一个函数字典的操作吗,来来来,我们有更高大上的做法,在文件开头声明一个空字典,然后在每个函数前加上装饰器,完成自动添加到字典的操作

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
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')

@make_route('create')
def func5():
    print('create')

print(route_dic)

九 编写日志装饰器,实现功能如:一旦函数f1执行,则将消息2017-07-21 11:12:11 f1 run写入到日志文件中,日志文件路径可以指定
注意:时间格式的获取
import time
time.strftime('%Y-%m-%d %X')

#!/usr/bin/evn python
# -*- coding:utf-8 -*-
# author:stealth
import time,os
def logger(logfile):
    def deco(func):
        def wrapper(*args,**kwargs):
            res = func(*args,**kwargs)
            with open(logfile,'a+',encoding='utf-8') as f:
                f.write('%s run\n' %(time.strftime('%Y-%m-%d %X')))
            return res
        return wrapper
    return deco



@logger('log1.txt')
def index():
    print('欢迎来到首页')

index()
time.sleep(3)
index()
time.sleep(3)
index()

 

你可能感兴趣的:(python练习)