程序规范
1.bin目录--存放执行脚本
里面有一个start.py文件,作文执行程序的开始
import os import sys BaseDir = os.path.dirname(os.path.dirname(os.getcwd())) #获取包的路径 sys.path.append(BaseDir) #把包添加到导入搜索路径 from ChoiceCourses.core import core core.main()
start.py
2.conf目录---存放配置文件
3.core目录---存放核心逻辑代码
4.db目录---存放数据库文件
5.lib目录---存放自定义的模块与包
6.log目录---存放日志
#=============>bin目录:存放执行脚本 #start.py import sys,os BASE_DIR=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASE_DIR) from core import core from conf import my_log_settings if __name__ == ‘__main__‘: my_log_settings.load_my_logging_cfg() core.run() #=============>conf目录:存放配置文件 #config.ini [DEFAULT] user_timeout = 1000 [egon] password = 123 money = 10000000 [alex] password = alex3714 money=10000000000 [yuanhao] password = ysb123 money=10 #settings.py import os config_path=r‘%s\%s‘ %(os.path.dirname(os.path.abspath(__file__)),‘config.ini‘) user_timeout=10 user_db_path=r‘%s\%s‘ %(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), ‘db‘) #my_log_settings.py """ logging配置 """ import os import logging.config # 定义三种日志输出格式 开始 standard_format = ‘[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]‘ ‘[%(levelname)s][%(message)s]‘ #其中name为getlogger指定的名字 simple_format = ‘[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s‘ id_simple_format = ‘[%(levelname)s][%(asctime)s] %(message)s‘ # 定义日志输出格式 结束 logfile_dir = r‘%s\log‘ %os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # log文件的目录 logfile_name = ‘all2.log‘ # log文件名 # 如果不存在定义的日志目录就创建一个 if not os.path.isdir(logfile_dir): os.mkdir(logfile_dir) # log文件的全路径 logfile_path = os.path.join(logfile_dir, logfile_name) # log配置字典 LOGGING_DIC = { ‘version‘: 1, ‘disable_existing_loggers‘: False, ‘formatters‘: { ‘standard‘: { ‘format‘: standard_format }, ‘simple‘: { ‘format‘: simple_format }, }, ‘filters‘: {}, ‘handlers‘: { #打印到终端的日志 ‘console‘: { ‘level‘: ‘DEBUG‘, ‘class‘: ‘logging.StreamHandler‘, # 打印到屏幕 ‘formatter‘: ‘simple‘ }, #打印到文件的日志,收集info及以上的日志 ‘default‘: { ‘level‘: ‘DEBUG‘, ‘class‘: ‘logging.handlers.RotatingFileHandler‘, # 保存到文件 ‘formatter‘: ‘standard‘, ‘filename‘: logfile_path, # 日志文件 ‘maxBytes‘: 1024*1024*5, # 日志大小 5M ‘backupCount‘: 5, ‘encoding‘: ‘utf-8‘, # 日志文件的编码,再也不用担心中文log乱码了 }, }, ‘loggers‘: { #logging.getLogger(__name__)拿到的logger配置 ‘‘: { ‘handlers‘: [‘default‘, ‘console‘], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕 ‘level‘: ‘DEBUG‘, ‘propagate‘: True, # 向上(更高level的logger)传递 }, }, } def load_my_logging_cfg(): logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置 logger = logging.getLogger(__name__) # 生成一个log实例 logger.info(‘It works!‘) # 记录该文件的运行状态 if __name__ == ‘__main__‘: load_my_logging_cfg() #=============>core目录:存放核心逻辑 #core.py import logging import time from conf import settings from lib import read_ini config=read_ini.read(settings.config_path) logger=logging.getLogger(__name__) current_user={‘user‘:None,‘login_time‘:None,‘timeout‘:int(settings.user_timeout)} def auth(func): def wrapper(*args,**kwargs): if current_user[‘user‘]: interval=time.time()-current_user[‘login_time‘] if interval < current_user[‘timeout‘]: return func(*args,**kwargs) name = input(‘name>>: ‘) password = input(‘password>>: ‘) if config.has_section(name): if password == config.get(name,‘password‘): logger.info(‘登录成功‘) current_user[‘user‘]=name current_user[‘login_time‘]=time.time() return func(*args,**kwargs) else: logger.error(‘用户名不存在‘) return wrapper @auth def buy(): print(‘buy...‘) @auth def run(): print(‘‘‘ 购物 查看余额 转账 ‘‘‘) while True: choice = input(‘>>: ‘).strip() if not choice:continue if choice == ‘1‘: buy() if __name__ == ‘__main__‘: run() #=============>db目录:存放数据库文件 #alex_json #egon_json #=============>lib目录:存放自定义的模块与包 #read_ini.py import configparser def read(config_file): config=configparser.ConfigParser() config.read(config_file) return config #=============>log目录:存放日志 #all2.log [2017-07-29 00:31:40,272][MainThread:11692][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:31:41,789][MainThread:11692][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:31:46,394][MainThread:12348][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:31:47,629][MainThread:12348][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:31:57,912][MainThread:10528][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:32:03,340][MainThread:12744][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:32:05,065][MainThread:12916][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:32:08,181][MainThread:12916][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:32:13,638][MainThread:7220][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:32:23,005][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功] [2017-07-29 00:32:40,941][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功] [2017-07-29 00:32:47,222][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功] [2017-07-29 00:32:51,949][MainThread:7220][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:33:00,213][MainThread:7220][task_id:core.core][core.py:20][INFO][登录成功] [2017-07-29 00:33:50,118][MainThread:8500][task_id:conf.my_log_settings][my_log_settings.py:75][INFO][It works!] [2017-07-29 00:33:55,845][MainThread:8500][task_id:core.core][core.py:20][INFO][登录成功] [2017-07-29 00:34:06,837][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:34:09,405][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在] [2017-07-29 00:34:10,645][MainThread:8500][task_id:core.core][core.py:25][ERROR][用户名不存在]
isinstance
from collections import Iterable print(isinstance(range(10),Iterable)) #判断是不是可迭代序列 print(isinstance(10,int)) #type(10) is int type的方法更好一点
判断一个对象是不是这个类的实例,如果这个类有父类,那么这个对象也是其父类的对象
class Foo(object):pass obj = Foo() print(isinstance(obj, Foo)) #判断第一个参数是否是第二个参数的对象,返回一个布尔值 print(isinstance(obj, object))
issubclass() : 判断两个类是不是父子关系,接受两个参数(子类,父类)
反射
2 python面向对象中的反射:通过字符串的形式操作对象相关的属性。python中的一切事物都是对象(都可以使用反射)
1.getattr 获取属性
class SB: def __init__(self,name): self.name = name def happy(self,x): print(‘sb %s is happy‘%self.name) return x+‘aaaaaa‘ jinghong = SB(‘景弘‘) #实例化对象 func = getattr(jinghong,‘happy‘) #相当于jinghong.happy ret = getattr(jinghong,‘name‘) #相当于jinghong.name # func2 = getattr(jinghong,‘sleep‘) #没有这个属性或者方法就会报错 func(‘bbb‘) #sb 景弘 is happy print(ret) #景弘
2.hasattr 检查是否含有某属性
class Login(): def login(self): print(‘login‘) def register(self): print(‘register‘) l = Login() #实例化对象 f = input(‘func >>>‘) #用户输入字符串 if hasattr(l,f): #判断f是否是对象l的属性 getattr(l,f)() #如果是的话获得方法名,加()直接执行 相当于l.login
3.setattr 设置属性
class SB: def __init__(self,name): self.name = name def happy(self,x): print(‘sb %s is happy‘%self.name) return x+‘aaaaaa‘ jinghong = SB(‘景弘‘) setattr(jinghong,‘sex‘,‘female‘) #设置jinghong对象的sex属性为female print(jinghong.sex) #female
时间: 2024-10-08 18:28:31