# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/19 10:12
import pickle
import os
import time
class Certification(object):
'''登录认证类'''
def __init__(self):
pass
def written_information(self, file_name, content):
'''写入信息'''
with open('%s' % file_name, mode='ab') as f:
pickle.dump(content, f)
def read_information(self, file_name):
'''读取信息'''
with open('%s' % file_name, mode='rb') as f:
while True:
try:
r = pickle.load(f)
# print(r.__dict__)
print('~' * 25)
for k, v in r.__dict__.items():
yield k, v
except EOFError:
break
def login(self):
'''登录验证'''
for i in range(3):
user = input('请输入登录名 :').strip()
if 'admin' == user.lower():
passwd = input('请输入管理员密码 :').strip()
if 'admin' == passwd:
print('登录成功!欢迎你,%s管理员!' % user)
return user
else:
print('管理员密码校验失败!')
continue
ret = Certification().read_information('db/student_info.txt')
for k, v in ret:
if 'username' == k and user == v.split(':')[-1].strip():
passwd = input('请输入密码 :').strip()
if passwd == ret.__next__()[-1].split(':')[-1].strip():
print('登录成功!欢迎你,%s同学!' % user)
return user, passwd, ret.__next__()[-1], ret.__next__()[-1], ret.__next__()[-1]
else:
print('密码校验失败!')
else:
print('账号不存在!')
else:
print('您的3次尝试机会已用完,谢谢使用!')
return False
class Course(object):
'''课程类'''
def __init__(self, name, price, period, teacher):
self.name = name
self.price = price
self.period = period
self.teacher = teacher
class Students(object):
'''学生类'''
def __init__(self, username, password, age, sex, phone):
self.username = username
self.password = password
self.age = age
self.sex = sex
self.phone = phone
def view_optional_courses(self):
'''查看可选课程'''
# Admin('admin').view_all_courses()
print('~' * 25)
print('\033[31;1m所有可选课程信息如下:\033[0m')
ret = Certification().read_information('db/course_info.txt')
for k, v in ret:
print(v)
print('~' * 25)
def choose_course(self):
'''选择课程'''
print('请输入选择课程名称:')
flag = True
while flag:
choose = input().strip()
ret = Certification().read_information('db/course_info.txt')
for k, v in ret:
if '课程名称' in v and choose in v:
name = v
price = ret.__next__()[-1]
period = ret.__next__()[-1]
teacher = ret.__next__()[-1]
print('选择课程成功!详情如下:\n%s\n%s\n%s\n%s' % (name, price, period, teacher))
c = Course(name, price, period, teacher) # 将课程信息传入课程类
Certification().written_information('db/%s_choose_course_info.txt' % self.username, c) # 将课程类写入文件
flag = False
break
else:
print('选择的课程不存在哦!请重新选择:')
def view_selected_courses(self):
'''查看所选课程'''
print('~' * 25)
print('\033[31;1m%s所选课程信息如下:\033[0m' % self.username)
ret = Certification().read_information('db/%s_choose_course_info.txt' % self.username)
for k, v in ret:
print(v)
print('~' * 25)
def student_view(self):
'''学生界面'''
while True:
print('*' * 25)
print('1、查看可选课程')
print('2、选择课程')
print('3、查看已选课程')
print('4、退出')
print('*' * 25)
choose = input('请选择:').strip()
if '1' == choose:
self.view_optional_courses()
elif '2' == choose:
self.choose_course()
elif '3' == choose:
try:
self.view_selected_courses()
except:
print('\033[31;1m你还没有选择任何课程哦!\033[0m')
elif '4' == choose:
print('谢谢使用!')
exit(-1)
else:
print('输入有误,请重新输入!')
print('5秒后自动跳转回主页面!')
time.sleep(5)
class Admin(object):
'''管理员类'''
def __init__(self, name):
self.name = name
def create_student_account(self):
'''创建学生账号'''
username = '姓名:' + input('please input the student`s username:').strip()
password = '密码:' + input('please input the student`s password:').strip()
age = '年龄:' + input('please input the age:').strip()
sex = '性别:' + input('please input the sex:').strip()
phone = '手机号码:' + input('please input the phone number:').strip()
print('\033[31;1m学生账号创建成功!详细信息如下:\033[0m\n%s\n%s\n%s\n%s' % (username, age, sex, phone))
s = Students(username, password, age, sex, phone)
Certification().written_information('db/student_info.txt', s) # 将学生类写入文件
def view_all_students(self):
'''查看所有学生'''
print('~' * 25)
print('\033[31;1m所有学生信息如下:\033[0m')
ret = Certification().read_information('db/student_info.txt')
for k, v in ret:
print(v)
print('~' * 25)
def create_course(self):
'''创建课程'''
name = '课程名称:' + input('please input the course name:').strip()
price = '课程价格:' + input('please input the course`s price:').strip()
period = '课程周期:' + input('please input the period:').strip()
teacher = '授课老师:' + input('please input the teacher`s name:').strip()
print('\033[31;1m创建课程成功!信息如下:\033[0m\n%s\n%s\n%s\n%s' % (name, price, period, teacher))
c = Course(name, price, period, teacher) # 将课程信息传入课程类
Certification().written_information('db/course_info.txt', c) # 将课程类写入文件
def view_all_courses(self):
'''查看所有课程'''
print('~' * 25)
print('\033[31;1m所有课程信息如下:\033[0m')
ret = Certification().read_information('db/course_info.txt')
for k, v in ret:
print(v)
print('~' * 25)
def view_all_selected_courses(self):
'''查看所有学生的选课情况'''
work_path = os.getcwd()
path = os.path.join(work_path, 'db')
for file_name in os.listdir(path):
if 'choose_course_info' in file_name:
print('~' * 25)
print('\033[31;1m%s所选课程信息如下:\033[0m' % file_name.split('_')[0])
ret = Certification().read_information('db/%s' % file_name)
for k, v in ret:
print(v)
print('~' * 25)
def admin_view(self):
'''管理员界面'''
while True:
print('*' * 25)
print('1、创建学生账号')
print('2、查看所有学生信息')
print('3、创建课程')
print('4、查看所有课程')
print('5、查看所有学生的选课情况')
print('6、退出')
print('*' * 25)
choose = input('请选择:').strip()
if '1' == choose:
self.create_student_account()
elif '2' == choose:
self.view_all_students()
elif '3' == choose:
self.create_course()
elif '4' == choose:
self.view_all_courses()
elif '5' == choose:
self.view_all_selected_courses()
elif '6' == choose:
print('谢谢使用!')
exit(-1)
else:
print('输入有误,请重新输入!')
print('5秒后自动跳转回主页面!')
time.sleep(5)
if __name__ == '__main__':
'''
管理员账号:admin
管理员密码:admin
'''
print('欢迎来到luffy选课系统!')
ret = Certification().login()
if 'admin' == ret:
a = Admin(ret)
a.admin_view()
elif ret:
s = Students(ret[0], ret[1], ret[2], ret[3], ret[4])
s.student_view()
选课系统版本1
修复了以下bug:
1、支持多个管理员账号
2、学生查看可选课程时,如果已经选过的课程就不再展示,只展示未选课程
3、学生选课时,判断课程是否已存在,避免重复选课
4、管理员创建账号时,判断学生账号是否已存在,避免重复创建
5、管理员创建课程时,判断课程是否已存在,避免重复创建
6、读取文件信息时,判断文件是否存在,避免报错。
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/19 10:12
import pickle
import os
import time
work_path = os.getcwd() # 获取当时工作目录绝对路径
db_path = os.path.join(work_path, 'db') # 数据存储路径
class Certification(object):
'''登录认证类'''
def __init__(self):
pass
def written_information(self, file_name, content):
'''写入信息'''
with open('%s' % file_name, mode='ab') as f:
pickle.dump(content, f)
def read_information(self, file_name):
'''读取信息'''
try:
with open('%s' % file_name, mode='rb') as f:
while True:
try:
r = pickle.load(f)
for k, v in r.__dict__.items():
yield k, v # 以迭代器方式返回,节省内存使用
except EOFError:break
except:return ("", "")
def login(self):
'''登录验证'''
for i in range(3): # 3次机会
user = input('请输入登录名 :').strip()
if user in admin_dict: # 优先校验管理员账号,管理员账号总会比普通账号少嘛。
passwd = input('请输入管理员密码 :').strip()
if admin_dict[user] == passwd:
print("*" * 25 + '\n登录成功!%s管理员!' % user)
return user
else:
print('管理员密码校验失败!')
continue
ret = Certification().read_information('db/student_info.txt') # 读取学生账号信息文件,返回迭代器
for k, v in ret:
if 'username' == k and user == v.split(':')[-1].strip():
passwd = input('请输入密码 :').strip()
if passwd == ret.__next__()[-1].split(':')[-1].strip():
print("*" * 25 + '\n登录成功!%s同学!' % user)
return user, passwd, ret.__next__()[-1], ret.__next__()[-1], ret.__next__()[-1]
else:
print('密码校验失败!')
else:
print('账号不存在!')
else:
print('您的3次尝试机会已用完,谢谢使用!')
return False
class Course(object):
'''课程类'''
def __init__(self, name, price, period, teacher):
self.name = name
self.price = price
self.period = period
self.teacher = teacher
class Students(object):
'''学生类'''
def __init__(self, username, password, age, sex, phone):
self.username = username
self.password = password
self.age = age
self.sex = sex
self.phone = phone
def view_optional_courses(self):
'''查看可选课程'''
if not os.path.exists(db_path + '/course_info.txt'): return print('还未有可选课程哦!')
print('*' * 25 + '\n\033[31;1m所有可选课程信息如下:\033[0m')
stu = list(Certification().read_information('db/%s_choose_course_info.txt' % self.username))
ret = Certification().read_information('db/course_info.txt')
for k, v in ret:
for s, t in stu: # 只展示该学生未选的课程,已经选过的课就不能再选啦。
if t == v: break
else:
print(v)
def choose_course(self):
'''选择课程'''
print('请输入选择课程名称:')
flag = True
while flag:
choose = input().strip()
ret = Certification().read_information('db/%s_choose_course_info.txt' % self.username)
for k, v in ret: # 已经选过的课程就不能重复选择了。
if choose in v:
print('您已经选过\033[31;1m%s\033[0m课程!请重新选择:' % choose)
break
else:
ret = Certification().read_information('db/course_info.txt')
for k, v in ret: # 从剩下的可选课程中选择。
if '课程名称' in v and choose in v:
name = v # 将选择的课程信息都写入到该学生的选课文件中。
price = ret.__next__()[-1]
period = ret.__next__()[-1]
teacher = ret.__next__()[-1]
print("*" * 25 + '\n\033[31;1m选择课程成功!详情如下:\033[0m\n%s\n%s\n%s\n%s' % (name, price, period, teacher))
c = Course(name, price, period, teacher) # 将课程信息传入课程类
Certification().written_information('db/%s_choose_course_info.txt' % self.username,c) # 将课程类写入文件
flag = False
break
else:
print('选择的课程不存在哦!请重新选择:')
def view_selected_courses(self):
'''查看所选课程'''
if not os.path.exists(db_path + '/%s_choose_course_info.txt' % self.username): return print('您还未选择任何课程哦!')
print('*' * 25 + '\n\033[31;1m%s所选课程信息如下:\033[0m' % self.username)
ret = Certification().read_information('db/%s_choose_course_info.txt' % self.username)
for k, v in ret:print(v) # 打印课程信息
def student_view(self):
'''学生界面'''
while True:
print('*' * 25 + '\n1、查看可选课程\n2、选择课程\n3、查看已选课程\n4、退出\n' + '*' * 25)
choose = input('请选择:').strip()
if '1' == choose: # 查看可选课程
self.view_optional_courses()
elif '2' == choose: # 选择课程
self.choose_course()
elif '3' == choose: # 查看已选课程
self.view_selected_courses()
elif '4' == choose:
print('谢谢使用!')
exit(-1)
else:
print('输入有误,请重新输入!')
print('5秒后自动跳转回主页面!')
time.sleep(5)
class Admin(object):
'''管理员类'''
def __init__(self, name):
self.name = name
def create_student_account(self):
'''创建学生账号'''
while True:
username = '*' * 25 + '\n姓名:' + input('please input the student`s username:').strip()
ret = Certification().read_information('db/student_info.txt')
for k, v in ret: # 校验账号是否已存在
if username in v:
print('\033[31;1m%s学生账号已存在!!\033[0m' % username.split(':')[-1])
break
else:
password = '密码:' + input('please input the student`s password:').strip()
age = '年龄:' + input('please input the age:').strip()
sex = '性别:' + input('please input the sex:').strip()
phone = '手机号码:' + input('please input the phone number:').strip()
print("*" * 25 + '\n\033[31;1m学生账号创建成功!详细信息如下:\033[0m\n%s\n%s\n%s\n%s' % (username, age, sex, phone))
s = Students(username, password, age, sex, phone) # 将信息传入学生类
Certification().written_information('db/student_info.txt', s) # 将学生类写入文件
break
def view_all_students(self):
'''查看所有学生'''
if not os.path.exists(db_path + '/student_info.txt'): return print('还未添加任何学生账号哦!')
print('*' * 25 + '\n\033[31;1m所有学生信息如下:\033[0m')
ret = Certification().read_information('db/student_info.txt')
for k, v in ret:print(v) # 打印学生账号信息
def create_course(self):
'''创建课程'''
while True:
name = '*' * 25 + '\n课程名称:' + input('please input the course`s name:').strip()
ret = Certification().read_information('db/course_info.txt')
for k, v in ret: # 校验课程是否已存在,避免重复创建课程。
if name in v:
print('\033[31;1m%s课程已存在!!\033[0m' % name.split(':')[-1])
break
else:
price = '课程价格:' + input('please input the course`s price:').strip()
period = '课程周期:' + input('please input the period:').strip()
teacher = '授课老师:' + input('please input the teacher`s name:').strip()
print("*" * 25 + '\n\033[31;1m创建课程成功!信息如下:\033[0m\n%s\n%s\n%s\n%s' % (name, price, period, teacher))
c = Course(name, price, period, teacher) # 将课程信息传入课程类
Certification().written_information('db/course_info.txt', c) # 将课程类写入文件
break
def view_all_courses(self):
'''查看所有课程'''
if not os.path.exists(db_path + '/course_info.txt'): return print('还未添加任何课程哦!')
print('*' * 25 + '\n\033[31;1m所有课程信息如下:\033[0m')
ret = Certification().read_information('db/course_info.txt')
for k, v in ret:print(v) # 打印所有课程信息
def view_all_selected_courses(self):
'''查看所有学生的选课情况'''
flag = True
for file_name in os.listdir(db_path): # 获取所有的学生选课信息文件
if 'choose_course_info' in file_name:
print('*' * 25 + '\n\033[31;1m%s所选课程信息如下:\033[0m' % file_name.split('_')[0])
ret = Certification().read_information('db/%s' % file_name)
for k, v in ret:print(v) # 打印所选课程信息
flag = False
if flag: print('还未有学生选择任何课程哦!')
def admin_view(self):
'''管理员界面'''
while True:
print('*' * 25 + '\n1、创建学生账号\n2、查看所有学生信息\n3、创建课程\n4、查看所有课程\n5、查看所有学生的选课情况\n6、退出\n' + '*' * 25)
choose = input('请选择:').strip()
if '1' == choose: # 创建学生账号
self.create_student_account()
elif '2' == choose: # 查看所有学生信息
self.view_all_students()
elif '3' == choose: # 创建课程
self.create_course()
elif '4' == choose: # 查看所有课程
self.view_all_courses()
elif '5' == choose: # 查看所有学生的选课情况
self.view_all_selected_courses()
elif '6' == choose:
print('谢谢使用!')
exit(-1)
else:
print('输入有误,请重新输入!')
print('5秒后自动跳转回主页面!')
time.sleep(5)
if __name__ == '__main__':
admin_dict = {'admin': 'admin', 'xiaoqiang': '123'}
print("#" * 25 + '\n欢迎来到luffycity选课系统!\n' + "#" * 25)
ret = Certification().login() # 登录校验
if ret in admin_dict:
a = Admin(ret)
a.admin_view() # 管理员视图
elif ret:
s = Students(ret[0], ret[1], ret[2], ret[3], ret[4])
s.student_view() # 学生视图
选课系统版本2
拆分文件后目录结构如下:
这次改成用shelve模块来存储数据,发现shelve模块也是很好用的,跟字典类似,支持增删改查,存入文件时,要求key是字符类型,但是值可以是几乎所有的数据类型,包括对象的存储,真是很好用。
废话不多说,上版本3的源码:
bin目录:
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/29 14:36
import os
import sys
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
sys.path.append(BASE_DIR)
from core import main
if __name__ == '__main__':
main.main()
start.py
conf目录:
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:37
import os
import time
# 当前文件工作目录绝对路径
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# 数据存储路径
db_path = os.path.join(BASE_DIR, 'db')
if not os.path.exists(db_path):os.makedirs(db_path)
# 学生账号信息文件
student_file = r'%s/student_info' % db_path
# 课程信息文件
course_file = r'%s/course_info' % db_path
# 学生选课信息存储路径
def choose_course_path(name):
path = os.path.join(db_path,'choose_course',name)
if not os.path.exists(path):os.makedirs(path)
return path
# 学生选课信息文件,函数:传入学生姓名。
choose_course_file = lambda name: r'%s/choose_course_info' % (choose_course_path(name))
# 日志文件路径
log_path = os.path.join(BASE_DIR,'log')
if not os.path.exists(log_path):os.makedirs(log_path)
log_file = r'%s/%s-log' % (log_path,time.strftime('%Y-%m-%d', time.localtime(time.time())))
settings.py
core目录:
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:11
import sys
import time
from core.common import Common as cn
from core.log import Log as log
from conf import settings as ss
from core import student
from core import manager
def main():
'''主逻辑函数'''
log.debug('*' * 25 + '\n欢迎来到LuffyCity选课系统!\n' + '*' * 25)
username = input('请输入用户名: ').strip()
password = cn.changeHashlib(input('请输入密码:').strip())
flag = False
ident = None
for k, v in cn.readInfo(ss.student_file):
if username == k and password == v[1]:
ident = v[-1]
content = '%s用户%s登录成功!' % (ident, username)
log.debug(content)
log.info(content)
flag = True
break
else:
log.warning('%s用户登录失败!' % username)
if flag: # flag为真表示登录成功
cls = getattr(sys.modules['core.%s' % ident.lower()], ident)
obj = cls(username)
while True:
for index, opt in enumerate(cls.opt_lst, 1): print('\033[35;1m%s、%s\033[0m' % (index, opt[0]))
try:
num = int(input('请选择要操作的序号:'))
getattr(obj, cls.opt_lst[num - 1][1])()
except ValueError as e:
log.error('%s不是效数字!!' % e)
except IndexError as e:
log.error('%s\n请输入有效数字!!' % e)
log.debug('*' * 25 + '\n3秒后自动跳转回主页面!')
time.sleep(3)
main.py
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:42
import shelve
import hashlib
class Common:
'''公共类'''
def __init__(self):
pass
@staticmethod
def writeInfo(file,name,content):
'''写入信息'''
with shelve.open(file,writeback=True) as s:
s[name] = content
@staticmethod
def readInfo(file):
'''读取信息'''
with shelve.open(file,writeback=True) as s:
for key, value in s.items():
yield key, value # 返回生成器,节省内存
@staticmethod
def changeHashlib(password):
'''将明文转换成密文'''
md5 = hashlib.md5()
md5.update(password.encode('utf-8'))
ret = md5.hexdigest()
return ret
common.py
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:34
class Course:
def __init__(self,name,price,period):
self.name = '*'* 25 + '\n课程名称:' + name
self.price = '课程价格:' + price
self.period = '课程周期:' + period
course.py
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:34
import os
from core.common import Common as cn
from core.log import Log as log
from core import course as cs
from conf import settings as ss
class Manager:
opt_lst = [('创建学生', 'createStudent'), ('创建课程', 'createCourse'), ('查看所有学生', 'showStudents'),
('查看所有课程', 'showCourse'),('查看学生所选课程', 'showStudentCourse'), ('退出', 'quit')]
def __init__(self, name):
self.name = name
def __createInfo(self,file,kind):
'''创建信息'''
while True:
name = input('请输入%s名称:' % kind).strip()
for k, v in cn.readInfo(file):
if k == name:
log.warning('%s%s已存在!' % (name,kind))
break
else:
if kind == '课程':
pric = input('请输入课程价格:').strip()
period = input('请输入课程周期:').strip()
c = cs.Course(name, pric, period)
cn.writeInfo(ss.course_file, name, c)
else:
__password = cn.changeHashlib(input('请输入密码:').strip())
cn.writeInfo(ss.student_file, name, (name, __password, 'Student'))
conten = self.name + '创建%s%s成功!' % (name,kind)
log.debug(conten)
log.info(conten)
break
def createCourse(self):
'''创建课程'''
self.__createInfo(ss.course_file,'课程')
def createStudent(self):
'''创建学生账号'''
self.__createInfo(ss.student_file,'学生')
def showStudents(self):
'''查看所有学生'''
log.debug('*' * 25 + '\n所有的学生信息如下:\n' + '*' * 25)
for k, v in cn.readInfo(ss.student_file):
if v[-1] == 'Student': log.debug(k)
log.info(self.name + '查看了所有学生信息!')
def printInfo(self, file):
'''打印信息,利用列表推导式打印'''
[log.debug(t) for k, v in cn.readInfo(file) for s, t in v.__dict__.items()]
def showCourse(self):
'''查看所有课程'''
log.debug('*' * 25 + '\n所有课程信息如下:')
self.printInfo(ss.course_file)
log.info(self.name + '查看了所有课程信息!')
def showStudentCourse(self):
'''查看学生所选择的课程'''
log.info(self.name + '查看了所有学生选择的课程信息!')
dir_path = os.path.join(ss.db_path, 'choose_course')
for name in os.listdir(dir_path):
log.debug('*' * 25 + '\n%s选择的课程如下:' % name)
file_name = os.path.join(dir_path, name, 'choose_course_info')
self.printInfo(file_name)
def quit(self):
log.debug('谢谢使用!')
exit(-1)
manager.py
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/28 10:33
from core.common import Common as cn
from core.log import Log as log
from conf import settings as ss
class Student:
opt_lst = [('查看可选课程', 'showCourse'), ('选择课程', 'chooseCourse'),('查看已选课程','showSelectedCourse'),('退出','quit')]
def __init__(self,name):
self.name = name
self.courses = []
def showCourse(self):
'''查看可选课程'''
log.debug('*'*25 + '\n' + self.name+'可选的课程有:')
stu = list(cn.readInfo(ss.choose_course_file(self.name)))
for k,v in cn.readInfo(ss.course_file):
for s,t in stu:
if k == s:break
else:
for s, t in v.__dict__.items():log.debug(t)
log.info(self.name+'查看了可选课程!')
def chooseCourse(self):
'''选择课程'''
flag = True
while flag:
name = input('请选择课程:').strip()
for s, t in cn.readInfo(ss.choose_course_file(self.name)): # 已经选过的课程就不能重复选择了。
if name == s:
log.warning('您已经选过%s课程!请重新选择:' % name)
break
else:
for k,v in cn.readInfo(ss.course_file):
if name == k:
cn.writeInfo(ss.choose_course_file(self.name),name,v)
content = self.name + '选择课程%s成功!' % name
log.debug(content)
log.info(content)
flag = False
break
else:
log.warning('选择的%s课程不存在哦!请重新选择:' % name)
def showSelectedCourse(self):
'''查看已选课程'''
log.info(self.name+'查看了已选课程信息!')
[log.debug(t) for k,v in cn.readInfo(ss.choose_course_file(self.name)) for s,t in v.__dict__.items()]
def quit(self):
print('谢谢使用!')
exit(-1)
student.py
# -*- coding: utf-8 -*-
__author__ = 'caiqinxiong_cai'
# 2019/8/26 15:37
import logging
import sys
import time
from logging import handlers
from conf import settings as ss
class Log(object):
'''
https://cloud.tencent.com/developer/article/1354396
'''
now_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))
sh = logging.StreamHandler() # 既打印输入又写入文件
# rh = handlers.RotatingFileHandler(ss.log_file, maxBytes=1024,backupCount=5) # 按大小切换日志,保留5份
fh = handlers.TimedRotatingFileHandler(filename=ss.log_file, when='D', backupCount=5, interval=5,encoding='utf-8') # 按时间切割日志
logging.basicConfig(level=logging.WARNING, # 打印日志级别
handlers=[fh, sh],
datefmt='%Y-%m-%d %H:%M:%S',
format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s') # [%(lineno)d] 只显示当前文件的行号
@classmethod
def writeOnly(cls, content):
'''自定义函数,只写入日志文件'''
with open(ss.log_file, mode='a', encoding='utf-8') as f:
f.write(Log.now_time + '\t' + str(content) + '\n')
@classmethod
def readOnly(cls, content):
'''自定义函数,只打印日志'''
print('\033[36;1m%s\033[0m' % content)
@classmethod
def debug(cls, content):
# return logging.debug(content)
return Log.readOnly(content)
@classmethod
def info(cls, content):
# return logging.info(content)
return Log.writeOnly('[INFO]\t' + content) # info信息直接写入log文件
@classmethod
def warning(cls, content):
return logging.warning(content)
@classmethod
def error(cls, content):
# 获取调用函数的文件名和行数
head = '%s line%s error!\n' % (sys._getframe().f_back.f_code.co_filename, sys._getframe().f_back.f_lineno)
return logging.error(head + content)
@classmethod
def critical(cls, content):
head = '%s line%s critical!\n' % (sys._getframe().f_back.f_code.co_filename, sys._getframe().f_back.f_lineno)
return logging.critical(head + content)
log.py