zoukankan      html  css  js  c++  java
  • 8.7 每日课后作业系列之常用模板(介绍和运用)

    # 今日作业:
    # p1.简述
    # 什么是模块
    #一系列功能的集合体

    # 模块有哪些来源
    # p1.内置
    # 2.第三方
    # 3.自定义

    # 模块的格式要求有哪些
    # p1 .py文件
    # 2 已被编译为共享库或DLL的C或C++扩展
    # 3 把一系列模块组织到一起的文件夹(注:文件夹下有一个__init__.py文件,该文件夹称之为包)
    # 4 使用C编写并链接到python解释器的内置模块

    # 2.定义一个cuboid模块,模块中有三个变量长(long)宽(wide)高(high),数值自定义,有一个返回值为周长的perimeter方法,一个返回值为表面积的area方法
    # import cuboid as cd
    # print(cd.perimeter())
    # print(cd.area())

    # 3.定义一个用户文件stu1.py,在该文件中打印cuboid的长宽高,并获得周长和表面积,打印出来
    # import cuboid
    # print(cuboid.long)
    # print(cuboid.wide)
    # print(cuboid.high)
    # print(cuboid.perimeter())
    # print(cuboid.area())


    # 4.在stu2.py文件中导入cuboid模块时为模块起简单别名,利用别名完成第3题中完成的操作
    # import cuboid as cd
    # print(cuboid.long)
    # print(cuboid.wide)
    # print(cuboid.high)
    # print(cuboid.perimeter())
    # print(cuboid.area())



    # 5.现在有三个模块sys、time、place,可以在run.py文件导入三个模块吗?有几种方式?分别写出来
    #
    # 6.结合第2、3、4题完成from...import...案例,完成同样的功能
    #
    # 7.比较总结import与from...import...各自的优缺点
    # import导入模块:在使用时必须加上前缀:模块名.
    # 优点: 指名道姓地向某一个名称空间要名字,肯定不会与当前名称空间中的名字冲突
    # 缺点: 但凡应用模块中的名字都需要加前缀,不够简洁
    # from...import...
    # 优点: 使用时,无需再加前缀,更简洁
    # 缺点: 容易与当前名称空间中的名字冲突
    #
    #
    # # 四:编写装饰器,为多个函数加上认证的功能(用户的账号密码来源于文件),要求登录成功一次,后续的函数都无需再输入用户名和密码
    # # 注意:从文件中读出字符串形式的字典,可以用eval('{"name":"egon","password":"123"}')转成字典格式
    login_status={'user':None,'status':False}
    def auth(type='file'):
    def auth1(func):
    def wrapper(*args,**kwargs):
    if login_status['user'] and login_status['status']:
    return func(*args,**kwargs)
    if type=='file':
    with open('db1.txt',mode='r',encoding='utf-8') as f:
    dic=eval(f.read())
    name=input('用户名:')
    pwd=input('密码:')
    if name==dic['name'] and pwd==dic['password']:
    login_status['user'] = name
    login_status['status'] = True
    res = func(*args, **kwargs)
    return res
    else:
    print('username or password error')
    return wrapper
    return auth1


    # 五:编写装饰器,为多个函数加上认证功能,要求登录成功一次,在超时时间内无需重复登录,超过了超时时间,则必须重新登录
    # import time,random
    # user={'user':None,'login_time':None,'timeout':0.0003}
    # def auth(func):
    # def wrapper(*args,**kwargs):
    # if user['user']:
    # time_out=time.time()-user['login_time']
    # if time_out<user['timeout']:
    # return func(*args,**kwargs)
    # name=input('用户名:')
    # pwd=input('密码:')
    # if name=='egon' and pwd=='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 page')
    #
    # @auth
    # def home(name):
    # time.sleep(random.randrange(3))
    # print('welcome to %s page' %name)
    #
    # index()
    # home('egon')

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


    # 七:为题目五编写装饰器,实现缓存网页内容的功能:
    # 具体:实现下载的页面存放于文件中,如果文件内有值(文件大小不为0),就优先从文件中读取网页内容,否则,就去下载,然后存到文件中
    # 扩展功能:用户可以选择缓存介质/缓存引擎,针对不同的url,缓存到不同的文件中

    # import os
    # import requests
    # cahce_file='cache.txt'
    # def cache(func):
    # def wrapper(*args,**kwargs):
    # if not os.path.exists(cahce_file):
    # with open(r'cache.txt',mode='w',encoding='utf-8'):pass
    # if os.path.getsize(cahce_file):
    # with open('cache.txt',mode='r',encoding='utf-8') as f:
    # res=f.read()
    # return res
    # else:
    # res=func(*args,**kwargs)
    # with open(cahce_file,mode='w',encoding='utf-8') as f:
    # f.write(res)
    # return res
    # return wrapper
    #
    # @cache
    # def get(url):
    # return requests.get(url).text
    # res=get('https://www.baidu.com')
    # print(res)


    #题目七:扩展版本
    # import requests,os,hashlib
    # engine_settings={
    # 'file':{'dirname':'./db'},
    # 'mysql':{
    # 'host':'127.0.0.p1',
    # 'port':3306,
    # 'user':'root',
    # 'password':'123'},
    # 'redis':{
    # 'host':'127.0.0.p1',
    # '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)
    # for k,v in route_dic.items():
    # print(k,v)
    # v()

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

    # import os
    # import time
    # def outter1(cache):
    # def outter2(func):
    # if not os.path.exists(cache):
    # with open(cache,mode='w',encoding='utf-8'):pass
    # def wrapper(*args,**kwargs):
    # with open(cache,mode='a',encoding='utf-8') as f:
    # res=f.write('%s %s run ' %(time.strftime('%Y-%m-%d %H:%M:%S %p'),func.__name__))
    # return res
    # return wrapper
    # return outter2
    # @outter1(cache='b.txt')
    # def index():
    # print('index')
    # index()
  • 相关阅读:
    kaggle CTR预估
    基于大规模语料的新词发现算法【转自matix67】
    vim E437: terminal capability "cm" required
    makefile 中的符号替换($@、$^、$<、$?)
    【转】Makefile 中:= ?= += =的区别
    python urljoin问题
    python 写文件刷新缓存
    python Popen卡死问题
    nohup 日志切割
    换行和回车野史
  • 原文地址:https://www.cnblogs.com/Maikes/p/9459169.html
Copyright © 2011-2022 走看看