需求:
可依次选择进入各子菜单 可从任意一层往回退到上一层 可从任意一层退出程序
数据结构
menu = {
\'北京\':{
\'海淀\':{
\'五道口\':{
\'soho\':{},
\'网易\':{},
\'google\':{}
},
\'中关村\':{
\'爱奇艺\':{},
\'汽车之家\':{},
\'youku\':{},
},
\'上地\':{
\'百度\':{},
},
},
\'昌平\':{
\'沙河\':{
\'北航\':{},
},
},
\'朝阳\':{},
\'东城\':{},
},
\'上海\':{
\'闵行\':{
"人民广场":{
\'炸鸡店\':{}
}
},
\'闸北\':{
\'火车战\':{
\'携程\':{}
}
},
\'浦东\':{},
},
\'山东\':{},
}
代码:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
new_menu = menu list = [] while 1 : print ( \'-----menu-----\' ) for i in new_menu: print (i) user_input = input ( \'输入名称进入下一栏,或输入r/R回到上一栏,或输入q/Q退出程序:\' ).strip() #strip:移除输入中的空格 if not new_menu: continue if user_input in new_menu: list .append(new_menu) #进入下一层之前记录当前层 new_menu = new_menu[user_input] #进入下一层 elif user_input = = \'r\' or user_input = = \'R\' : if len ( list ) ! = 0 : new_menu = list .pop() #将上一级菜单弹出赋值给new_menu! else : print ( \'没有栏目了\' ) elif user_input = = \'q\' or user_input = = \'Q\' : print ( \'退出程序!\' ) exit() |
\'\'\'
需求:
1、启动程序后,输入用户名密码后,让用户输入工资,然后打印商品列表 2、允许用户根据商品编号购买商品 3、用户选择商品后,检测余额是否够,够就直接扣款,不够就提醒 4、可随时退出,退出时,打印已购买商品和余额 5、在用户使用过程中, 关键输出,如余额,商品已加入购物车等消息,需高亮显示
6、用户下一次登录后,输入用户名密码,直接回到上次的状态,即上次消费的余额什么的还是那些,再次登录可继续购买
说明:运行此程序需要自己再在相同的目录里新建balance.txt与shopping_car.txt文件分别存放余额与所购物品
\'\'\'
#源代码
#登陆用户名及密码 username = \'whw\' password = \'123\' #商品列表 goods = [ {"name": "电脑", "price": 1999}, {"name": "鼠标", "price": 10}, {"name": "游艇", "price": 20}, {"name": "美女", "price": 998}, {\'name\':\'1080ti\',\'price\':2222}, {\'name\':\'机械键盘\',\'price\':555}, {\'name\':\'《西游记》\',\'price\':56}, {\'name\':\'固态硬盘\',\'price\':666} ] #若用户名密码不正确直接退出系统 print(\'-------------用户登陆----------------\') input_user = input(\'请输入用户名:\') input_pass = input(\'请输入密码:\') if input_user != username or input_pass != password: print(\'\033[31;1m很遗憾登陆失败\033[0m\') exit() #用户名及密码正确后进行接下来的操作 print(\'\033[32;1m登陆成功!\033[0m\') #在balance.txt 与 shopping_car.txt 中找之前的记录 file_balance = open(\'balance.txt\',\'r\') file_balance_data = file_balance.read() #注意要把文件读取第一次的值赋给变量,后面不要再次进行read()操作了! if file_balance_data != \'\': #balance文件中如果有记录说明之前购买过东西 #print(\'原来的余额:\',file_balance_data) wages = int(file_balance_data) #利用上次的余额赋给wages #上次购买的购物车的物品 file_shopping_car = open(\'shopping_car.txt\',\'r\') shopping_car_old = file_shopping_car.read() print(\'\033[32;3m-----您的购物车共有以下商品-----\033[0m\') print(shopping_car_old) #直接打印即可 print(\'\033[32;3m您上次购买后的余额为:%d\033[0m\' % wages) #若没之前的记录就输入工资新开始 else: wages = input(\'请输入工资:\')#不建议直接int(),如果输入字符就会报错,需先用isdigit()方法判断下 if wages.isdigit():#isdigit方法 判断是否输入的全是数字 wages = int(wages) else: print(\'\033[32;3m抱歉您输入了错误的字符,程序退出!\033[0m\') exit() shopping_car = [] while 1: print(\'-----商品列表-----\') for i,v in enumerate(goods): print(i,":",v) print(\'-----可进行的操作-----\') print(\'一:输入相应的商品编号购买商品\') print(\'二:输入Q/q以退出程序\') choice = input(\'请输入要购买的商品编号或要进行的操作:\') #===========购买===================== if choice.isdigit(): #isdigit()方法 if 0 <= int(choice) < len(goods): #先确认在编号范围 if goods[int(choice)].get(\'price\') <= wages:#工资不得少于所选商品的价格 wages -= goods[int(choice)].get(\'price\') shopping_car.append(goods[int(choice)]) print(\'\033[32;3m商品 %s 已添加进购物车!\033[0m\' % goods[int(choice)])#将商品添加进购物车 print(\'\033[31;3m您的余额为:%d\033[0m \' % wages) else: print(\'\033[31;3m对不起,您的余额不足以购买该商品\033[0m\') else: print(\'\033[31;3m请输入正确的商品编号或操作编号\033[0m\') #=========退出,打印已购买的商品并显示余额,并将余额与购物车物品写到文件里=========================== elif choice ==\'q\' or choice == \'Q\': print(\'\033[32;3m-----您已购买以下商品-----\033[0m\') for index,k in enumerate(shopping_car): print(index,\':\',k) print(\'\033[32;3m账户余额为:%d\033[0m\'% wages) #余额存到balance.txt中,购物车存到shopping_car.txt中 file1 = open(\'balance.txt\', \'w\') #file1.truncate() # 因为\'w\'方式本身可以清空原来的内容,故不用清空原有的余额 file1.write(str(wages))#将新的余额信息写进去 file1.close() file2 = open(\'shopping_car.txt\',\'a\') file2.write(str(shopping_car)) file2.close() break else: print(\'\033[31;3m请输入正确的操作编号!\033[0m\')
需求:
让用户输入用户名密码 认证成功后显示欢迎信息 输错三次后退出程序
可以支持多个用户登录 (提示,通过列表存多个账户信息) 用户3次认证失败后,退出程序,再次启动程序尝试登录时,还是锁定状态(本程序将用户锁定的状态存到文件里)
代码:(需再建立一个txt文件存放锁定状态)
username_password = [[\'whw1\',\'whw11\'],[\'whw2\',\'whw22\'],[\'whw3\',\'whw33\'],[\'whwm\',\'whwmm\']] #列表存储用户名及密码 #程序执行之前先教研whw.txt,如果之前锁定登陆了就直接提示锁定并quit() file_over = open(\'whw.txt\', mode=\'r\') if file_over.read() == \'哈哈,没机会啦\': print(\'系统已被锁定\') quit() count = 1 #计数器 input_user = input(\'请输入用户名:\') input_pass = input(\'请输入密码:\') #将输入的用户名密码放到列表中 user_input = [input_user,input_pass] while count <3: count +=1 if user_input in username_password:#判断用户名及密码是否匹配 print(\'恭喜您登陆成功!\') break else: input_user = str(input(\'输入错误,请再次输入用户名:\')) input_pass = str(input(\'请再次输入密码:\')) user_input = [input_user, input_pass] if user_input in username_password: print(\'恭喜您登陆成功!\') break else: #while..else语句:三次都输入错误后提示登陆失败并且将需要锁定程序的信息写到whw.txt文件里 file1 = open(\'whw.txt\', mode=\'w\') file1.write(\'哈哈,没机会啦\') file1.close() print(\'很遗憾登陆失败!\')
在Python3中我们要实现将本地文件homework.txt中的内容的修改操作时,大体的思路是这样的:先将homework.txt文件的内容读取到内存中,在内存中对里面的数据进行修改,接着将修改完成后的数据写到一个新文件(取名为:homework.txt.new)里。此时homework.txt.new文件里装着我们修改后的数据,但homework.txt文件中仍然存着旧的未修改的数据。要想在homework.txt中存放修改后的数据,可以这样实现:
一:在Mac操作系统下
利用os模块的rename方法即可实现:
1
2
|
import os os.rename(‘homework.txt.new’,’homework.txt’) |
二:在Windows操作系统下:
方法一:
利用replace方法:
1
2
|
import os os.replace(‘homework.txt.new’,’ homework.txt’) |
方法二:
删掉源文件homework.txt ,然后将homework.txt.new重命名成 homework.txt
1
2
3
|
import os os.remove(‘homework.txt’) os.rename(‘homework.txt.new’,’homework.txt’) |
三:特别注意,不可以在Windows系统下直接使用rename方法,会报错:
一:需求
homework.txt文件中有如下格式的人员信息:
1,Jack Wang,28,13451024608,HR,2015‐01‐07
2,Rain Wang,21,13451054608,IT112,2017‐04‐01
3,Mack Qiao,44,15653354208,Sales,2016‐02‐01
4,Rachel Chen,23,13351024606,IT112,2013‐03‐16
5,Eric Liu,19,18531054602,Marketing,2012‐12‐01
6,Chao Zhang,21,13235324334,Administration,2011‐08‐08
7,Kevin Chen,22,13151054603,Sales,2013‐04‐01
8,Shit Wen,20,13351024602,IT112,2017‐07‐03
9,Shanshan Du,26,13698424612,Operation,2017‐07‐02
10, whw,25,185310546502,IT,2015‐10‐29
11, wh3w,26,185310544602,IT,2015‐10‐29
对应的Key值为:[\'id\',\'name\',\'age\',\'phone\',\'dept\',\'enrolled_date\']
要求实现基本的增删改查功能,并且数据需要实时更新~
find name,age from homework where age > 22
find * from homework where age > 22
del from homework where id = 2
update homework set dept=IT11 where dept = IT
add homework whw,25,18531054602,IT,2015‐10‐29(如果有相同的Phone值提示重复,不可以增加)
二、这里直接上代码~~需要交流请站内信~
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
|
#说明:为了消除add后再find时不会出现新增的条目的问题,将load_db()方法分别写入了各函数中,为的就是要实现数据的实时更新 import os DB_FILE = \'homework.txt\' colums = [ \'id\' , \'name\' , \'age\' , \'phone\' , \'dept\' , \'enrolled_date\' ] #字典data的键 #提示加粗 def print_log(msg,log_type = \'info\' ): if log_type = = \'info\' : print (msg) elif log_type = = \'error\' : print ( \'\033[31;1m %s\033[0m\' % msg) def load_db(db_file): \'\'\' 加载员工信息并转成指定的格式 :return: \'\'\' data = {} #先定义一个空字典 for i in colums: data[i] = [] #空字典每个键对应一个空列表,放具体值 f = open (db_file, \'r\' ,encoding = \'gb18030\' ,errors = \'ignore\' ) #gb18030比gbk多 (日期的 - 字符需要改正) for line in f: staff_id,name,age,phone,dept,enrolled_date = line.split( \',\' ) #利用split()方法 每隔一个逗号分隔文件内容,并将值赋给临时变量 data[ \'id\' ].append(staff_id) data[ \'name\' ].append(name) data[ \'age\' ].append(age) data[ \'phone\' ].append(phone) data[ \'dept\' ].append(dept) data[ \'enrolled_date\' ].append(enrolled_date) #临时变量的值追加到colums中 f.close() return data #自定义分隔出的右半部分的取值操作方式: #大于 def op_gt(column,condition_val): \'\'\' :param column: eg.age :param condition_val:eg.22 :return:[[id,name,age,...]] 返回一个输入的键组成的列表 \'\'\' staff_data = load_db( \'homework.txt\' ) matched_records = [] #符合条件的人员信息的拼起来的列表,且顺序也不能错 for index,val in enumerate (staff_data[column]): #枚举 if float (val) > float (condition_val): #将字符串转换为数字,匹配上了 #print(\'match:\',val) 打印符合条件的“年龄值” record = [] for col in colums: record.append(staff_data[col][index]) #按顺序将符合匹配的数据加进去,放到临时的小列表中 matched_records.append(record) #将组合好的小列表加到大列表中去,得到的是符合条件的每个人的信息 #print(\'matched records:\',matched_records) #打印符合条件的人员信息,大列表嵌套小列表的形式 return matched_records #小于 def op_lt(column,condition_val): \'\'\' :param column: eg.age :param condition_val:eg.22 :return:[[id,name,age,...]] 返回一个输入的键组成的列表 \'\'\' staff_data = load_db( \'homework.txt\' ) matched_records = [] # 符合条件的人员信息的拼起来的列表,且顺序也不能错 for index, val in enumerate (staff_data[column]): # 枚举 if float (val) < float (condition_val): # 将字符串转换为数字,匹配上了 # print(\'match:\',val) 打印符合条件的“年龄值” record = [] for col in colums: record.append(staff_data[col][index]) # 按顺序将符合匹配的数据加进去,放到临时的小列表中 matched_records.append(record) # 将组合好的小列表加到大列表中去,得到的是符合条件的每个人的信息 # print(\'matched records:\',matched_records) #打印符合条件的人员信息,大列表嵌套小列表的形式 return matched_records #等于 def op_eq(column,condition_val): \'\'\' :param column: eg.age :param condition_val:eg.22 :return:[[id,name,age,...]] 返回一个输入的键组成的列表 \'\'\' staff_data = load_db( \'homework.txt\' ) matched_records = [] # 符合条件的人员信息的拼起来的列表,且顺序也不能错 for index, val in enumerate (staff_data[column]): # 枚举 age if val = = condition_val: # 匹配上了 # print(\'match:\',val) 打印符合条件的“年龄值” record = [] for col in colums: record.append(staff_data[col][index]) # 按顺序将符合匹配的数据加进去,放到临时的小列表中 matched_records.append(record) # 将组合好的小列表加到大列表中去,得到的是符合条件的每个人的信息 # print(\'matched records:\',matched_records) #打印符合条件的人员信息,大列表嵌套小列表的形式 return matched_records #like def op_like(column,condition_val): \'\'\' :param column: eg.age :param condition_val:eg.22 :return:[[id,name,age,...]] 返回一个输入的键组成的列表 \'\'\' staff_data = load_db( \'homework.txt\' ) matched_records = [] # 符合条件的人员信息的拼起来的列表,且顺序也不能错 for index, val in enumerate (staff_data[column]): # 枚举 if condition_val in val: # 匹配上了 # print(\'match:\',val) 打印符合条件的“年龄值” record = [] for col in colums: record.append(staff_data[col][index]) # 按顺序将符合匹配的数据加进去,放到临时的小列表中 matched_records.append(record) # 将组合好的小列表加到大列表中去,得到的是符合条件的每个人的信息 # print(\'matched records:\',matched_records) #打印符合条件的人员信息,大列表嵌套小列表的形式 return matched_records def syntax_where(clause): #clause是where右边的部分 \'\'\' 解析where条件,并过滤数据 :param clause: 比如:age>22 :return:matched_data \'\'\' #也可以为每种情况定义一种方式: #column,operator,condition = clause.split(\'>\')或者column,operator,condition = clause.split(\'<\')...... operators = { \'>\' :op_gt, \'<\' :op_lt, \'=\' :op_eq, \'like\' :op_like, } for op_key,op_func in operators.items(): #op_key为符号< > 等,op_func为函数的内存地址 if op_key in clause: column,val = clause.split(op_key) #按照符号分割:age 22 matched_data = op_func(column.strip(),val.strip()) #真正去查询数据 return matched_data else : #在for执行完成且没有中间被break的情况下 才执行,也就是说没有匹配上任何的条件公式 print_log( \'语法错误:where条件只能支持[>,<,=,like]\' , \'error\' ) #find方法 只是查找 def syntax_find(data_set,left): #data_set里就是matched_data中的内容 \'\'\' 解析查询语句,并从deta_set中打印指定的列 :param data_set: eg.[\'1\', \'Alex Li\', \'22\', \'13651054608\', \'IT\', \'2013-04-01\n\'], [\'3\', \'Rain Wang\', \'21\', \'13451054608\', \'IT\', \'2017-04-01\n\']] :param left: find name,age from homework #find分一次 from分一次 :return: \'\'\' filter_cols_tmp = left.split( \'from\' )[ 0 ][ 4 :].split( \',\' ) #先按照from分,然后按照find分,找到关键字 filter_cols = [i.strip() for i in filter_cols_tmp] #过滤空格 干净的columns 去掉关键字的空格 可以只打印指定关键字的列 if \'*\' in filter_cols[ 0 ]: for i in data_set: print (i) print ( \'成功查询到%s条数据\' % len (data_set)) else : reformat_data_set = [] for row in data_set: filter_vals = [] #把要打印的字段放在列表中 for col in filter_cols: col_index = colums.index(col) #通过colums拿到关键字列的索引值,依据次取出每条记录里对应的索引的值 filter_vals.append(row[col_index]) reformat_data_set.append(filter_vals) for i in reformat_data_set: print (i) print ( \'成功查询到%s条数据\' % len (data_set)) #del方法 def syntax_delete(data_set,left): \'\'\' :param data_set: eg.[\'1\', \'Alex Li\', \'22\', \'13651054608\', \'IT\', \'2013-04-01\n\'] :param left: del from homework where id =1 :return: \'\'\' for matched_row in data_set: staff_id = matched_row[ 0 ].strip() #找到id值 f = open ( \'homework.txt\' , \'r\' ,encoding = \'gb18030\' ,errors = \'ignore\' ) f1 = open ( \'homework_new.txt\' , \'w\' ,encoding = \'gb18030\' ,errors = \'ignore\' ) for line in f: in_list = line.split( \',\' ) if in_list[ 0 ] < staff_id: f1.write(line) elif in_list[ 0 ] > staff_id: in_list[ 0 ] = str ( int (in_list[ 0 ]) - 1 ) f1.write( \',\' .join(in_list)) else : continue f.close() f1.close() os.replace( \'homework_new.txt\' , \'homework.txt\' ) print ( \'删除%s条记录!\' % len (data_set)) #update方法 def syntax_update(data_set,left): \'\'\' :param data_set: 与find一样 eg.[\'1\', \'Alex Li\', \'22\', \'13651054608\', \'IT\', \'2013-04-01\n\'] :param left: update homework set dept=IT11 where dept = IT :return: \'\'\' staff_data = load_db( \'homework.txt\' ) formula_raw = left.split( \'set\' ) if len (formula_raw) > 1 : # 有set关键字 col_name, new_val = formula_raw[ 1 ].strip().split( \'=\' ) # age = 25 col_name里是age,new_val 里是25 col_index = colums.index(col_name) # 在coluns中找到对应关键字的索引 # 循环data_set,取到每条记录的ID,拿着这个ID到STAFF_DATA[\'id\']里找对应的id的索引,拿到索引去STAFF_DATA[\'age\']列表里,改对应索引的值 for matched_row in data_set: staff_id = matched_row[ 0 ] staff_id_index = staff_data[ \'id\' ].index(staff_id) staff_data[col_name][staff_id_index] = new_val # !!把修改后的数据存到硬盘上 f1 = open ( \'%s.new\' % DB_FILE, \'w\' , encoding = \'gb18030\' , errors = \'ignore\' ) for i,v in enumerate (staff_data[ \'id\' ]): row = [] for col in colums: row.append(staff_data[col][i]) f1.write( \',\' .join(row)) f1.close() os.replace( \'homework.txt.new\' , \'homework.txt\' ) #save_db() print ( \'成功修改了%s条数据\' % len (data_set)) else : print_log( \'语法错误:未检测到set关键字\' , \'error\' ) #add 方法 def syntax_add(data_set,left): \'\'\' 总体思路是先将left字符串按照homework split 切割成两部分,第一部分改成id 后一部分不变,这样就变成了想要的格式,在join 最后写进去新文件就行! :param data_set: 整个表 :param left: 装的是完整的 add homework whw,25,18531054602,IT,2015‐10‐29 :return: \'\'\' while 1 : #add方法中,为了获得最新的行数的信息,必须每增加一次前打开最新的txt文件以获取最新的行数: staff_data = load_db( \'homework.txt\' ) cmd_add_list = left.strip().split( \'homework\' ) #[\'8\', \' whw,25,134435344,IT,2015‐10‐29\'] cmd_add_list[ 0 ] = str ( len (staff_data[ \'phone\' ]) + 1 ) #print(cmd_add_list) add = \',\' .join(cmd_add_list) #add 里 就是我们想要的最后添加进去的字符串 s = cmd_add_list[ 1 ].split( \',\' ) #s 里是:[\' whw\', \'25\', \'134435344\', \'IT\', \'2015‐10‐29\'] if s[ 2 ].strip() in staff_data[ \'phone\' ]: print ( \'记录中已经有重复的手机号,请重新输入\' ) break else : f = open ( \'homework.txt\' , \'a\' , encoding = \'gb18030\' , errors = \'ignore\' ) #a模式 f.write( \'\n\' ) f.write(add) f.close() print ( \'增加了1条记录!\' ) break def syntax_parser(cmd): \'\'\' 解析语句并执行,是否合法 :param cmd: :return: \'\'\' syntax_list = { \'find\' : syntax_find, \'del\' : syntax_delete, \'update\' : syntax_update, \'add\' : syntax_add } staff_data = load_db( \'homework.txt\' ) if cmd.split()[ 0 ] in ( \'find\' , \'add\' , \'del\' , \'update\' ): if \'where\' in cmd: #含where语句的 left,right = cmd.split( \'where\' ) #用split方法将语句按照where切割成左右两个部分! #print(left,right) #中途打印 查看where前后部分用split断开了 matched_record = syntax_where(right) #找到右边的 else : #不包含where语句的 matched_record = [] for index,staff_id in enumerate (staff_data[ \'id\' ]): record = [] for col in colums: record.append(staff_data[col][index]) matched_record.append(record) left = cmd cmd_action = cmd.split()[ 0 ] #注意去掉空格 if cmd_action in syntax_list: syntax_list[cmd_action](matched_record,left) #匹配上了 else : print_log( \'语法错误:\n[find\\add\del\\update] from [colum...] from [homework] [where] [name...] [colum] [>/</=/like] [...] \' , \'error\' ) def main(): \'\'\' 让用户输入语句,并执行 :return: \'\'\' while 1 : cmd = input ( \'staff_db:\' ).strip() if not cmd: continue #如果为空 继续 syntax_parser(cmd.strip()) #传入值得时候讲空格去掉 #开始执行程序 if __name__ = = "__main__" : #仅在本模块运行main(),其他模块调用的时候不用启动 main() |
whw.txt文件中有一下内容:
张三 13333333333
小李 15555555555
王二麻 12222222222
编写程序实现文件内容的修改:
方法一:占硬盘的修改方式(需要新建一个文件)
import os f_name = \'whw.txt\' f_new_name = \'%s.new\' % f_name old_str = \'张三\' new_str = \'张啊啊\' f = open(f_name,\'r\',encoding=\'utf-8\') #注意编码方式 f1 = open(f_new_name,\'w\',encoding=\'utf-8\') for line in f:#遍历旧文件 if old_str in line:#如果旧文件里有需要替换的内容 line = line.replace(old_str,new_str) #没用到os模块,将就内容替换为新内容 f1.write(line)#将“新内容写进新的文件中去” f.close() f1.close() os.replace(f_new_name,f_name)#用到了os模块,将旧文件替换为新文件
方法二:占内存的修改方式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
import os f_name = \'whw.txt\' f_new_name = \'%s.new\' % f_name old_str = \'王二麻\' new_str = \'王二\' f = open (f_name, \'r\' ,encoding = \'utf-8\' ) f1 = open (f_new_name, \'w\' ,encoding = \'utf-8\' ) #与占硬盘的方法不同的是,占内存的方法是将文件内容一次性的读出来,然后进行判断和替换 data = f.read() if old_str in data: data = data.replace(old_str,new_str) f1.write(data) f.close() f1.close() os.replace(f_new_name,f_name) |
斐波那契数列的形式为:1,1,2,3,5,8,13,21......从第三项开始,后面的每一项都是前面两项的和。
实现的方式有一下 两种:
一:递归方式实现
def fib(n): if n <1: print(\'数值错误!\') return -1 if n ==1 or n ==2: return 1 return fib(n-1) + fib(n-2) f = fib(10) print(f)
当然这种方式的输出为55,是直接计算出某一项的数值的。
二:简单的赋值语句逻辑实现
def fib(max): n,a,b = 0,0,1 while n < max: print(b) a,b = b,a+b n += 1 fib(10)
这种方式输出为:1,1,2,3,5,8,13,21,34,55。可以看到中间值,当然也可以在while结束后只返回最终值。
一、功能介绍(第6条未实现)
模拟实现一个ATM + 购物商城程序
1额度15000或自定义
2实现购物商城,买东西加入购物车,调用信用卡接口结账
3可以提现,手续费5%
4支持多账户登录
5支持账户间转账
6记录每月日常消费流水
7提供还款接口
8ATM记录操作日志
9提供管理接口,包括添加账户、用户额度,冻结账户等。。。
10用户认证用装饰器
二、实现流程图
三、程序目录结构
ATM_WHW
├── whw_atm
├── README.txt
├── atm #入口程序目录
│ ├── __init__.py
│ └── main.py #入口程序(启动程序)
├── conf #配置文件目录
│ ├── __init__.py
│ └── setting.py #里面包含日志的相关设置
├── logics #程序核心逻辑目录
│ ├── __init__.py
│ ├── admin_opera.py #管理员模块(用户名与密码均是:admin)
│ ├── authentication.py #认证模块,实现三种不同的登录模式
│ ├── creditcard_opera.py #信用卡操作模块
│ ├── shoppingmall.py #购物商城模块
│ ├── logger_opera.py #日志实现逻辑模块
├── db #程序所用到的静态数据(今后会是数据库的动态数据操作)
│ ├── creditcard_dict #信用卡信息
│ ├── productlist #商城产品信息
│ └── shopping_car #购物车信息
│ └── users_dict #用户信息
└── logs
├── __init__.py
└── access.log #记录操作日志
└── transactions.log #记录信用卡相关日志
四、具体模块代码
1.main.py
import os import sys from logics import authentication,shoppingmall,creditcard_opera,admin_opera #程序主目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #为程序添加环境变量 sys.path.append(BASE_DIR) while 1: message = \'\'\' 1: 购物中心 2: 信用卡中心 3: 账户及信用卡管理 q: 退出系统 \'\'\' print(\'欢迎进入信用卡及购物管理系统\'.center(30,\'#\')) print(message) choice = input(\'请输入您想操作的编号:\') if not choice or choice not in [\'1\',\'2\',\'3\',\'q\']: print(\'请输入正确的编号!!!\') continue if choice == \'1\': res = authentication.user_auth() if res != None: if res[0] == "True": current_user = res[1]#当前用户名 shoppingmall.clear_shopping_car() while 1: print(\'欢迎进入购物中心\'.center(30,\'#\'), \'\n1:购物商场\n\' \'2:查看购物车\n\' \'3:购物结算\n\' \'4:个人中心\n\' \'b:返回\n\' ) choice = input(\'请输入要进行操作的对应编号:\') if choice == \'1\': shoppingmall.shopping_mall() elif choice == \'2\': shoppingmall.shopping_car() elif choice == \'3\': shoppingmall.shopping_pay(current_user) elif choice == \'4\': while 1: print(\'欢迎进入个人中心\'.center(30,\'^\'), \'\n1:绑定信用卡\n\' \'2:修改登陆密码\n\' \'b:返回上一级菜单\' ) choice = input(\'请输入对应操作的编号:\') if choice == \'b\': break elif choice == \'1\': shoppingmall.creditcard_linked(current_user) elif choice == \'2\': shoppingmall.revise_password(current_user) else: print(\'请输入正确的编号!\') elif choice == \'b\': break elif choice == \'2\': res = authentication.creditcard_auth() ############################################### if res != None: if res[0] == \'True\': current_creditcard = res[1] while 1: print(\'欢迎进入信用卡中心\'.center(30,\'#\'), \'\n1:信用卡信息\n\' \'2:提现\n\' \'3:转账\n\' \'4:还款\n\' \'b:返回\') choice_c = input(\'请输入您要进行的操作代码:\') if choice_c not in [\'1\',\'2\',\'3\',\'4\',\'b\'] or not choice_c: print(\'请输入正确的编号!\') continue elif choice_c == \'b\': break elif choice_c == \'1\': creditcard_opera.creditcard_msg(current_creditcard) elif choice_c == \'2\': creditcard_opera.creditcard_cash(current_creditcard) elif choice_c == \'3\': creditcard_opera.creditcard_transfer(current_creditcard) elif choice_c == \'4\': creditcard_opera.creditcard_payback(current_creditcard) elif choice == \'3\': res = authentication.admin_auth() if res != None: while 1: print(\'管理员中心\'.center(30,\'#\'), "\n1:创建账号\n" "2:锁定账号\n" "3:解锁账号\n" "4:新建信用卡\n" "5:冻结信用卡\n" "6:解冻信用卡\n" "b:返回" ) choice = input(\'请输入要进行的操作编号:\') if not choice or choice not in [\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'b\']: print(\'请输入正确的编号!\') continue elif choice == \'b\': break elif choice == \'1\': admin_opera.create_user() elif choice == \'2\': admin_opera.user_locked() elif choice == \'3\': admin_opera.user_unlock() elif choice == \'4\': admin_opera.create_creditcard() elif choice == \'5\': admin_opera.lock_creditcard() elif choice == \'6\': admin_opera.unlock_creditcard() elif choice == \'q\': print(\'退出程序!\') exit()
import os import sys from logics import authentication,shoppingmall,creditcard_opera,admin_opera #程序主目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #为程序添加环境变量 sys.path.append(BASE_DIR) while 1: message = \'\'\' 1: 购物中心 2: 信用卡中心 3: 账户及信用卡管理 q: 退出系统 \'\'\' print(\'欢迎进入信用卡及购物管理系统\'.center(30,\'#\')) print(message) choice = input(\'请输入您想操作的编号:\') if not choice or choice not in [\'1\',\'2\',\'3\',\'q\']: print(\'请输入正确的编号!!!\') continue if choice == \'1\': res = authentication.user_auth() if res != None: if res[0] == "True": current_user = res[1]#当前用户名 shoppingmall.clear_shopping_car() while 1: print(\'欢迎进入购物中心\'.center(30,\'#\'), \'\n1:购物商场\n\' \'2:查看购物车\n\' \'3:购物结算\n\' \'4:个人中心\n\' \'b:返回\n\' ) choice = input(\'请输入要进行操作的对应编号:\') if choice == \'1\': shoppingmall.shopping_mall() elif choice == \'2\': shoppingmall.shopping_car() elif choice == \'3\': shoppingmall.shopping_pay(current_user) elif choice == \'4\': while 1: print(\'欢迎进入个人中心\'.center(30,\'^\'), \'\n1:绑定信用卡\n\' \'2:修改登陆密码\n\' \'b:返回上一级菜单\' ) choice = input(\'请输入对应操作的编号:\') if choice == \'b\': break elif choice == \'1\': shoppingmall.creditcard_linked(current_user) elif choice == \'2\': shoppingmall.revise_password(current_user) else: print(\'请输入正确的编号!\') elif choice == \'b\': break elif choice == \'2\': res = authentication.creditcard_auth() ############################################### if res != None: if res[0] == \'True\': current_creditcard = res[1] while 1: print(\'欢迎进入信用卡中心\'.center(30,\'#\'), \'\n1:信用卡信息\n\' \'2:提现\n\' \'3:转账\n\' \'4:还款\n\' \'b:返回\') choice_c = input(\'请输入您要进行的操作代码:\') if choice_c not in [\'1\',\'2\',\'3\',\'4\',\'b\'] or not choice_c: print(\'请输入正确的编号!\') continue elif choice_c == \'b\': break elif choice_c == \'1\': creditcard_opera.creditcard_msg(current_creditcard) elif choice_c == \'2\': creditcard_opera.creditcard_cash(current_creditcard) elif choice_c == \'3\': creditcard_opera.creditcard_transfer(current_creditcard) elif choice_c == \'4\': creditcard_opera.creditcard_payback(current_creditcard) elif choice == \'3\': res = authentication.admin_auth() if res != None: while 1: print(\'管理员中心\'.center(30,\'#\'), "\n1:创建账号\n" "2:锁定账号\n" "3:解锁账号\n" "4:新建信用卡\n" "5:冻结信用卡\n" "6:解冻信用卡\n" "b:返回" ) choice = input(\'请输入要进行的操作编号:\') if not choice or choice not in [\'1\',\'2\',\'3\',\'4\',\'5\',\'6\',\'b\']: print(\'请输入正确的编号!\') continue elif choice == \'b\': break elif choice == \'1\': admin_opera.create_user() elif choice == \'2\': admin_opera.user_locked() elif choice == \'3\': admin_opera.user_unlock() elif choice == \'4\': admin_opera.create_creditcard() elif choice == \'5\': admin_opera.lock_creditcard() elif choice == \'6\': admin_opera.unlock_creditcard() elif choice == \'q\': print(\'退出程序!\') exit()
2.setting.py
import os,logging BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_LEVEL = logging.INFO LOG_TYPES = { \'transaction\':\'transactions.log\', \'access\':\'access.log\' } LOG_PATH = os.path.join(BASE_DIR,\'logs\') LOG_FORMAT = logging.Formatter(\'%(asctime)s - %(name)s - %(levelname)s - %(message)s\' )
import os,logging BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) LOG_LEVEL = logging.INFO LOG_TYPES = { \'transaction\':\'transactions.log\', \'access\':\'access.log\' } LOG_PATH = os.path.join(BASE_DIR,\'logs\') LOG_FORMAT = logging.Formatter(\'%(asctime)s - %(name)s - %(levelname)s - %(message)s\' )
3.db文件夹中的内容(存放的都是静态数据)
(1)creditcard_dict.json
{"666666": {"personinfo": "lisi", "password": "123", "limit": 2569, "locked": 0, "limitcash": 7500, "creditcard": "666666"}, "123456": {"personinfo": "whw", "password": "123", "limit": 9807.45, "locked": 0, "limitcash": 7500, "creditcard": "123456"}, "888888": {"personinfo": "zhangsan", "password": "123", "limit": 11313, "locked": 0, "limitcash": 7500, "creditcard": "888888"}, "654321": {"personinfo": "zhaosi", "password": "123", "limit": 14478, "locked": 0, "limitcash": 7500, "creditcard": "654321"}, "777777": {"personinfo": "wangwu", "password": "123", "limit": 14288, "locked": 0, "limitcash": 7500, "creditcard": "777777"}, "000000": {"personinfo": "wanghw", "password": "123", "limit": 11001, "locked": 0, "limitcash": 7500, "creditcard": "000000"}, "111111": {"personinfo": "fff", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "111111"}, "785458": {"personinfo": "ttt", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "785458"}, "999999": {"personinfo": "uuu", "password": "123", "limit": 14334, "locked": 0, "limitcash": 7500, "creditcard": "999999"}, "222222": {"personinfo": "ooo", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "222222"}, "909090": {"personinfo": "blank", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "909090"}}
{"666666": {"personinfo": "lisi", "password": "123", "limit": 2569, "locked": 0, "limitcash": 7500, "creditcard": "666666"}, "123456": {"personinfo": "whw", "password": "123", "limit": 9807.45, "locked": 0, "limitcash": 7500, "creditcard": "123456"}, "888888": {"personinfo": "zhangsan", "password": "123", "limit": 11313, "locked": 0, "limitcash": 7500, "creditcard": "888888"}, "654321": {"personinfo": "zhaosi", "password": "123", "limit": 14478, "locked": 0, "limitcash": 7500, "creditcard": "654321"}, "777777": {"personinfo": "wangwu", "password": "123", "limit": 14288, "locked": 0, "limitcash": 7500, "creditcard": "777777"}, "000000": {"personinfo": "wanghw", "password": "123", "limit": 11001, "locked": 0, "limitcash": 7500, "creditcard": "000000"}, "111111": {"personinfo": "fff", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "111111"}, "785458": {"personinfo": "ttt", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "785458"}, "999999": {"personinfo": "uuu", "password": "123", "limit": 14334, "locked": 0, "limitcash": 7500, "creditcard": "999999"}, "222222": {"personinfo": "ooo", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "222222"}, "909090": {"personinfo": "blank", "password": "123", "limit": 15000, "locked": 0, "limitcash": 7500, "creditcard": "909090"}}
(2)publiclist.json
Computer 2299 1080Ti 3999 keyboard 999 Cookbook 199 MATE10 3999 Beauty 1099 Dragon 666
Computer 2299 1080Ti 3999 keyboard 999 Cookbook 199 MATE10 3999 Beauty 1099 Dragon 666
(3)shoppingcar仅是一个临时存放数据的地方,当用户退出或者结账后里面的数据自动清空
(4)user_dict.json
{"zhangsan": {"creditcard": "888888", "locked": 0, "username": "zhangsan", "password": "123"}, "lisi": {"creditcard": "666666", "password": "123", "username": "lisi", "locked": 0}, "wangwu": {"creditcard": "777777", "locked": 0, "username": "wangwu", "password": "333"}, "zhaosi": {"creditcard": "654321", "password": "123", "username": "zhaosi", "locked": 0}, "whw": {"creditcard": "123456", "password": "123", "username": "whw", "locked": 0}, "www": {"username": "www", "password": "123", "creditcard": "0", "locked": 0}, "eee": {"username": "eee", "password": "123", "creditcard": "0", "locked": 1}, "wanghw": {"username": "wanghw", "password": "123", "creditcard": "000000", "locked": 0}, "fff": {"username": "fff", "password": "123", "creditcard": "111111", "locked": 0}, "ttt": {"username": "ttt", "password": "123", "creditcard": "785458", "locked": 0}, "rrr": {"username": "rrr", "password": "123", "creditcard": "0", "locked": 0}, "uuu": {"username": "uuu", "password": "123", "creditcard": "999999", "locked": 0}, "ooo": {"username": "ooo", "password": "321", "creditcard": "222222", "locked": 0}, "rty": {"username": "rty", "password": "123", "creditcard": "0", "locked": 0}}
{"zhangsan": {"creditcard": "888888", "locked": 0, "username": "zhangsan", "password": "123"}, "lisi": {"creditcard": "666666", "password": "123", "username": "lisi", "locked": 0}, "wangwu": {"creditcard": "777777", "locked": 0, "username": "wangwu", "password": "333"}, "zhaosi": {"creditcard": "654321", "password": "123", "username": "zhaosi", "locked": 0}, "whw": {"creditcard": "123456", "password": "123", "username": "whw", "locked": 0}, "www": {"username": "www", "password": "123", "creditcard": "0", "locked": 0}, "eee": {"username": "eee", "password": "123", "creditcard": "0", "locked": 1}, "wanghw": {"username": "wanghw", "password": "123", "creditcard": "000000", "locked": 0}, "fff": {"username": "fff", "password": "123", "creditcard": "111111", "locked": 0}, "ttt": {"username": "ttt", "password": "123", "creditcard": "785458", "locked": 0}, "rrr": {"username": "rrr", "password": "123", "creditcard": "0", "locked": 0}, "uuu": {"username": "uuu", "password": "123", "creditcard": "999999", "locked": 0}, "ooo": {"username": "ooo", "password": "321", "creditcard": "222222", "locked": 0}, "rty": {"username": "rty", "password": "123", "creditcard": "0", "locked": 0}}
4.logics文件夹中的内容(都是本程序的后台逻辑)
(1)admin_opera.py
import os,json from .logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #信用卡与用户文件的相对路径 _user_dict = BASE_DIR + r\'\db\user_dict.json\' _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #负责记录各种操作 access_logger = logger(\'access\') #创建账户 def create_user(creditcard=\'0\',locked=0): while 1: print(\'创建用户\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) print(\'现有账户名信息如下:\') for i,v in enumerate(user_dict,1): print(\'%s:%s\' % (i,v)) username = input(\'请输入要添加的账户名:\') password = input(\'请输入想要添加的密码:\') if username not in user_dict.keys(): if len(username.strip()) > 0: if len(password.strip()) > 0: #添加用户 user_dict[username] = {"username": username, "password": password, "creditcard": creditcard, "locked": locked} new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) access_logger.info(\'create a new user: %s \' % username) print("创建用户 %s 成功" % (username)) print(\'添加后的账户名信息如下:\') for i, v in enumerate(user_dict, 1): print(\'%s:%s\' % (i, v)) break else: print("输入的密码为空") else: print("输入的用户名为空") else: print("用户名 %s 已经存在" % (username)) #锁定账号 def user_locked(): while 1: print(\'锁定账户\'.center(30,\'+\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) print(\'账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) lock_input = input(\'请输入要锁定的用户:\') if not lock_input:continue if lock_input in user_dict.keys(): sure = input(\'是否确定进行锁定操作?确定【y】,返回上一级【b】\') if sure == \'y\': if user_dict[lock_input][\'locked\'] == 0: user_dict[lock_input][\'locked\'] = 1 new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) print(\'账户 %s 锁定成功!\' % lock_input) access_logger.info(\'user %s just be locked!\' % lock_input) print(\'修改后的账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) break else: print(\'操作失败!该账户之前已被锁定!\') elif sure == \'b\': break else: print(\'请输入正确的操作编码!\') break else: print(\'账户名不存在,请重新输入!\') continue #解锁账号 def user_unlock(): while 1: print(\'解锁用户\'.center(30,\'-\')) f_user_dict = open(_user_dict, \'r+\') user_dict = json.loads(f_user_dict.read()) print(\'账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) unlock_input = input(\'请输入需要解锁的用户:\') if not unlock_input:continue if unlock_input in user_dict.keys(): sure = input(\'是否确定进行解锁操作?确定【y】,返回上一级【b】\') if sure == \'y\': if user_dict[unlock_input][\'locked\'] != 0: user_dict[unlock_input][\'locked\'] = 0 new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) print(\'账户 %s 解锁成功!\' % unlock_input) access_logger.info(\'user %s just be unlocked!\' % unlock_input) print(\'修改后的账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) break else: print(\'操作失败!该账户之前未被锁定!\') elif sure == \'b\': break else: print(\'请输入正确的操作编码!\') break else: print(\'账户名不存在,请重新输入!\') continue #新建信用卡 def create_creditcard(personinfo=\'blank\',limit=15000,locked=0,limitcash=7500): while 1: print(\'新建信用卡\'.center(30,\'+\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: print(\'信用卡 %s >> 持卡人 %s\'% (index,creditcard_dict[index][\'personinfo\'])) new_card = input(\'请输入要发行的信用卡卡号:\') if not new_card:continue if new_card.isdigit(): if len(new_card.strip()) == 6: if new_card not in creditcard_dict.keys(): password = input(\'请输入新增信用卡的密码:\') if len(password.strip()) > 0: #新增信用卡 creditcard_dict[new_card] = {"personinfo": personinfo, "password": password, "limit": limit, "locked": 0, "limitcash": limit//2, "creditcard": new_card} new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'create a new creditcard: %s \' % new_card) print(\'信用卡新增成功!新的信用卡信息如下:\') for index in creditcard_dict: print(\'信用卡 %s >> 持卡人 %s\'% (index,creditcard_dict[index][\'personinfo\'])) break else: print(\'信用卡密码不能为空!\') else: print(\'该卡号已存在!\') else: print(\'信用卡卡号必须是6位数字!\') else: print(\'请输入数字!\') #冻结信用卡 def lock_creditcard(): while 1: print(\'冻结信用卡\'.center(30,\'-\')) f_creditcard_dict = open(_creditcard_dict, \'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index,\'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) lock_card = input(\'请输入要冻结的信用卡卡号:\') if lock_card.isdigit() and len(lock_card) ==6: if lock_card in creditcard_dict.keys(): if_lock = input(\'是否冻结该信用卡:%s。确认【y】,返回【b】\' % lock_card) if if_lock == \'b\': break elif if_lock == \'y\': creditcard_dict[lock_card][\'locked\'] = 1 new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'creditcard %s just be locked!\' % lock_card) print(\'信用卡 %s 已成功冻结!\' % lock_card) print(\'更改后的信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index, \'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) break else: print(\'请输入正确的操作信息!\') else: print(\'该信用卡卡号不存在!\') else: print(\'请输入正确的卡号格式!\') continue #解冻信用卡 def unlock_creditcard(): while 1: print(\'解冻信用卡\'.center(30,\'-\')) f_creditcard_dict = open(_creditcard_dict, \'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index,\'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) ulock_card = input(\'请输入要解冻的信用卡卡号:\') if ulock_card.isdigit() and len(ulock_card) ==6: if ulock_card in creditcard_dict.keys(): if_lock = input(\'是否解冻该信用卡:%s。确认【y】,返回【b】\' % ulock_card) if if_lock == \'b\': break elif if_lock == \'y\': creditcard_dict[ulock_card][\'locked\'] = 0 new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'creditcard %s just be unlocked!\' % ulock_card) print(\'信用卡 %s 已成功解冻!\' % ulock_card) print(\'更改后的信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index, \'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) break else: print(\'请输入正确的操作信息!\') else: print(\'该信用卡卡号不存在!\') else: print(\'请输入正确的卡号格式!\') continue
import os,json from .logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #信用卡与用户文件的相对路径 _user_dict = BASE_DIR + r\'\db\user_dict.json\' _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #负责记录各种操作 access_logger = logger(\'access\') #创建账户 def create_user(creditcard=\'0\',locked=0): while 1: print(\'创建用户\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) print(\'现有账户名信息如下:\') for i,v in enumerate(user_dict,1): print(\'%s:%s\' % (i,v)) username = input(\'请输入要添加的账户名:\') password = input(\'请输入想要添加的密码:\') if username not in user_dict.keys(): if len(username.strip()) > 0: if len(password.strip()) > 0: #添加用户 user_dict[username] = {"username": username, "password": password, "creditcard": creditcard, "locked": locked} new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) access_logger.info(\'create a new user: %s \' % username) print("创建用户 %s 成功" % (username)) print(\'添加后的账户名信息如下:\') for i, v in enumerate(user_dict, 1): print(\'%s:%s\' % (i, v)) break else: print("输入的密码为空") else: print("输入的用户名为空") else: print("用户名 %s 已经存在" % (username)) #锁定账号 def user_locked(): while 1: print(\'锁定账户\'.center(30,\'+\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) print(\'账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) lock_input = input(\'请输入要锁定的用户:\') if not lock_input:continue if lock_input in user_dict.keys(): sure = input(\'是否确定进行锁定操作?确定【y】,返回上一级【b】\') if sure == \'y\': if user_dict[lock_input][\'locked\'] == 0: user_dict[lock_input][\'locked\'] = 1 new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) print(\'账户 %s 锁定成功!\' % lock_input) access_logger.info(\'user %s just be locked!\' % lock_input) print(\'修改后的账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) break else: print(\'操作失败!该账户之前已被锁定!\') elif sure == \'b\': break else: print(\'请输入正确的操作编码!\') break else: print(\'账户名不存在,请重新输入!\') continue #解锁账号 def user_unlock(): while 1: print(\'解锁用户\'.center(30,\'-\')) f_user_dict = open(_user_dict, \'r+\') user_dict = json.loads(f_user_dict.read()) print(\'账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) unlock_input = input(\'请输入需要解锁的用户:\') if not unlock_input:continue if unlock_input in user_dict.keys(): sure = input(\'是否确定进行解锁操作?确定【y】,返回上一级【b】\') if sure == \'y\': if user_dict[unlock_input][\'locked\'] != 0: user_dict[unlock_input][\'locked\'] = 0 new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) print(\'账户 %s 解锁成功!\' % unlock_input) access_logger.info(\'user %s just be unlocked!\' % unlock_input) print(\'修改后的账户锁定状态如下:\') for i in user_dict: if user_dict[i][\'locked\'] == 0: print(\'用户 %s 未被锁定!\' % i) else: print(\'用户 %s 已被锁定\' % i) break else: print(\'操作失败!该账户之前未被锁定!\') elif sure == \'b\': break else: print(\'请输入正确的操作编码!\') break else: print(\'账户名不存在,请重新输入!\') continue #新建信用卡 def create_creditcard(personinfo=\'blank\',limit=15000,locked=0,limitcash=7500): while 1: print(\'新建信用卡\'.center(30,\'+\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: print(\'信用卡 %s >> 持卡人 %s\'% (index,creditcard_dict[index][\'personinfo\'])) new_card = input(\'请输入要发行的信用卡卡号:\') if not new_card:continue if new_card.isdigit(): if len(new_card.strip()) == 6: if new_card not in creditcard_dict.keys(): password = input(\'请输入新增信用卡的密码:\') if len(password.strip()) > 0: #新增信用卡 creditcard_dict[new_card] = {"personinfo": personinfo, "password": password, "limit": limit, "locked": 0, "limitcash": limit//2, "creditcard": new_card} new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'create a new creditcard: %s \' % new_card) print(\'信用卡新增成功!新的信用卡信息如下:\') for index in creditcard_dict: print(\'信用卡 %s >> 持卡人 %s\'% (index,creditcard_dict[index][\'personinfo\'])) break else: print(\'信用卡密码不能为空!\') else: print(\'该卡号已存在!\') else: print(\'信用卡卡号必须是6位数字!\') else: print(\'请输入数字!\') #冻结信用卡 def lock_creditcard(): while 1: print(\'冻结信用卡\'.center(30,\'-\')) f_creditcard_dict = open(_creditcard_dict, \'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index,\'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) lock_card = input(\'请输入要冻结的信用卡卡号:\') if lock_card.isdigit() and len(lock_card) ==6: if lock_card in creditcard_dict.keys(): if_lock = input(\'是否冻结该信用卡:%s。确认【y】,返回【b】\' % lock_card) if if_lock == \'b\': break elif if_lock == \'y\': creditcard_dict[lock_card][\'locked\'] = 1 new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'creditcard %s just be locked!\' % lock_card) print(\'信用卡 %s 已成功冻结!\' % lock_card) print(\'更改后的信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index, \'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) break else: print(\'请输入正确的操作信息!\') else: print(\'该信用卡卡号不存在!\') else: print(\'请输入正确的卡号格式!\') continue #解冻信用卡 def unlock_creditcard(): while 1: print(\'解冻信用卡\'.center(30,\'-\')) f_creditcard_dict = open(_creditcard_dict, \'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) print(\'现有信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index,\'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) ulock_card = input(\'请输入要解冻的信用卡卡号:\') if ulock_card.isdigit() and len(ulock_card) ==6: if ulock_card in creditcard_dict.keys(): if_lock = input(\'是否解冻该信用卡:%s。确认【y】,返回【b】\' % ulock_card) if if_lock == \'b\': break elif if_lock == \'y\': creditcard_dict[ulock_card][\'locked\'] = 0 new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) access_logger.info(\'creditcard %s just be unlocked!\' % ulock_card) print(\'信用卡 %s 已成功解冻!\' % ulock_card) print(\'更改后的信用卡信息如下:\') for index in creditcard_dict: if creditcard_dict[index][\'locked\'] == 0: print(\'信用卡 %s >>> %s\' % (index, \'未冻结\')) else: print(\'信用卡 %s >>> %s\' % (index, \'已冻结\')) break else: print(\'请输入正确的操作信息!\') else: print(\'该信用卡卡号不存在!\') else: print(\'请输入正确的卡号格式!\') continue
(2)authentication.py
import os import json #程序主目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #数据库文件:用户文件与信用卡文件——相对路径 users_dict = BASE_DIR + r\'\db\user_dict.json\' creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #认证——装饰器 def login(auth_type): def auth(func): #用户名认证 if auth_type == \'user_auth\': def inner(): res = func() n = 0 while n < 3:#用户有三次输入的机会 username = input(\'请输入用户名:\') password = input(\'请输入密码:\') if not username or not password: print(\'用户名或密码不能为空,请重新输入!\') n += 1 continue f = open(users_dict,\'r+\') users_dict_j = json.loads(f.read())#loads if username in users_dict_j.keys(): if password in users_dict_j[username]["password"]: if users_dict_j[username][\'locked\'] == 0: print(\'用户 %s 认证成功!\' % username) return res,username else: print(\'用户 %s 已被锁定!\' % username) break else: print(\'密码不匹配!\') n += 1 continue else: print(\'用户名不匹配!\') n += 1 continue return inner #信用卡认证 if auth_type == \'creditcard_auth\': def inner(): res = func() n = 0 while n < 3: creditcard = input(\'请输入信用卡卡号(6位数字):\') password = input(\'请输入信用卡密码:\') if not creditcard or not password: print(\'卡号或者密码不能为空,请重新输入!\') n += 1 continue f = open(creditcard_dict,\'r+\') creditcard_dict_j = json.loads(f.read()) if creditcard in creditcard_dict_j.keys(): if password in creditcard_dict_j[creditcard][\'password\']: if creditcard_dict_j[creditcard][\'locked\'] == 0: print(\'信用卡 %s 认证成功!\' % creditcard) return res,creditcard else: print(\'该信用卡已被冻结!\') break else: print(\'密码错误!\') n += 1 continue else: print(\'卡号错误!\') n += 1 continue return inner #管理员认证 if auth_type == \'admin_auth\': def inner(): res = func() #规定admin账户只能是这一个唯一的账户 admin_dict = {\'admin\':\'admin\'} n = 0 while n < 3: admin_name = input(\'请输入管理员账户:\') admin_password = input(\'请输入管理员密码:\') if not admin_name or not admin_password: print(\'账户名或密码不能为空!\') n += 1 continue if admin_name in admin_dict: if admin_password in admin_dict: print(\'管理员账户 %s 认证成功!\' % admin_name) return res,admin_name else: print(\'密码不匹配!!\') n += 1 continue else: print(\'管理员账户名不匹配:\') n += 1 continue return inner return auth #用户以三种方式登陆:用户名、信用卡、后台管理员 @login(\'user_auth\') def user_auth(): print(\'用户登陆认证:\'.center(30,\'+\')) return \'True\' @login(\'creditcard_auth\') def creditcard_auth(): print(\'信用卡登陆认证:\'.center(30,\'+\')) return \'True\' @login(\'admin_auth\') def admin_auth(): print(\'后台管理员登陆认证:\'.center(30,\'+\')) return \'True\'
import os import json #程序主目录 BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #数据库文件:用户文件与信用卡文件——相对路径 users_dict = BASE_DIR + r\'\db\user_dict.json\' creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #认证——装饰器 def login(auth_type): def auth(func): #用户名认证 if auth_type == \'user_auth\': def inner(): res = func() n = 0 while n < 3:#用户有三次输入的机会 username = input(\'请输入用户名:\') password = input(\'请输入密码:\') if not username or not password: print(\'用户名或密码不能为空,请重新输入!\') n += 1 continue f = open(users_dict,\'r+\') users_dict_j = json.loads(f.read())#loads if username in users_dict_j.keys(): if password in users_dict_j[username]["password"]: if users_dict_j[username][\'locked\'] == 0: print(\'用户 %s 认证成功!\' % username) return res,username else: print(\'用户 %s 已被锁定!\' % username) break else: print(\'密码不匹配!\') n += 1 continue else: print(\'用户名不匹配!\') n += 1 continue return inner #信用卡认证 if auth_type == \'creditcard_auth\': def inner(): res = func() n = 0 while n < 3: creditcard = input(\'请输入信用卡卡号(6位数字):\') password = input(\'请输入信用卡密码:\') if not creditcard or not password: print(\'卡号或者密码不能为空,请重新输入!\') n += 1 continue f = open(creditcard_dict,\'r+\') creditcard_dict_j = json.loads(f.read()) if creditcard in creditcard_dict_j.keys(): if password in creditcard_dict_j[creditcard][\'password\']: if creditcard_dict_j[creditcard][\'locked\'] == 0: print(\'信用卡 %s 认证成功!\' % creditcard) return res,creditcard else: print(\'该信用卡已被冻结!\') break else: print(\'密码错误!\') n += 1 continue else: print(\'卡号错误!\') n += 1 continue return inner #管理员认证 if auth_type == \'admin_auth\': def inner(): res = func() #规定admin账户只能是这一个唯一的账户 admin_dict = {\'admin\':\'admin\'} n = 0 while n < 3: admin_name = input(\'请输入管理员账户:\') admin_password = input(\'请输入管理员密码:\') if not admin_name or not admin_password: print(\'账户名或密码不能为空!\') n += 1 continue if admin_name in admin_dict: if admin_password in admin_dict: print(\'管理员账户 %s 认证成功!\' % admin_name) return res,admin_name else: print(\'密码不匹配!!\') n += 1 continue else: print(\'管理员账户名不匹配:\') n += 1 continue return inner return auth #用户以三种方式登陆:用户名、信用卡、后台管理员 @login(\'user_auth\') def user_auth(): print(\'用户登陆认证:\'.center(30,\'+\')) return \'True\' @login(\'creditcard_auth\') def creditcard_auth(): print(\'信用卡登陆认证:\'.center(30,\'+\')) return \'True\' @login(\'admin_auth\') def admin_auth(): print(\'后台管理员登陆认证:\'.center(30,\'+\')) return \'True\'
(3)creditcard_opera.py
import os,json from.logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #信息文件的相对路径: _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #负责记录各种交易 transaction_logger = logger(\'transaction\') #本信用卡信息 def creditcard_msg(current_creditcard): while 1: print(\'本信用卡信息:\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r\') creditcard_dict = json.loads(f_creditcard_dict.read()) #先判断提现额度 if creditcard_dict[current_creditcard][\'limitcash\'] <= creditcard_dict[current_creditcard][\'limit\']: limitcash = creditcard_dict[current_creditcard][\'limitcash\'] else: limitcash = creditcard_dict[current_creditcard][\'limit\'] print("卡号:\t【%s】\n余额:\t【¥%s】\n提现额度:\t【¥%s】\n持卡人:\t【%s】\n"%(current_creditcard, creditcard_dict[current_creditcard]["limit"],limitcash,creditcard_dict[current_creditcard]["personinfo"])) choice = input(\'是否返回?【b】返回\') if choice == \'b\': break else: print(\'请输入【b】返回\') continue #提现 def creditcard_cash(current_creditcard): while 1: print(\'信用卡提现操作(手续费为%5)\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) limit = creditcard_dict[current_creditcard][\'limit\'] limitcash = creditcard_dict[current_creditcard][\'limitcash\'] if limit >= limitcash: print(\'可提现的金额为:%s\' % limitcash) cash_input = input(\'请输入要提取的金额:\') if not cash_input or not cash_input.isdigit():#输入为空或非数字 print(\'请输入数字!\') continue cash = int(cash_input) if cash != 0: if cash <= limitcash: limit = limit - (cash*1.05) creditcard_dict[current_creditcard][\'limit\'] = limit creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) #日志 transaction_logger.info(\'信用卡 %s 提现 %s元\' % (current_creditcard,cash_input)) print(\'提现成功!当前余额为: %s \' % creditcard_dict[current_creditcard][\'limit\']) break else: print(\'提现金额超出信用卡限额!\') else: print(\'提现金额不能为空!\') if limit < limitcash: print("可提现金额:【%s】(扣除0.05手续费)\n" % (int(limit*0.95))) cash_input = input(\'请输入要提取的金额:\') if not cash_input or not cash_input.isdigit(): # 输入为空或非数字 print(\'请输入数字!\') continue cash = int(cash_input) if cash != 0: if cash < limit*0.95: limit = limit - (cash * 1.05) creditcard_dict[current_creditcard][\'limit\'] = limit creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) # 日志 transaction_logger.info(\'信用卡 %s 提现 %s元\' % (current_creditcard, cash_input)) print(\'提现成功!当前余额为: %s \' % creditcard_dict[current_creditcard][\'limit\']) break else: print(\'提现金额超出信用卡限额!\') else: print(\'提现金额不能为空!\') #转账 def creditcard_transfer(current_creditcard): while 1: print(\'信用卡转账\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) trans_input = input(\'(您的余额为%s)请输入要转入的卡号:\' % creditcard_dict[current_creditcard][\'limit\']) if trans_input or trans_input.isdigit() or len(trans_input) == 6: if trans_input in creditcard_dict.keys(): transfer_cash = input(\'请输入您要转入的金额:\') if transfer_cash or transfer_cash.isdigit(): transfer_cash = int(transfer_cash) if transfer_cash < creditcard_dict[current_creditcard][\'limit\']: creditcard_dict[current_creditcard][\'limit\'] -= transfer_cash creditcard_dict[trans_input][\'limit\'] += transfer_cash creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) # 日志 transaction_logger.info(\'信用卡 %s 给信用卡 %s 转账 %s元\' % (current_creditcard,trans_input,transfer_cash)) print(\'转账成功!您的当前余额为: %s\' % (creditcard_dict[current_creditcard][\'limit\'])) break else: print(\'对不起,您的金额不足,转账失败!\') else: print(\'金额输入有误!\') else: print(\'该信用卡卡号不存在!\') else: print(\'银行卡号输入有误!\') #还款 def creditcard_payback(current_creditcard): while 1: print(\'信用卡还款\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) payback = input(\'请输入还款金额:\') if payback and payback.isdigit(): payback = int(payback) creditcard_dict[current_creditcard][\'limit\'] += payback new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) # 日志 transaction_logger.info(\'信用卡 %s 还款 %s元\' % (current_creditcard, payback)) print(\'信用卡 %s 还款成功!当前余额为:%s\' % (current_creditcard,creditcard_dict[current_creditcard][\'limit\'])) break else: print(\'请输入正确的金额!\')
import os,json from.logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #信息文件的相对路径: _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' #负责记录各种交易 transaction_logger = logger(\'transaction\') #本信用卡信息 def creditcard_msg(current_creditcard): while 1: print(\'本信用卡信息:\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r\') creditcard_dict = json.loads(f_creditcard_dict.read()) #先判断提现额度 if creditcard_dict[current_creditcard][\'limitcash\'] <= creditcard_dict[current_creditcard][\'limit\']: limitcash = creditcard_dict[current_creditcard][\'limitcash\'] else: limitcash = creditcard_dict[current_creditcard][\'limit\'] print("卡号:\t【%s】\n余额:\t【¥%s】\n提现额度:\t【¥%s】\n持卡人:\t【%s】\n"%(current_creditcard, creditcard_dict[current_creditcard]["limit"],limitcash,creditcard_dict[current_creditcard]["personinfo"])) choice = input(\'是否返回?【b】返回\') if choice == \'b\': break else: print(\'请输入【b】返回\') continue #提现 def creditcard_cash(current_creditcard): while 1: print(\'信用卡提现操作(手续费为%5)\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) limit = creditcard_dict[current_creditcard][\'limit\'] limitcash = creditcard_dict[current_creditcard][\'limitcash\'] if limit >= limitcash: print(\'可提现的金额为:%s\' % limitcash) cash_input = input(\'请输入要提取的金额:\') if not cash_input or not cash_input.isdigit():#输入为空或非数字 print(\'请输入数字!\') continue cash = int(cash_input) if cash != 0: if cash <= limitcash: limit = limit - (cash*1.05) creditcard_dict[current_creditcard][\'limit\'] = limit creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) #日志 transaction_logger.info(\'信用卡 %s 提现 %s元\' % (current_creditcard,cash_input)) print(\'提现成功!当前余额为: %s \' % creditcard_dict[current_creditcard][\'limit\']) break else: print(\'提现金额超出信用卡限额!\') else: print(\'提现金额不能为空!\') if limit < limitcash: print("可提现金额:【%s】(扣除0.05手续费)\n" % (int(limit*0.95))) cash_input = input(\'请输入要提取的金额:\') if not cash_input or not cash_input.isdigit(): # 输入为空或非数字 print(\'请输入数字!\') continue cash = int(cash_input) if cash != 0: if cash < limit*0.95: limit = limit - (cash * 1.05) creditcard_dict[current_creditcard][\'limit\'] = limit creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) # 日志 transaction_logger.info(\'信用卡 %s 提现 %s元\' % (current_creditcard, cash_input)) print(\'提现成功!当前余额为: %s \' % creditcard_dict[current_creditcard][\'limit\']) break else: print(\'提现金额超出信用卡限额!\') else: print(\'提现金额不能为空!\') #转账 def creditcard_transfer(current_creditcard): while 1: print(\'信用卡转账\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) trans_input = input(\'(您的余额为%s)请输入要转入的卡号:\' % creditcard_dict[current_creditcard][\'limit\']) if trans_input or trans_input.isdigit() or len(trans_input) == 6: if trans_input in creditcard_dict.keys(): transfer_cash = input(\'请输入您要转入的金额:\') if transfer_cash or transfer_cash.isdigit(): transfer_cash = int(transfer_cash) if transfer_cash < creditcard_dict[current_creditcard][\'limit\']: creditcard_dict[current_creditcard][\'limit\'] -= transfer_cash creditcard_dict[trans_input][\'limit\'] += transfer_cash creditcard_dict_new = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(creditcard_dict_new) # 日志 transaction_logger.info(\'信用卡 %s 给信用卡 %s 转账 %s元\' % (current_creditcard,trans_input,transfer_cash)) print(\'转账成功!您的当前余额为: %s\' % (creditcard_dict[current_creditcard][\'limit\'])) break else: print(\'对不起,您的金额不足,转账失败!\') else: print(\'金额输入有误!\') else: print(\'该信用卡卡号不存在!\') else: print(\'银行卡号输入有误!\') #还款 def creditcard_payback(current_creditcard): while 1: print(\'信用卡还款\'.center(30,\'*\')) f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) payback = input(\'请输入还款金额:\') if payback and payback.isdigit(): payback = int(payback) creditcard_dict[current_creditcard][\'limit\'] += payback new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) # 日志 transaction_logger.info(\'信用卡 %s 还款 %s元\' % (current_creditcard, payback)) print(\'信用卡 %s 还款成功!当前余额为:%s\' % (current_creditcard,creditcard_dict[current_creditcard][\'limit\'])) break else: print(\'请输入正确的金额!\')
(4)logger_opera.py
import logging,os from conf import settings def logger(log_type): #新建日志 logger = logging.getLogger(log_type) #拿到settings文件里的LOG_LEVEL:当前设置为logging.INFO logger.setLevel(settings.LOG_LEVEL) #根据log_type 决定往哪个log文件里写 log_file = os.path.join(settings.LOG_PATH,settings.LOG_TYPES[log_type]) #决定往哪里写后进行操作 fh = logging.FileHandler(log_file) fh.setLevel(settings.LOG_LEVEL) formatter = settings.LOG_FORMAT #formatter: fh.setFormatter(formatter) logger.addHandler(fh) return logger
import logging,os from conf import settings def logger(log_type): #新建日志 logger = logging.getLogger(log_type) #拿到settings文件里的LOG_LEVEL:当前设置为logging.INFO logger.setLevel(settings.LOG_LEVEL) #根据log_type 决定往哪个log文件里写 log_file = os.path.join(settings.LOG_PATH,settings.LOG_TYPES[log_type]) #决定往哪里写后进行操作 fh = logging.FileHandler(log_file) fh.setLevel(settings.LOG_LEVEL) formatter = settings.LOG_FORMAT #formatter: fh.setFormatter(formatter) logger.addHandler(fh) return logger
(5)shoppingmall.py
import json,os from .logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #数据库文件的相对路径: _user_dict = BASE_DIR + r\'\db\user_dict.json\' _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' _productlist = BASE_DIR + r\'\db\productlist.json\' _shoppingcar = BASE_DIR + r\'\db\shoppingcar\' #负责记录各种交易 transaction_logger = logger(\'transaction\') #清空购物车 def clear_shopping_car(): f = open(_shoppingcar,\'w\') l = json.dumps([]) f.write(l) #购物商城 def shopping_mall(): shopping_list,pro_list = [],[] f_pro = open(_productlist,\'r\') for i in f_pro: #得到商品列表,pro_list里面是:[[\'computer\', \'2299\'], [\'1080Ti\', \'3999\'], ...] pro_list.append(i.strip("\n").split()) while 1: print((\'商城目前正在出售的商品及价格信息:\').center(30,\'#\')) print(\'编号\t商品\t\t\t价格\') for i,v in enumerate(pro_list): print(\'%s\t%s: %s\' % (i,v[0],v[1]))#打印商品列表 choice = input(\'请输入想要购买的商品编号或者输入\\'b\\'返回:\') if choice.isdigit(): choice = int(choice) if 0 <= choice < len(pro_list): pro_item = pro_list[choice] print(\'已将商品 %s 加入购物车,价格为%s \'% (pro_item[0],pro_item[1])) shopping_list.append(pro_item) else: print(\'错误!没有对应的编号,请重新输入!\') elif choice == \'b\': f_shopping_car = open(_shoppingcar,\'r+\') list_s = json.loads(f_shopping_car.read()) #注意这里是extend而不是append,append会使价格v[1]取成一个列表 list_s.extend(shopping_list) f_shopping_car.seek(0) f_shopping_car.truncate(0) list_s = json.dumps(list_s) f_shopping_car.write(list_s) break else: print(\'错误~没有对应的编号,请重新输入!\') #查看购物车 def shopping_car(): while 1: f_shopping_car = open(_shoppingcar,\'r+\') l_shopping_car = json.loads(f_shopping_car.read()) n = 0 print(\'购物车信息清单如下:\'.center(30,\'*\')) for i,v in enumerate(l_shopping_car): print(i,v[0],v[1]) n += int(v[1])#计算商品总价格 print(\'购物车中商品的总额为:%d 元\' % n) choice_in = input(\'请选择要进行的操作:返回【b】/清空【c】\') if choice_in == \'b\': break elif choice_in == \'c\': clear_shopping_car() else: print(\'请重新输入正确的编号\') #购物结算前进行信用卡密码认证 def Auth_creditcard(creditcard): with open(_creditcard_dict, "r+") as f_creditcard_dict: creditcard_dict = json.loads(f_creditcard_dict.read()) passwd = input("当前信用卡 %s 请输入支付密码::" % (creditcard)) if passwd == creditcard_dict[creditcard]["password"]: return True else: print("密码输入错误,支付失败") #购物结算 def shopping_pay(current_user): while 1: money = 0 print(\'购物结算\'.center(30,\'$\')) f_shopping_car = open(_shoppingcar,\'r+\') l_shopping_car = json.loads(f_shopping_car.read()) for item in l_shopping_car: money += int(item[1]) #购物车里商品的总钱数 pay_input = input(\'当前商品总额为 %d,是否进行支付?确定【y】/返回【b】\' % money) if pay_input == \'b\': break elif pay_input == \'y\': f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) creditcard = user_dict[current_user][\'creditcard\']#找到账户对应的信用卡 if creditcard == \'0\': print(\'账户 %s 还未绑定信用卡,请进入个人中心绑定信用卡后再进行操作\' % current_user) else: f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) limit = creditcard_dict[creditcard][\'limit\'] limit_new = limit - money if limit_new < 0: print(\'当前信用卡额度为:%s元,不足以支付购物款:%s元\',(limit,money)) else: res = Auth_creditcard(creditcard) if res == True: creditcard_dict[creditcard][\'limit\'] = limit_new new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) print(\'支付成功,当前余额为 %s元\' % limit_new) #记录日志 transaction_logger.info(\'用户 %s 购买产品花费 %s\' %(current_user,money)) clear_shopping_car()#最后清空当前购物车 break #信用卡绑定 def creditcard_linked(current_user): while 1: print(\'信用卡绑定\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) creditcard = user_dict[current_user][\'creditcard\'] if creditcard == \'0\': print(\'当前账号 %s 未绑定信用卡\' % current_user) else: print(\'当前账号 %s 已经绑定了信用卡:%s,不可以重复绑定!\' % (current_user,creditcard)) break link_input = input(\'是否要修改信用卡绑定? 确定【y】/返回【b】\') if link_input.strip() == \'b\': break if link_input.strip() == \'y\': creditcard_new = input(\'请输入新的信用卡卡号(6位数字):\') if creditcard_new.isdigit() and len(creditcard_new) == 6: f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) if creditcard_new not in creditcard_dict.keys(): print(\'输入信用卡卡号不存在(或者未发行)!\') #信用卡的持卡人信息为blank(代表这个卡没有人绑定) if creditcard_dict[creditcard_new][\'personinfo\'] == \'blank\': creditcard_dict[creditcard_new][\'personinfo\'] = current_user user_dict[current_user][\'creditcard\'] = creditcard_new #新的信用卡信息 dict_creditcard = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(dict_creditcard) #新的人员信息 dict_users = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(dict_users) #记录日志 transaction_logger.info(\'用户 %s 绑定信用卡 %s!\' % (current_user,creditcard_new)) print(\'用户 %s 已成功绑定信用卡 %s!\' % (current_user,creditcard_new)) break else: print(\'信用卡 %s 已绑定用户,不可以再绑定!\' % creditcard_new) else: print(\'请输入正确格式的信用卡卡号\') else: print(\'请输入正确的操作编号!\') #修改登陆密码 def revise_password(current_user): while 1: print(\'修改用户登陆密码\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) old_password = user_dict[current_user][\'password\'] old_password_o = input(\'请输入旧密码:\') if old_password_o != old_password: print(\'旧密码不正确!\') break new_password = input(\'请输入新密码:\') new_password_again = input(\'请确认新密码:\') if new_password == new_password_again: user_dict[current_user][\'password\'] = new_password new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) #记录日志 transaction_logger.info(\'用户 %s 修改了密码\' % current_user) print(\'用户 %s 密码修改成功!\' % current_user) break else: print(\'两次输入的密码不一致!\') break
import json,os from .logger_opera import logger BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #数据库文件的相对路径: _user_dict = BASE_DIR + r\'\db\user_dict.json\' _creditcard_dict = BASE_DIR + r\'\db\creditcard_dict.json\' _productlist = BASE_DIR + r\'\db\productlist.json\' _shoppingcar = BASE_DIR + r\'\db\shoppingcar\' #负责记录各种交易 transaction_logger = logger(\'transaction\') #清空购物车 def clear_shopping_car(): f = open(_shoppingcar,\'w\') l = json.dumps([]) f.write(l) #购物商城 def shopping_mall(): shopping_list,pro_list = [],[] f_pro = open(_productlist,\'r\') for i in f_pro: #得到商品列表,pro_list里面是:[[\'computer\', \'2299\'], [\'1080Ti\', \'3999\'], ...] pro_list.append(i.strip("\n").split()) while 1: print((\'商城目前正在出售的商品及价格信息:\').center(30,\'#\')) print(\'编号\t商品\t\t\t价格\') for i,v in enumerate(pro_list): print(\'%s\t%s: %s\' % (i,v[0],v[1]))#打印商品列表 choice = input(\'请输入想要购买的商品编号或者输入\\'b\\'返回:\') if choice.isdigit(): choice = int(choice) if 0 <= choice < len(pro_list): pro_item = pro_list[choice] print(\'已将商品 %s 加入购物车,价格为%s \'% (pro_item[0],pro_item[1])) shopping_list.append(pro_item) else: print(\'错误!没有对应的编号,请重新输入!\') elif choice == \'b\': f_shopping_car = open(_shoppingcar,\'r+\') list_s = json.loads(f_shopping_car.read()) #注意这里是extend而不是append,append会使价格v[1]取成一个列表 list_s.extend(shopping_list) f_shopping_car.seek(0) f_shopping_car.truncate(0) list_s = json.dumps(list_s) f_shopping_car.write(list_s) break else: print(\'错误~没有对应的编号,请重新输入!\') #查看购物车 def shopping_car(): while 1: f_shopping_car = open(_shoppingcar,\'r+\') l_shopping_car = json.loads(f_shopping_car.read()) n = 0 print(\'购物车信息清单如下:\'.center(30,\'*\')) for i,v in enumerate(l_shopping_car): print(i,v[0],v[1]) n += int(v[1])#计算商品总价格 print(\'购物车中商品的总额为:%d 元\' % n) choice_in = input(\'请选择要进行的操作:返回【b】/清空【c】\') if choice_in == \'b\': break elif choice_in == \'c\': clear_shopping_car() else: print(\'请重新输入正确的编号\') #购物结算前进行信用卡密码认证 def Auth_creditcard(creditcard): with open(_creditcard_dict, "r+") as f_creditcard_dict: creditcard_dict = json.loads(f_creditcard_dict.read()) passwd = input("当前信用卡 %s 请输入支付密码::" % (creditcard)) if passwd == creditcard_dict[creditcard]["password"]: return True else: print("密码输入错误,支付失败") #购物结算 def shopping_pay(current_user): while 1: money = 0 print(\'购物结算\'.center(30,\'$\')) f_shopping_car = open(_shoppingcar,\'r+\') l_shopping_car = json.loads(f_shopping_car.read()) for item in l_shopping_car: money += int(item[1]) #购物车里商品的总钱数 pay_input = input(\'当前商品总额为 %d,是否进行支付?确定【y】/返回【b】\' % money) if pay_input == \'b\': break elif pay_input == \'y\': f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) creditcard = user_dict[current_user][\'creditcard\']#找到账户对应的信用卡 if creditcard == \'0\': print(\'账户 %s 还未绑定信用卡,请进入个人中心绑定信用卡后再进行操作\' % current_user) else: f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) limit = creditcard_dict[creditcard][\'limit\'] limit_new = limit - money if limit_new < 0: print(\'当前信用卡额度为:%s元,不足以支付购物款:%s元\',(limit,money)) else: res = Auth_creditcard(creditcard) if res == True: creditcard_dict[creditcard][\'limit\'] = limit_new new_creditcard_dict = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(new_creditcard_dict) print(\'支付成功,当前余额为 %s元\' % limit_new) #记录日志 transaction_logger.info(\'用户 %s 购买产品花费 %s\' %(current_user,money)) clear_shopping_car()#最后清空当前购物车 break #信用卡绑定 def creditcard_linked(current_user): while 1: print(\'信用卡绑定\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) creditcard = user_dict[current_user][\'creditcard\'] if creditcard == \'0\': print(\'当前账号 %s 未绑定信用卡\' % current_user) else: print(\'当前账号 %s 已经绑定了信用卡:%s,不可以重复绑定!\' % (current_user,creditcard)) break link_input = input(\'是否要修改信用卡绑定? 确定【y】/返回【b】\') if link_input.strip() == \'b\': break if link_input.strip() == \'y\': creditcard_new = input(\'请输入新的信用卡卡号(6位数字):\') if creditcard_new.isdigit() and len(creditcard_new) == 6: f_creditcard_dict = open(_creditcard_dict,\'r+\') creditcard_dict = json.loads(f_creditcard_dict.read()) if creditcard_new not in creditcard_dict.keys(): print(\'输入信用卡卡号不存在(或者未发行)!\') #信用卡的持卡人信息为blank(代表这个卡没有人绑定) if creditcard_dict[creditcard_new][\'personinfo\'] == \'blank\': creditcard_dict[creditcard_new][\'personinfo\'] = current_user user_dict[current_user][\'creditcard\'] = creditcard_new #新的信用卡信息 dict_creditcard = json.dumps(creditcard_dict) f_creditcard_dict.seek(0) f_creditcard_dict.truncate(0) f_creditcard_dict.write(dict_creditcard) #新的人员信息 dict_users = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(dict_users) #记录日志 transaction_logger.info(\'用户 %s 绑定信用卡 %s!\' % (current_user,creditcard_new)) print(\'用户 %s 已成功绑定信用卡 %s!\' % (current_user,creditcard_new)) break else: print(\'信用卡 %s 已绑定用户,不可以再绑定!\' % creditcard_new) else: print(\'请输入正确格式的信用卡卡号\') else: print(\'请输入正确的操作编号!\') #修改登陆密码 def revise_password(current_user): while 1: print(\'修改用户登陆密码\'.center(30,\'*\')) f_user_dict = open(_user_dict,\'r+\') user_dict = json.loads(f_user_dict.read()) old_password = user_dict[current_user][\'password\'] old_password_o = input(\'请输入旧密码:\') if old_password_o != old_password: print(\'旧密码不正确!\') break new_password = input(\'请输入新密码:\') new_password_again = input(\'请确认新密码:\') if new_password == new_password_again: user_dict[current_user][\'password\'] = new_password new_user_dict = json.dumps(user_dict) f_user_dict.seek(0) f_user_dict.truncate(0) f_user_dict.write(new_user_dict) #记录日志 transaction_logger.info(\'用户 %s 修改了密码\' % current_user) print(\'用户 %s 密码修改成功!\' % current_user) break else: print(\'两次输入的密码不一致!\') break
5.logs文件夹中的内容(存放的都是日志信息)
(1)access.log
2018-04-17 17:41:37,130 - access - INFO - create a new user: rty 2018-04-17 17:41:49,616 - access - INFO - user rty just be locked! 2018-04-17 17:41:56,711 - access - INFO - user rty just be unlocked! 2018-04-17 17:42:08,399 - access - INFO - create a new creditcard: 909090 2018-04-17 17:42:21,666 - access - INFO - creditcard 909090 just be locked! 2018-04-17 17:42:29,636 - access - INFO - creditcard 909090 just be unlocked! 2018-04-17 18:01:53,331 - access - INFO - creditcard 000000 just be unlocked!
(2)transactions.log
2018-04-17 17:34:09,615 - transaction - INFO - 用户 whw 购买产品花费 4998 2018-04-17 17:34:23,226 - transaction - INFO - 用户 whw 修改了密码 2018-04-17 17:40:41,468 - transaction - INFO - 信用卡 123456 提现 333元 2018-04-17 17:40:49,250 - transaction - INFO - 信用卡 123456 给信用卡 666666 转账 11元 2018-04-17 17:40:55,188 - transaction - INFO - 信用卡 123456 还款 222元
需求如下:创建管理员、教师、学员这三个视图,实现一个简单的课程操作交互
具体实现如下:
Homework:
│
├─bin
│──────start.py #程序的入口
│
├─conf
│──────config.py #程序用到的文件的路径以及其他关系映射信息
│
├─core #
│──────logger.py#记录日志的逻辑
│──────main.py#实现三类用户的登陆逻辑,并利用反射调用不同类的具体方法
│──────manager.py#实现了管理员类的各个功能
│──────my_pickle.py#实现了将不同对象dump、load进文件的方法以及修改已经被dump的文件的方法
│──────other_logics.py#其他额外功能的逻辑
│──────school.py#里面的classes类用来创建与班级名相同名字的文件
│──────student.py#实现学生类的功能逻辑
│──────teacher.py#实现讲师类的功能逻辑
│
└─db
│──classes_obj#存放各个班级对象的信息
│──logs.log#存放日志信息
│──teacher_obj#存放讲师对象信息
│──userinfo#存放登陆用户信息
│
└─studentinfo#里面的文件是与班级同名的文件,各个文件里面存的是相应班级里的学员信息
│────────python_s9
代码如下:
代码如下:
from os import getcwd,path from sys import path as sys_path sys_path.insert(0,path.dirname(getcwd())) from core import main if __name__ == \'__main__\': main.main()
from os import getcwd,path from sys import path as sys_path sys_path.insert(0,path.dirname(getcwd())) from core import main if __name__ == \'__main__\': main.main()
import os PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #userinfo文件的路径 USERINFO = os.path.join(PATH,\'db\',\'userinfo\') #schoolinfo的路径 SCHOOLINFO = os.path.join(PATH,\'db\',\'school_obj\') #teacher_obj的路径 TEACHER_OBJ = os.path.join(PATH,\'db\',\'teacher_obj\') #classes_obj的路径 CLASSES_OBJ = os.path.join(PATH,\'db\',\'classes_obj\') #course_obj的路径 COURSE_OBJ = os.path.join(PATH,\'db\',\'course_obj\') #studentinfo的路径 STUDENTINFO = os.path.join(PATH,\'db\',\'studentinfo\') #日志文件的路径 LOGGER = os.path.join(PATH,\'db\',\'logs.log\') #用户选择视图输入项与身份信息的键值对 USER_DICT = {\'1\':\'Manager\',\'2\':\'Teacher\',\'3\':\'Student\'} #学校与课程对应关系字典 school_class = {\'Beijing\':[\'python\',\'linux\'],\'Shanghai\':[\'go\']}
import os PATH = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #userinfo文件的路径 USERINFO = os.path.join(PATH,\'db\',\'userinfo\') #schoolinfo的路径 SCHOOLINFO = os.path.join(PATH,\'db\',\'school_obj\') #teacher_obj的路径 TEACHER_OBJ = os.path.join(PATH,\'db\',\'teacher_obj\') #classes_obj的路径 CLASSES_OBJ = os.path.join(PATH,\'db\',\'classes_obj\') #course_obj的路径 COURSE_OBJ = os.path.join(PATH,\'db\',\'course_obj\') #studentinfo的路径 STUDENTINFO = os.path.join(PATH,\'db\',\'studentinfo\') #日志文件的路径 LOGGER = os.path.join(PATH,\'db\',\'logs.log\') #用户选择视图输入项与身份信息的键值对 USER_DICT = {\'1\':\'Manager\',\'2\':\'Teacher\',\'3\':\'Student\'} #学校与课程对应关系字典 school_class = {\'Beijing\':[\'python\',\'linux\'],\'Shanghai\':[\'go\']}
import logging from conf import config def logger_file(): #生成logger对象 whw_logger = logging.getLogger(\'logs.log\') whw_logger.setLevel(logging.INFO) #生成handler对象 whw_fh = logging.FileHandler(config.LOGGER) whw_fh.setLevel(logging.INFO) #生成Formatter对象 file_formatter = logging.Formatter(\' %(asctime)s - %(name)s - %(levelname)s - %(message)s \') #把formatter对象绑定到handler对象中 whw_fh.setFormatter(file_formatter) # 把handler对象绑定到logger对象中 whw_logger.addHandler(whw_fh) return whw_logger def write_log(msg): log_obj = logger_file() log_obj.info(msg) log_obj.handlers.pop()
import logging from conf import config def logger_file(): #生成logger对象 whw_logger = logging.getLogger(\'logs.log\') whw_logger.setLevel(logging.INFO) #生成handler对象 whw_fh = logging.FileHandler(config.LOGGER) whw_fh.setLevel(logging.INFO) #生成Formatter对象 file_formatter = logging.Formatter(\' %(asctime)s - %(name)s - %(levelname)s - %(message)s \') #把formatter对象绑定到handler对象中 whw_fh.setFormatter(file_formatter) # 把handler对象绑定到logger对象中 whw_logger.addHandler(whw_fh) return whw_logger def write_log(msg): log_obj = logger_file() log_obj.info(msg) log_obj.handlers.pop()
import sys import os from core.manager import Manager from core.teacher import Teacher from core.student import Student from conf import config from core import my_pickle from .other_logics import file_name,show_classes,show_student_score def login(): \'\'\' 登录函数,应该先到conf.config中先读取userinfo的文件路径。 再读取userinfo文件中的信息,对用户名与密码进行查验 登陆成功后查看这个人的身份来确定进入哪一个视图 :return: \'\'\' while 1: print( \'\033[1;32m请选择用户视图:\n\033[0m\', \'1:管理员视图\n\', \'2:讲师视图\n\', \'3:学生视图\n\' ) choice = input(\'请选择相应视图的编号:\') if not choice.isdigit() or int(choice)<=0 or int(choice)>3: print(\'\033[1;31m请输入正确的编号!\033[0m\') continue else: username = input(\'用户名:\') password = input(\'密 码:\') user_identity = config.USER_DICT[choice] #打开userinfo文件... with open(config.USERINFO,\'r\',encoding=\'utf-8\') as f: for line in f: user_name,pass_word,identity = line.strip().split(\'|\') #必须是用户名 密码 身份 三个全部一致才能登陆成功 if user_name == username and password == pass_word and user_identity == identity: print(\'\033[1;32m%s 用户 %s 登陆成功!\033[0m\' % (user_identity,username)) #以字典形式返回用户名 身份 return {\'username\':username,\'identity\':identity} else: print(\'\033[1;31m抱歉,输入有误,登陆失败!\033[0m\') def main(): \'\'\' 打印欢迎信息 调用login()——得到一个返回值:用户的姓名与身份 打印用户身份的功能菜单 如果用户想要调用任何方法,应该通过角色的对象调用,跳转到对应对象的方法里 :return: \'\'\' print(\'\033[0;35m欢迎进入学生选课系统!\033[0m\') ret = login() if ret: while 1: #管理员登陆 if ret[\'identity\'] == \'Manager\': print(\'\033[0;32m******************\033[0m\') role_class = getattr(sys.modules[__name__],ret[\'identity\']) #将类实例化成相应的对象 obj = role_class(ret[\'username\']) while 1: print(\'\033[0;32m******************\033[0m\') for i,v in enumerate(role_class.menu,1): print(i,v[0]) #避免输入不合法,利用异常处理 choice = input(\'\033[0;32m请输入您要进行的操作编号:\033[0m\') if not choice.isdigit(): print(\'\033[1;31m请输入数字!\033[0m\') break choice_int = int(choice) if choice_int < 1 or choice_int > 9: print(\'\033[1;31m抱歉,请输入正确的编号!\033[0m\') break ##进行第二次的反射,后面加了括号直接执行了 getattr(obj,role_class.menu[choice_int-1][1])() #讲师登陆 if ret[\'identity\'] == \'Teacher\': print(\'\033[0;32m******************\033[0m\') global teacher_school #反射:从本模块找到Teacher类 teacher_class = getattr(sys.modules[__name__],ret[\'identity\']) pk_teacher = my_pickle.MyPickle(config.TEACHER_OBJ) ob_teacher = pk_teacher.loaditer() for i in ob_teacher: if i.name == ret[\'username\']: teacher_school = i.school #利用找到的Teacher类与用户输入的name、school实例化讲师对象 teacher_obj = teacher_class(ret[\'username\'],teacher_school) while 1: print(\'\033[0;32m******************\033[0m\') for i,v in enumerate(teacher_class.menu,1): print(i,v[0]) choice = input(\'\033[0;32m请输入您要进行的操作编号:\033[0m\') if choice.isdigit() and 0 < int(choice) < 5: choice_int = int(choice) #第二次反射,后面加了括号,直接执行就行 getattr(teacher_obj,teacher_class.menu[choice_int-1][1])() else: print(\'\033[1;31m抱歉,请输入正确的编号!\033[0m\') #学生登录——需要输入班级 if ret[\'identity\'] == \'Student\': global stu_status stu_status = False global stu_class print(\'\033[0;32m******************\033[0m\') class_input = input(\'请输入您所在的班级:\').strip() #判断输入的班级是否存在 if class_input not in file_name(config.STUDENTINFO): print(\'\033[1;31m抱歉,请输入正确的班级!\033[0m\') else: #判断输入的班级有没有登陆的学生name pk_student = my_pickle.MyPickle(os.path.join(config.STUDENTINFO,class_input)) obj_student = pk_student.loaditer() for i in obj_student: #找到了这个学生对象 if i.name == ret[\'username\']: #将这个班级赋值给global变量stu_class stu_class = i.clas stu_status = True #说明成功找到了该学生的对象 if stu_status == True: # 第一次反射 student_class = getattr(sys.modules[__name__], ret[\'identity\']) #实例化 student_obj = student_class(ret[\'username\'],stu_class) while 1: print(\'\033[0;32m******************\033[0m\') for i,v in enumerate(student_obj.menu,1): print(i,v[0]) choice = input(\'请输入您要进行的操作编号:\') if choice.isdigit() and ( 0 < int(choice) < 3): if choice == \'1\': show_student_score(ret[\'username\'],class_input) elif choice == \'2\': exit() else: print(\'\033[1;31m请输入正确的操作编号!\033[0m\') else: print(\'\033[1;31m抱歉您不在这个班级!\033[0m\') else: print(\'\033[1;31m请输入正确的用户编号\033[0m\')
#首先,以管理员的身份登录 #登录后 应该实例化一个对应身份的对象manager_obj = manager(name) #管理员对象可以调用所有的方法 from conf import config from core import teacher from core import my_pickle from core import student from core import school from .other_logics import file_name from .logger import logger_file from .logger import write_log import os #管理员类 class Manager: menu =[ (\'创建讲师账号\',\'create_teacher\'),(\'创建学生账号\',\'create_student\'), (\'创建班级\', \'create_classes\'), (\'查看学校\',\'show_school\'), (\'查看课程\',\'show_courses\'),(\'查看讲师\',\'show_teachers\'), (\'查看班级\',\'show_classes\'),(\'为班级指定老师\',\'bound_class_teacher\'), (\'退出\',\'exit\') ] def __init__(self,name): self.name = name #相当于拿到了一个对象,这个对象里面只存了文件的名字 self.teacher_pickle_obj = my_pickle.MyPickle(config.TEACHER_OBJ) #拿到 mypickle_obj self.school_pickle_obj = my_pickle.MyPickle(config.SCHOOLINFO) self.classes_pickle_obj = my_pickle.MyPickle(config.CLASSES_OBJ) self.course_pickle_obj = my_pickle.MyPickle(config.COURSE_OBJ) def exit(self): exit() #往文件里面添加内容的时候写成统一的方法 #因为它既没有引用类的属性,也没有引用对象的属性,所以把它做成非绑定方法 @staticmethod def userinfo_handler(content): with open(config.USERINFO,\'a\') as f: f.write(\'\n%s\' % content) def show(self,pickle_obj): #反射 pick_obj = getattr(self,pickle_obj) #执行一个生成器函数就拿到一个生成器对象,这里拿到的每一个值,都是生成器返回的对象 load_g = pick_obj.loaditer() for course_obj in load_g: for i in course_obj.__dict__:#### print(\'%s: %s\'%(i,course_obj.__dict__[i])) print(\'*\' * 20) def show_school(self): print(\'校区信息如下:\') for i,v in enumerate(config.school_class,1): print(\'%s: %s\'% (i,v)) def show_teachers(self): self.show(\'teacher_pickle_obj\') def show_courses(self): print(\'课程信息如下:\') for i,v in enumerate(config.school_class): print(\'学校:%s-->课程:%s\' % (v,config.school_class[v])) def show_classes(self): self.show(\'classes_pickle_obj\') def create_teacher(self): l = [] with open(config.USERINFO,\'r\') as f: for line in f: username,v,b = line.strip().split(\'|\') l.append(username) teacher_name = input(\'请输入老师的姓名:\') if teacher_name in l: print(\'\033[1;31m该讲师已经存在!\033[0m\') return teacher_pass = input(\'请输入老师的密码:\') self.show_school() teacher_school = input(\'请输入所属的学校:(Beijing|Shanghai)\') #存入文件 content = \'%s|%s|Teacher\' % (teacher_name,teacher_pass) Manager.userinfo_handler(content) #根据输入的姓名与学校值实例化一个老师对象 teacher1 = teacher.Teacher(teacher_name,teacher_school)###实例化 self.teacher_pickle_obj.dump(teacher1) print(\'\033[0;32m讲师创建成功!\033[0m\') write_log(\'创建了讲师:%s\' % teacher_name) def create_classes(self): #注意,新建的班级名字不能是已经存在的 classes_names = file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i,v in enumerate(classes_names,1): print(\'%s: %s\' % (i,v)) class_name = input(\'请输入您要新建的班级名称:\') if class_name in classes_names: print(\'\033[1;31m该班级已经存在!\033[0m\') return school_name = input(\'请输入所属的学校:(Beijing|Shanghai)\') if school_name not in \'Beijing|Shanghai\'.split(\'|\'): print(\'\033[1;31m请输入正确的学校!\033[0m\') return course_name = input(\'请输入课程名称:(python|linux|go)\') if course_name not in \'python|linux|go\'.split(\'|\'): print(\'\033[1;31m请输入正确的课程!\033[0m\') return #判断 Beijing只能有python与linux,Shanghai只能有go: if (school_name == \'Beijing\' and (course_name ==\'python\' or course_name == \'linux\')) or (school_name == \'Shanghai\' and course_name == \'go\'): #如果符合条件的话新建一个路径 student_path = os.path.join(config.STUDENTINFO,class_name) #利用上面的路径创建一个空文件 open(student_path,\'w\').close() class_obj = school.Classes(school_name,class_name,course_name) #利用pickle dump实例化的对象,这一点json做不到! self.classes_pickle_obj.dump(class_obj)####### print(\'课程 %s 创建成功!\' % course_name) write_log(\'创建了课程:%s\' % course_name) else: print(\'\033[1;31m您填写的学校与课程的关系不存在!\033[0m\') return def create_student(self): student_name = input(\'请输入学生姓名:\') student_pass = input(\'请输入学生密码:\') #列举出所有存在的班级 classes_names = file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i, v in enumerate(classes_names, 1): print(\'%s: %s\' % (i, v)) student_class = input(\'请输入学生所在的班级:\') class_g = self.classes_pickle_obj.loaditer() for clas in class_g: #这里有既有班级名卡控,不用做判断了 if clas.name == student_class: #先把用户名、密码、角色写入userinfo文件中 content = \'%s|%s|Student\' % (student_name,student_pass) Manager.userinfo_handler(content) #实例化 stu_obj = student.Student(student_name,clas) student_path = os.path.join(config.STUDENTINFO,student_class) my_pickle.MyPickle(student_path).dump(stu_obj) print(\'学生 %s 创建成功!\' % student_name) write_log(\'学生 %s 创建成功!\' % student_name) return else: print(\'\033[1;31m输入错误,创建学生失败!\033[0m\') #for...else 语句 def bound_class_teacher(self): global a global status status = False #显示既有的班级 classes_names =file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i, v in enumerate(classes_names, 1): print(\'%s: %s\' % (i, v)) class_name = input(\'请输入要指定的班级:\') #判断一下输入的班级是否存在 if class_name not in classes_names: print(\'\033[1;31m抱歉,没有这个班级!\033[0m\') return #显示既有讲师 print(\'所有讲师信息为:\') self.show_teachers() teacher_name = input(\'请输入需要指定的讲师:\') #利用teacher_obj文件实例化出一个可迭代的对象 teach_g = self.teacher_pickle_obj.loaditer() #遍历这个可迭代的对象 for teacher_obj in teach_g: # 前提是姓名是唯一的,找到了对应的老师! if teacher_obj.name == teacher_name: if class_name in teacher_obj.classes: print(\'\033[1;31m本教师已经与该课程有了绑定关系,请勿重复绑定!\033[0m\') return #将符合要求的对象赋值给一个global变量,待后面处理 teacher_obj.classes.append(class_name) a = teacher_obj #判断成功修改 status = True #必须等遍历完文件关闭后才能再进行edit操作 if status == True: file1 = my_pickle.MyPickle(config.TEACHER_OBJ) file1.edit(a) print(a.name,a.classes) print(\'绑定成功!\') write_log(\'班级%s绑定了讲师:%s\' % (class_name,teacher_name)) a = None status = False else: print(\'\033[1;31m录入有误,绑定失败!\033[0m\')
#首先,以管理员的身份登录 #登录后 应该实例化一个对应身份的对象manager_obj = manager(name) #管理员对象可以调用所有的方法 from conf import config from core import teacher from core import my_pickle from core import student from core import school from .other_logics import file_name from .logger import logger_file from .logger import write_log import os #管理员类 class Manager: menu =[ (\'创建讲师账号\',\'create_teacher\'),(\'创建学生账号\',\'create_student\'), (\'创建班级\', \'create_classes\'), (\'查看学校\',\'show_school\'), (\'查看课程\',\'show_courses\'),(\'查看讲师\',\'show_teachers\'), (\'查看班级\',\'show_classes\'),(\'为班级指定老师\',\'bound_class_teacher\'), (\'退出\',\'exit\') ] def __init__(self,name): self.name = name #相当于拿到了一个对象,这个对象里面只存了文件的名字 self.teacher_pickle_obj = my_pickle.MyPickle(config.TEACHER_OBJ) #拿到 mypickle_obj self.school_pickle_obj = my_pickle.MyPickle(config.SCHOOLINFO) self.classes_pickle_obj = my_pickle.MyPickle(config.CLASSES_OBJ) self.course_pickle_obj = my_pickle.MyPickle(config.COURSE_OBJ) def exit(self): exit() #往文件里面添加内容的时候写成统一的方法 #因为它既没有引用类的属性,也没有引用对象的属性,所以把它做成非绑定方法 @staticmethod def userinfo_handler(content): with open(config.USERINFO,\'a\') as f: f.write(\'\n%s\' % content) def show(self,pickle_obj): #反射 pick_obj = getattr(self,pickle_obj) #执行一个生成器函数就拿到一个生成器对象,这里拿到的每一个值,都是生成器返回的对象 load_g = pick_obj.loaditer() for course_obj in load_g: for i in course_obj.__dict__:#### print(\'%s: %s\'%(i,course_obj.__dict__[i])) print(\'*\' * 20) def show_school(self): print(\'校区信息如下:\') for i,v in enumerate(config.school_class,1): print(\'%s: %s\'% (i,v)) def show_teachers(self): self.show(\'teacher_pickle_obj\') def show_courses(self): print(\'课程信息如下:\') for i,v in enumerate(config.school_class): print(\'学校:%s-->课程:%s\' % (v,config.school_class[v])) def show_classes(self): self.show(\'classes_pickle_obj\') def create_teacher(self): l = [] with open(config.USERINFO,\'r\') as f: for line in f: username,v,b = line.strip().split(\'|\') l.append(username) teacher_name = input(\'请输入老师的姓名:\') if teacher_name in l: print(\'\033[1;31m该讲师已经存在!\033[0m\') return teacher_pass = input(\'请输入老师的密码:\') self.show_school() teacher_school = input(\'请输入所属的学校:(Beijing|Shanghai)\') #存入文件 content = \'%s|%s|Teacher\' % (teacher_name,teacher_pass) Manager.userinfo_handler(content) #根据输入的姓名与学校值实例化一个老师对象 teacher1 = teacher.Teacher(teacher_name,teacher_school)###实例化 self.teacher_pickle_obj.dump(teacher1) print(\'\033[0;32m讲师创建成功!\033[0m\') write_log(\'创建了讲师:%s\' % teacher_name) def create_classes(self): #注意,新建的班级名字不能是已经存在的 classes_names = file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i,v in enumerate(classes_names,1): print(\'%s: %s\' % (i,v)) class_name = input(\'请输入您要新建的班级名称:\') if class_name in classes_names: print(\'\033[1;31m该班级已经存在!\033[0m\') return school_name = input(\'请输入所属的学校:(Beijing|Shanghai)\') if school_name not in \'Beijing|Shanghai\'.split(\'|\'): print(\'\033[1;31m请输入正确的学校!\033[0m\') return course_name = input(\'请输入课程名称:(python|linux|go)\') if course_name not in \'python|linux|go\'.split(\'|\'): print(\'\033[1;31m请输入正确的课程!\033[0m\') return #判断 Beijing只能有python与linux,Shanghai只能有go: if (school_name == \'Beijing\' and (course_name ==\'python\' or course_name == \'linux\')) or (school_name == \'Shanghai\' and course_name == \'go\'): #如果符合条件的话新建一个路径 student_path = os.path.join(config.STUDENTINFO,class_name) #利用上面的路径创建一个空文件 open(student_path,\'w\').close() class_obj = school.Classes(school_name,class_name,course_name) #利用pickle dump实例化的对象,这一点json做不到! self.classes_pickle_obj.dump(class_obj)####### print(\'课程 %s 创建成功!\' % course_name) write_log(\'创建了课程:%s\' % course_name) else: print(\'\033[1;31m您填写的学校与课程的关系不存在!\033[0m\') return def create_student(self): student_name = input(\'请输入学生姓名:\') student_pass = input(\'请输入学生密码:\') #列举出所有存在的班级 classes_names = file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i, v in enumerate(classes_names, 1): print(\'%s: %s\' % (i, v)) student_class = input(\'请输入学生所在的班级:\') class_g = self.classes_pickle_obj.loaditer() for clas in class_g: #这里有既有班级名卡控,不用做判断了 if clas.name == student_class: #先把用户名、密码、角色写入userinfo文件中 content = \'%s|%s|Student\' % (student_name,student_pass) Manager.userinfo_handler(content) #实例化 stu_obj = student.Student(student_name,clas) student_path = os.path.join(config.STUDENTINFO,student_class) my_pickle.MyPickle(student_path).dump(stu_obj) print(\'学生 %s 创建成功!\' % student_name) write_log(\'学生 %s 创建成功!\' % student_name) return else: print(\'\033[1;31m输入错误,创建学生失败!\033[0m\') #for...else 语句 def bound_class_teacher(self): global a global status status = False #显示既有的班级 classes_names =file_name(config.STUDENTINFO) print(\'\033[0;32m已经存在的班级如下:\033[0m\') for i, v in enumerate(classes_names, 1): print(\'%s: %s\' % (i, v)) class_name = input(\'请输入要指定的班级:\') #判断一下输入的班级是否存在 if class_name not in classes_names: print(\'\033[1;31m抱歉,没有这个班级!\033[0m\') return #显示既有讲师 print(\'所有讲师信息为:\') self.show_teachers() teacher_name = input(\'请输入需要指定的讲师:\') #利用teacher_obj文件实例化出一个可迭代的对象 teach_g = self.teacher_pickle_obj.loaditer() #遍历这个可迭代的对象 for teacher_obj in teach_g: # 前提是姓名是唯一的,找到了对应的老师! if teacher_obj.name == teacher_name: if class_name in teacher_obj.classes: print(\'\033[1;31m本教师已经与该课程有了绑定关系,请勿重复绑定!\033[0m\') return #将符合要求的对象赋值给一个global变量,待后面处理 teacher_obj.classes.append(class_name) a = teacher_obj #判断成功修改 status = True #必须等遍历完文件关闭后才能再进行edit操作 if status == True: file1 = my_pickle.MyPickle(config.TEACHER_OBJ) file1.edit(a) print(a.name,a.classes) print(\'绑定成功!\') write_log(\'班级%s绑定了讲师:%s\' % (class_name,teacher_name)) a = None status = False else: print(\'\033[1;31m录入有误,绑定失败!\033[0m\')
import pickle import os class MyPickle: def __init__(self,filename): #只是用文件名来实例化对象,并没有打开文件 self.filename = filename #每次需要dump一个文件的时候需要先打开一个文件 def dump(self,obj): with open(self.filename,\'ab\') as f: # 利用pickle dump实例化的对象,这一点json做不到! pickle.dump(obj,f) #每次需要load文件的时候,需要转格式 def loaditer(self): with open(self.filename,\'rb\') as f: while 1: try: #不能把所有的文件都同时读出来,需要每读一个文件再做一次操作 obj = pickle.load(f) yield obj except: break def close_file(): f.close() #"修改"已经被dump的文件 def edit(self,obj): #利用原文件.bak这个路径名实例化一个新的对象,然后利用dump跟loaditer方法将满足条件的信息写进这个bak文件中,最后replace~~ f_temp = MyPickle(self.filename+\'.bak\') with open(self.filename,\'rb+\') as f: for i in self.loaditer(): if i.name == obj.name: f_temp.dump(obj) else: f_temp.dump(i) os.replace(self.filename+\'.bak\',self.filename)
import pickle import os class MyPickle: def __init__(self,filename): #只是用文件名来实例化对象,并没有打开文件 self.filename = filename #每次需要dump一个文件的时候需要先打开一个文件 def dump(self,obj): with open(self.filename,\'ab\') as f: # 利用pickle dump实例化的对象,这一点json做不到! pickle.dump(obj,f) #每次需要load文件的时候,需要转格式 def loaditer(self): with open(self.filename,\'rb\') as f: while 1: try: #不能把所有的文件都同时读出来,需要每读一个文件再做一次操作 obj = pickle.load(f) yield obj except: break def close_file(): f.close() #"修改"已经被dump的文件 def edit(self,obj): #利用原文件.bak这个路径名实例化一个新的对象,然后利用dump跟loaditer方法将满足条件的信息写进这个bak文件中,最后replace~~ f_temp = MyPickle(self.filename+\'.bak\') with open(self.filename,\'rb+\') as f: for i in self.loaditer(): if i.name == obj.name: f_temp.dump(obj) else: f_temp.dump(i) os.replace(self.filename+\'.bak\',self.filename)
import os from conf import config from .my_pickle import MyPickle # 查找studentinfo文件夹下文件列表的方法 def file_name(file_dir): for root, dirs, files in os.walk(file_dir): return files # 显示etudentinfo文件夹下所有文件名的方法 def show_classes(): for root, dirs, files in os.walk(config.STUDENTINFO): for i, v in enumerate(files, 1): print(\'%s : %s\' % (i, v)) # 因为学生需要班级来实例化,而班级是一个个的文件,所以显示学生成绩的方法写在函数里 def show_student_score(name, file): class_path = os.path.join(config.STUDENTINFO, file) pk_stu = MyPickle(class_path) obj_stu = pk_stu.loaditer() for i in obj_stu: if i.name == name: print(\'%s 的成绩为:%s\' % (name, i.score)) return
import os from conf import config from .my_pickle import MyPickle # 查找studentinfo文件夹下文件列表的方法 def file_name(file_dir): for root, dirs, files in os.walk(file_dir): return files # 显示etudentinfo文件夹下所有文件名的方法 def show_classes(): for root, dirs, files in os.walk(config.STUDENTINFO): for i, v in enumerate(files, 1): print(\'%s : %s\' % (i, v)) # 因为学生需要班级来实例化,而班级是一个个的文件,所以显示学生成绩的方法写在函数里 def show_student_score(name, file): class_path = os.path.join(config.STUDENTINFO, file) pk_stu = MyPickle(class_path) obj_stu = pk_stu.loaditer() for i in obj_stu: if i.name == name: print(\'%s 的成绩为:%s\' % (name, i.score)) return
class Classes: def __init__(self,school,name,course): self.school = school self.name = name #班级名称,, self.course = course #科目 python go linux #self.student_path = student_path #学生信息文件的绝对路径
class Classes: def __init__(self,school,name,course): self.school = school self.name = name #班级名称,, self.course = course #科目 python go linux #self.student_path = student_path #学生信息文件的绝对路径
class Student: menu = [(\'查看自己的成绩:\',\'show_my_score\'), (\'退出\',\'exit\') ] def __init__(self,name,clas): self.name = name self.clas = clas self.score = \'\'
class Student: menu = [(\'查看自己的成绩:\',\'show_my_score\'), (\'退出\',\'exit\') ] def __init__(self,name,clas): self.name = name self.clas = clas self.score = \'\'
from core import my_pickle from conf import config import os # class Classes: # def __init__(self,school_name,class_name,class_kind): # self.school_name = school_name #分校 # self.class_name = class_name #班级名 python_s11 # self.class_kind = class_kind #班级科目 python go linux # self.student = [\'student_obj\'] class Course: def __init__(self,course_name,course_period,course_price): self.course_name = course_name self.course_period = course_period#周期 self.course_price = course_price class Teacher: menu = [ (\'查看本人所授班级\',\'show_classes\'), (\'查看所授班级学生\',\'show_class_students\'), (\'修改学生成绩\',\'reverse_grade\'), (\'退出\',\'exit\') ] def __init__(self,name,school): self.name = name self.school = school self.classes = [] def exit(self): exit() def show_classes(self): print(\'\033[1;32m您所教授的班级为:\033[0m\') global classes_list #利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) #利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() #遍历~ for i in teacher_obj: #找到对应的讲师 if i.name == self.name: #班级列表赋值给classes_list classes_list = i.classes #显示这个classes_list列表,就是这个老师教的班级 for i,v in enumerate(classes_list,1): print(\'%s: %s\' % (i,v)) return def show_class_students(self): clas = input(\'请输入您要查找学生所在的班级:\').strip() global classes_list1 # 利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) # 利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() # 遍历~ for i in teacher_obj: # 找到对应的讲师 if i.name == self.name: # 班级列表赋值给classes_list classes_list1 = i.classes #判断输入的班级是否在老师所教班级的列表里 if clas in classes_list1: #得到这个班级文件的路径 class_path = os.path.join(config.STUDENTINFO,clas) #利用这个班级文件路径再实例化一个MyPickle对象... pk_class = my_pickle.MyPickle(class_path) class_obj = pk_class.loaditer() for i in class_obj: print(\'学生姓名:%s;学生成绩:%s\' % (i.name,i.score)) else: print(\'\033[1;31m抱歉,您没有教这个班级!\033[0m\') def reverse_grade(self): self.show_classes() clas = input(\'请输入您要修改的学生所在的班级:\').strip() global classes_list1 global stu1 global s_status s_status = False # 利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) # 利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() # 遍历~ for i in teacher_obj: # 找到对应的讲师 if i.name == self.name: # 班级列表赋值给classes_list classes_list1 = i.classes # 判断输入的班级是否在老师所教班级的列表里 if clas in classes_list1: # 得到这个班级文件的路径 class_path = os.path.join(config.STUDENTINFO, clas) # 利用这个班级文件路径再实例化一个MyPickle对象... pk_class = my_pickle.MyPickle(class_path) class_obj = pk_class.loaditer() choice_stu = input(\'请输入您要修改成绩的学生:\').strip() score = input(\'请输入该学生修改后的成绩:\').strip() for i in class_obj: if i.name == choice_stu: i.score = score #将这个学生对象赋值给global变量stu1 stu1 = i s_status = True else: print(\'\033[1;31m抱歉,您没有教这个班级!\033[0m\') return if s_status == True: stu_file = my_pickle.MyPickle(os.path.join(config.STUDENTINFO,clas)) stu_file.edit(stu1) print(\'学生:%s;成绩:%s\' % (stu1.name,stu1.score)) print(\'\033[1;32m修改成功!\n\033[0m\') s_status = False else: print(\'\033[1;31m录入有误,操作失败!\033[0m\')
from core import my_pickle from conf import config import os # class Classes: # def __init__(self,school_name,class_name,class_kind): # self.school_name = school_name #分校 # self.class_name = class_name #班级名 python_s11 # self.class_kind = class_kind #班级科目 python go linux # self.student = [\'student_obj\'] class Course: def __init__(self,course_name,course_period,course_price): self.course_name = course_name self.course_period = course_period#周期 self.course_price = course_price class Teacher: menu = [ (\'查看本人所授班级\',\'show_classes\'), (\'查看所授班级学生\',\'show_class_students\'), (\'修改学生成绩\',\'reverse_grade\'), (\'退出\',\'exit\') ] def __init__(self,name,school): self.name = name self.school = school self.classes = [] def exit(self): exit() def show_classes(self): print(\'\033[1;32m您所教授的班级为:\033[0m\') global classes_list #利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) #利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() #遍历~ for i in teacher_obj: #找到对应的讲师 if i.name == self.name: #班级列表赋值给classes_list classes_list = i.classes #显示这个classes_list列表,就是这个老师教的班级 for i,v in enumerate(classes_list,1): print(\'%s: %s\' % (i,v)) return def show_class_students(self): clas = input(\'请输入您要查找学生所在的班级:\').strip() global classes_list1 # 利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) # 利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() # 遍历~ for i in teacher_obj: # 找到对应的讲师 if i.name == self.name: # 班级列表赋值给classes_list classes_list1 = i.classes #判断输入的班级是否在老师所教班级的列表里 if clas in classes_list1: #得到这个班级文件的路径 class_path = os.path.join(config.STUDENTINFO,clas) #利用这个班级文件路径再实例化一个MyPickle对象... pk_class = my_pickle.MyPickle(class_path) class_obj = pk_class.loaditer() for i in class_obj: print(\'学生姓名:%s;学生成绩:%s\' % (i.name,i.score)) else: print(\'\033[1;31m抱歉,您没有教这个班级!\033[0m\') def reverse_grade(self): self.show_classes() clas = input(\'请输入您要修改的学生所在的班级:\').strip() global classes_list1 global stu1 global s_status s_status = False # 利用teacher_obj文件实例化一个MyPickle对象 teacher_file = my_pickle.MyPickle(config.TEACHER_OBJ) # 利用loaditer得到一个可迭代的对象 teacher_obj = teacher_file.loaditer() # 遍历~ for i in teacher_obj: # 找到对应的讲师 if i.name == self.name: # 班级列表赋值给classes_list classes_list1 = i.classes # 判断输入的班级是否在老师所教班级的列表里 if clas in classes_list1: # 得到这个班级文件的路径 class_path = os.path.join(config.STUDENTINFO, clas) # 利用这个班级文件路径再实例化一个MyPickle对象... pk_class = my_pickle.MyPickle(class_path) class_obj = pk_class.loaditer() choice_stu = input(\'请输入您要修改成绩的学生:\').strip() score = input(\'请输入该学生修改后的成绩:\').strip() for i in class_obj: if i.name == choice_stu: i.score = score #将这个学生对象赋值给global变量stu1 stu1 = i s_status = True else: print(\'\033[1;31m抱歉,您没有教这个班级!\033[0m\') return if s_status == True: stu_file = my_pickle.MyPickle(os.path.join(config.STUDENTINFO,clas)) stu_file.edit(stu1) print(\'学生:%s;成绩:%s\' % (stu1.name,stu1.score)) print(\'\033[1;32m修改成功!\n\033[0m\') s_status = False else: print(\'\033[1;31m录入有误,操作失败!\033[0m\')
演示如下:
模拟一个SSH“远程”执行命令并获取命令结果的一个程序:
1、在C/S架构下,当客户端与服务器建立连接(这里以TCP为例)后,二者可以不断的进行数据交互。SSH远程可以实现的效果是客户端输入命令可以在服务器中执行并且可以将结果返回给客户端。但是需要注意的一点事:客户端的“命令”在计算机看来仅仅是“字符串”而已,而真正需要执行的“命令”必须是操作系统能够识别的!也就是说,真正“执行命令”与“返回结果”的地方仍然是服务器端。在客户端我们只是“显示”出了一个这样的知执行假象而已。
那么,这样的一个SSH远程执行程序的具体流程是怎样的呢?
下图是这样的一个简单过程:
简单的过程说明:
对于客户端来讲,用户首先输入了str类型的命令command,然后程序将这个str类型的字符串encode成能够在网络中传输的bytes类型的数据并发送给服务器;服务器接收到以后将其重新解码为str,然后在本段“执行”这段代码生成str类型的结果,接着再进行编码传给客户端,客户端接收到以后解码为人能识别的str类型最终输出到屏幕上。
2、这个过程有两个大问题:一个是服务器端是如何进行“代码执行”的,另一个就是客户端与服务器端str与bytes格式数据的编解码问题。
2.1、对于第一个问题,我们利用subprocess模块下的Popen方法可以将str类型的“虚假命令”转换为操作系统能够识别的“真是命令”:
import subprocess cmd = input(\'>>>:\') obj = subprocess.Popen(cmd,shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) print(obj.stdout.read().decode(\'gbk\')) print(obj.stderr.read().decode(\'gbk\'))
这里有几点需要说明:
(1)可以把obj看成是一个管道,它一次性的、毫无保留将所有执行结果都拿到,再一次取值时里面没有了数据,这就像一个“管道”一样,里面的数据全部取完后就“无所保留”了。
(2)关于输出结果解码的问题:subprocess模块下的Popen方法在不同的操作系统下结果的编码方式不同:linux下为utf-8模式,windows下为gbk模式。由于本例是在windows操作系统下进行的,所以我们在输出是要进行gbk的方式解码才能看到结果。
(3)最终的结果包含正确的信息stdout与错误的结果stderr(当用户输入一个不存在的命令时产生)。
2.2、第二个编解码问题可以看下图具体的描述:
这里需要注意的一点是:本例是在windows操作系统下执行的,所以result的编码方式要以gbk模式进行,这样才不会在客户端中产生乱码。
程序的代码以及运行结果为:
import socket import subprocess server_whw = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_whw.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server_whw.bind((\'127.0.0.1\',8008)) server_whw.listen(5) print(\'Starting......\') conn,client_addr = server_whw.accept() while 1: try: cmd = conn.recv(8096) #将从客户端传来的命令信息进行处理 obj = subprocess.Popen(cmd.decode(\'utf-8\'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #将结果返回给客户端 stdout = obj.stdout.read().decode(\'gbk\') stderr = obj.stderr.read().decode(\'gbk\') std1 = stdout.encode(\'gbk\') std2 = stderr.encode(\'gbk\') conn.send(std1) conn.send(std2) except ConnectionResetError: print(\'连接断开\') break conn.close() server_whw.close()
import socket import subprocess server_whw = socket.socket(socket.AF_INET,socket.SOCK_STREAM) server_whw.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1) server_whw.bind((\'127.0.0.1\',8008)) server_whw.listen(5) print(\'Starting......\') conn,client_addr = server_whw.accept() while 1: try: cmd = conn.recv(8096) #将从客户端传来的命令信息进行处理 obj = subprocess.Popen(cmd.decode(\'utf-8\'),shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE) #将结果返回给客户端 stdout = obj.stdout.read().decode(\'gbk\') stderr = obj.stderr.read().decode(\'gbk\') std1 = stdout.encode(\'gbk\') std2 = stderr.encode(\'gbk\') conn.send(std1) conn.send(std2) except ConnectionResetError: print(\'连接断开\') break conn.close() server_whw.close()
import socket client_whw = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_whw.connect((\'127.0.0.1\',8008)) while 1: cmd = input(\'请输入命令:\') if not cmd: continue client_whw.send(cmd.encode(\'utf-8\')) data = client_whw.recv(1024) print(\'命令结果:\n\',data.decode(\'gbk\')) # client_whw.close()
import socket client_whw = socket.socket(socket.AF_INET,socket.SOCK_STREAM) client_whw.connect((\'127.0.0.1\',8008)) while 1: cmd = input(\'请输入命令:\') if not cmd: continue client_whw.send(cmd.encode(\'utf-8\')) data = client_whw.recv(1024) print(\'命令结果:\n\',data.decode(\'gbk\')) # client_whw.close()
程序演示:
当然,最终的结果出现了粘包问题~需要进行进一步的处理