python练习——moudule03——选课系统

开发简单的FTP:1. 用户登陆2. 上传/下载文件put/get3. 不同用户家目录不同home4. 查看当前目录下文件ls5. 充分使用面向对象知识

目录:

  1 import os,socket,optparse,json,time
  2
  3 STATUS_CODE ={
  4     200 : "操作成功",
  5     601 : ‘操作失败‘
  6 }
  7
  8 class FTPClient(object):
  9     def __init__(self):
 10         self.parser = optparse.OptionParser()
 11         self.parser.add_option(‘-H‘, ‘--host‘, dest=‘host‘, help=‘host of server‘)
 12         self.parser.add_option(‘-P‘,‘--port‘,type=‘int‘,dest= ‘port‘,help=‘port of server‘)
 13         self.parser.add_option(‘-u‘,‘--username‘,dest= ‘username‘,help=‘username‘)
 14         self.parser.add_option(‘-p‘,‘--password‘,dest= ‘password‘,help=‘password‘)
 15         (self.options,self.args) = self.parser.parse_args()
 16         self.verify_args()
 17         self.make_connection()
 18         self.header = {}
 19
 20     def make_connection(self):
 21         self.sock = socket.socket()
 22         self.sock.connect((self.options.host,self.options.port))
 23
 24     def verify_args(self):
 25         if self.options.host and self.options.port:
 26             if self.options.port > 0 and self.options.port<= 65535:
 27                 if self.options.username and self.options.password:
 28                     return True
 29                 else:
 30                     exit(‘check your username and password‘)
 31             else:
 32                 exit("worry Port!")
 33
 34         else:
 35             exit(‘Please check your host and port! They can not be null!‘)
 36
 37     def authenticate(self):
 38         ‘‘‘登陆验证‘‘‘
 39         # print(‘authenticating.........‘)
 40         # print(self.get_auth_result(self.options.username,self.options.password).get(‘code‘))
 41         if self.get_auth_result(self.options.username,self.options.password).get(‘code‘) == 200:
 42             self.header = {‘username‘:self.options.username}
 43             return True
 44         else:
 45             raise Exception(‘worry username or password!‘)
 46             # retry_count = 0
 47             # while retry_count < 3:
 48             #     user = input("username>>>").strip()
 49             #     password = input("password>>>").strip()
 50             #     self.get_auth_result(user,password)
 51             # else:
 52             #     retry_count += 1
 53     def get_auth_result(self,username,password):
 54         data = {
 55             ‘action‘ : ‘auth‘,
 56             ‘username‘ : username,
 57             ‘password‘ : password
 58         }
 59         # print(data)
 60         self.sock.sendall(json.dumps(data).encode())
 61         # print(‘send sucessfully‘)
 62         # print(self.get_response())
 63         # print(type(self.get_response()))
 64         return  self.get_response()
 65
 66     def get_response(self):
 67         ‘‘‘获取服务器结果‘‘‘
 68         recv = self.sock.recv(1024)
 69         recv = json.loads(recv.decode())
 70         # print(recv)
 71         print(‘response‘,recv)
 72         # print(type(recv))
 73         return recv
 74
 75     def opearte_cmd(self,cmd):
 76         # print(‘12345‘)
 77         # print(cmd,‘&&&&&&&&‘)
 78         if cmd is None :
 79             raise Exception(‘cmd cannot be null‘)
 80         cmd_list =cmd.split()
 81         if cmd_list[0] ==‘get‘ and len(cmd_list) == 2:
 82             self._get(cmd)
 83             return
 84         if cmd_list[0] ==‘put‘ and len(cmd_list) == 2:
 85             if os.path.exists(cmd_list[1]):
 86                 self._put(cmd)
 87                 return
 88         if cmd_list[0] ==‘ls‘:
 89             self._ls()
 90             return
 91         if cmd_list[0] ==‘exit‘:
 92             exit()
 93         else:
 94             raise Exception(‘cmd is worry!please try again later!‘)
 95
 96     def get_FileSize(self,filePath):
 97         fsize = os.path.getsize(filePath)
 98         # fsize = fsize / float(1024)
 99         # return round(fsize, 2)
100         return fsize
101     def _get(self,cmd):
102         cmd_list = cmd.split()
103         data = {
104             ‘header‘: self.header,
105             ‘action‘: ‘get‘,
106             ‘filename‘: cmd_list[1]
107         }
108         recv = self.sock.sendall(json.dumps(data).encode())
109         response = self.get_response()
110         print(‘recv‘,response)
111
112         if response.get(‘code‘) == 200:
113             file_size = response.get(‘file_size‘)
114             with open(cmd_list[1],‘wb‘) as f:
115                 recv_size = 0
116                 while recv_size < int(file_size):
117                     recv_data = self.sock.recv(1024)
118                     # print(recv_data)
119                     recv_size += len(recv_data)
120                     # print(recv_size)
121                     f.write(recv_data)
122                     self.sock.send(b‘1‘)
123                 print(self.get_response())
124             return
125         else:
126             raise Exception(‘worry with server in get file .‘)
127
128
129     def _put(self,cmd):
130         cmd_list = cmd.split()
131         filename = cmd_list[1].split(‘\\‘)[-1]
132         print(cmd_list[1])
133         file_size = self.get_FileSize(cmd_list[1])
134         data = {
135             ‘header‘: self.header,
136             ‘action‘: ‘put‘,
137             ‘filename‘: filename,
138             ‘file_size‘:file_size
139         }
140         self.sock.sendall(json.dumps(data).encode())
141         recv = self.get_response()
142         if recv.get(‘code‘) == 200:
143             print(os.path.exists(cmd_list[1]))
144             f = open(cmd_list[1],‘rb‘)
145             size = 0
146             for line in f:
147                 size += len(line)
148                 # print(size)
149                 # print(line)
150                 self.sock.send(line)
151                 self.sock.recv(1)
152             f.close()
153             print(‘recv:‘,self.get_response())
154             return True
155         else:
156             msg = {
157                 ‘code‘:recv.get(‘code‘),
158                 ‘message‘:  STATUS_CODE.get(recv.get(‘code‘))
159                    }
160             raise Exception(msg)
161
162     def _ls(self):
163         data = {
164             ‘header‘: self.header,
165             ‘action‘: ‘ls‘
166         }
167         self.sock.sendall(json.dumps(data).encode())
168         print(‘recv:‘, self.get_response())
169         return True
170
171 #python FTP1\Client\client.py -H 127.0.0.1 -P 9001 -u alex -p 1234
172
173     def interactive(self):
174         if self.authenticate():
175             print(‘start interactive‘.center(60,‘-‘))
176             while True:
177                 print(‘‘‘
178                 List of functions:
179                 get :   e.g:get XXX.txt,
180                 put :   e.g:put XXX.txt,
181                 ls  :   e.g:ls
182                 exit :  e.g:exit
183                 ‘‘‘)
184                 cmd = input("cmd>>>").strip()
185                 self.opearte_cmd(cmd)
186                 continue
187
188
189 #python FTP1\Client\client.py -H 127.0.0.1 -P 9001 -u alex -p 1234
190 # put C:\Users\Administrator\Desktop\noteForPython.txt
191 if __name__ == ‘__main__‘:
192     client = FTPClient()
193     client.interactive()

client.py

1 import os,sys
2 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
3 sys.path.append(base_dir)
4
5 from core import main
6
7 if __name__ == ‘__main__‘:
8     main.ArgvHandler()

server.py

 1 import os,sys
 2 base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
 3
 4 USER_HOME = ‘%s/home‘%(base_dir)
 5 LOG_DIR = ‘%s/log‘%(base_dir)
 6 LOG_level = ‘DEBUG‘
 7 ACCOUNT_FILE = ‘%s/db/account.ini‘%(base_dir)
 8
 9 HOST = ‘127.0.0.1‘
10 PORT = 9001

settings.py

  1 import socketserver,json,configparser,os,time
  2
  3 STATUS_CODE ={
  4     200 : "操作成功",
  5     601 : ‘操作失败‘
  6 }
  7 Base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
  8 from conf import settings
  9 class FTPHandler(socketserver.BaseRequestHandler):
 10     def handle(self):
 11         while True:
 12             print("welcome to FTPHander-handle-whileTrue...")
 13             self.data = self.request.recv(1024).strip()
 14             if  self.data is None:
 15                 print("Client is closed")
 16                 break
 17             print(self.client_address[0])
 18
 19             data = json.loads(self.data.decode())
 20
 21             if data.get(‘action‘) == ‘auth‘:
 22                 self._auth(data)
 23             elif data.get(‘action‘) in (‘put‘,‘get‘,‘ls‘):
 24                 func = getattr(self,‘_%s‘%data.get(‘action‘))
 25                 func(data)
 26             else:
 27                 print(‘invlid cmd‘)
 28                 self.send_response(601)
 29
 30
 31     def _auth(self,data):
 32         # print(data)
 33         parser = configparser.ConfigParser()
 34         parser.read(settings.ACCOUNT_FILE)
 35         section_list = parser.sections()
 36         if data.get(‘username‘) in section_list:
 37             true_pwd = parser.get(data.get(‘username‘),‘password‘)
 38             quation = parser.get(data.get(‘username‘),‘quation‘)
 39             # print(true_pwd,quation)
 40             # print(data.get(‘password‘))
 41             if true_pwd == data.get(‘password‘):
 42                 # print(‘1313‘)
 43                 self.send_response(200)
 44
 45
 46     # def _auth(self,*args,**kwargs):
 47     #     print(args.center(60,‘-‘))
 48     #     parser = configparser.ConfigParser()
 49     #     parser.read(settings.ACCOUNT_FILE)
 50     #     section_list = parser.sections()
 51     #     if args[‘username‘] in section_list:
 52     #         true_pwd = parser.get(args[‘username‘],‘password‘)
 53     #         quation = parser.get(args.get[‘username‘],‘quation‘)
 54     #         if true_pwd == args[‘password‘]:
 55     #             self.send_response(200)
 56         # if args.get(‘username‘) in section_list:
 57         #     true_pwd = parser.get(args.get(‘username‘),‘password‘)
 58         #     quation = parser.get(args.get(‘username‘),‘quation‘)
 59         #     if true_pwd == args.get(‘password‘):
 60         #         self.send_response(200)
 61
 62     def send_response(self,code,data=None):
 63         response ={‘code‘:code,‘msg‘:STATUS_CODE[code]}
 64         if data:
 65             response.update( data )
 66         self.request.send(json.dumps(response).encode())
 67
 68     def verify_data(self,*args):
 69         pass
 70
 71     def _put(self,data):
 72         print(‘start put......................................................‘)
 73         self.verify_data(data)
 74         if data.get(‘header‘) == {}:
 75             self.send_response(601)
 76         parser = configparser.ConfigParser()
 77         parser.read(settings.ACCOUNT_FILE)
 78         section_list = parser.sections()
 79         username_of_data = data.get(‘header‘).get(‘username‘)
 80         flag = username_of_data in section_list
 81         # print(flag)
 82         if flag:
 83             quation =  parser.get(username_of_data, ‘quation‘)
 84             # home_DIR = Base_dir.join(‘home\%s‘ % username_of_data)
 85             home_DIR = os.path.join(Base_dir,‘home\%s‘ % username_of_data)
 86             # print(home_DIR)
 87             user_exit_file = os.listdir(home_DIR)
 88             print(user_exit_file)
 89             size_exited = 0
 90             for filePath in user_exit_file:
 91                 filePath = os.path.join(home_DIR,filePath)
 92                 size_exited += self.get_FileSize(filePath)
 93
 94             puted_file_size = data.get(‘file_size‘)
 95
 96             if puted_file_size > int(quation) - size_exited:
 97                 self.send_response(601)
 98             else:
 99                 self.send_response(200)
100                 puted_filename = data.get(‘filename‘)
101                 if puted_filename in user_exit_file:
102                     puted_filename = ‘%s-1‘% puted_filename
103                 # filename = home_DIR.join(puted_filename)
104                 filename = os.path.join(home_DIR,puted_filename)
105                 get_FileSize = 0
106                 with open(filename,"wb") as f:
107                     while get_FileSize < puted_file_size:
108                         file_data = self.request.recv(1024)
109                         f.write(file_data)
110                         get_FileSize += len(file_data)
111                         self.request.send(b‘1‘)
112                         # print(file_data)
113                         # print(get_FileSize, puted_file_size)
114                     self.send_response(200)
115                 print(‘put successfully...‘.center(60,‘-‘))
116
117
118     def get_FileSize(self,filePath):
119         fsize = os.path.getsize(filePath)
120         # fsize = fsize / float(1024)
121         # return round(fsize, 2)
122         return fsize
123
124     def _get(self,data):
125         print(‘start get................‘)
126         # self.verify_data(data)
127         if data.get(‘header‘) == {}:
128             self.send_response(601)
129         parser = configparser.ConfigParser()
130         parser.read(settings.ACCOUNT_FILE)
131         section_list = parser.sections()
132         username_of_data = data.get(‘header‘).get(‘username‘)
133         filename = data.get(‘filename‘)
134         # home of user
135         home_DIR = os.path.join(Base_dir,‘home\%s‘ % username_of_data)
136         #abspath
137         filename = os.path.join(home_DIR,filename)
138         if os.path.isfile(filename):
139             file_size = os.path.getsize(filename)
140             self.send_response(200,{‘file_size‘:‘%s‘%file_size})
141             f = open(filename,‘rb‘)
142             for line in f:
143                 print(line)
144                 self.request.send(line)
145                 self.request.recv(1)
146             self.send_response(200)
147             print("get successfully.....")
148         else:
149             self.send_response(601)
150
151
152     def _ls(self,data):
153         print(‘start ls...‘)
154         self.verify_data(data)
155         if data.get(‘header‘) == {}:
156             self.send_response(601)
157         parser = configparser.ConfigParser()
158         parser.read(settings.ACCOUNT_FILE)
159         section_list = parser.sections()
160         username_of_data = data.get(‘header‘).get(‘username‘)
161         flag = username_of_data in section_list
162         if flag:
163             home_DIR = os.path.join(Base_dir, ‘home\%s‘ % username_of_data)
164             user_exit_file = os.listdir(home_DIR)
165             self.request.sendall(json.dumps(user_exit_file).encode())
166             for i in user_exit_file:
167                 print(i)
168
169
170     def _cd(self,*args,**kwargs):
171         pass
172
173 if __name__ == ‘__main__‘:
174     HOST, PORT = settings.Host, settings.PORT

ftp_server.py

 1 from core.ftp_server import FTPHandler
 2 from conf import settings
 3 import socketserver
 4
 5 class ArgvHandler(object):
 6     def __init__(self):
 7         self.start()
 8         # self.parser = optparse.OptionParser()
 9         # self.parser.add_option(‘-H‘,‘--host‘,dest= ‘host‘,help=‘host of server‘)
10         # self.parser.add_option(‘-P‘,‘--port‘,type=int,dest= ‘port‘,help=‘port of server‘)
11         # (self.options,self.args) = self.parser.parse_args()
12         # print(self.options,self.args)
13         # # print(dir(self.options))
14         # print(self.options.host)
15         # self.verify_args()
16
17
18     def verify_args(self):
19         if hasattr(self,self.args[0]):
20             func = getattr(self,self.args[0])
21             func()
22
23         else:
24             print(self.parser.print_help())
25
26     def start(self):
27         print(‘going to start...‘.center(60,‘-‘))
28         server = socketserver.ThreadingTCPServer((settings.HOST, settings.PORT),FTPHandler)
29         server.serve_forever()

main.py



原文地址:https://www.cnblogs.com/Macal/p/8372907.html

时间: 2024-08-03 03:59:15

python练习——moudule03——选课系统的相关文章

python面向对象练习--选课系统

这几天学完面向对象,然后找了一个练习做(题目如下):因为刚刚接触编程,可能有很多方面考虑得不周到 目录如下: import os import sys BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(BASEDIR) from core.admin_view import admin_main from lib.public_func import instanc from

Python 简易版选课系统

一.创建学生类 # # 创建学生类 import random class Student: def __init__(self,num,name,address,course_lst=None): self.num=num self.name=name self.address=address if course_lst: self.cous_lst=cous_lst else: self.cous_lst=[] def look(self): #查看学生所有的课程信息 print("%s学生

python之选课系统详解[功能未完善]

作业需求 思路:1.先写出大体的类,比如学校类,学生类,课程类--   2.写出类里面大概的方法,比如学校类里面有创建讲师.创建班级-- 3.根据下面写出大致的代码,并实现其功能       遇到的困难: 1.在类与类关联上卡住了,比如: 老师如何查看班级信息?? 老师有班级名称的属性, 而要查看班级信息,需要班级对象 那应该将老师的班级名称与班级对象相关联起来 那不同老师怎么办?? 所以学校创建 老师对象时,应该将老师名称与老师对象相关联起来 通过输入老师名称即可找到老师对象 2. 想把讲师对

Python作业-选课系统

Python作业-选课系统 学习 python Python作业-选课系统 days6作业-选课系统: 1. 程序说明 2. 思路和程序限制 3. 选课系统程序目录结构 4. 测试帐户说明 5. 程序测试过程 days6作业-选课系统: 角色:学校.学员.课程.讲师 作业需求 1.创建北京.上海 2 所学校 2.创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开 3.课程包含,周期,价格,通过学校创建课程 4.通过学校创建班级, 班级关联课程.

python第三十五天-----作业完成--学校选课系统

选课系统:角色:学校.学员.课程.讲师要求:1. 创建北京.上海 2 所学校2. 创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开3. 课程包含,周期,价格,通过学校创建课程 4. 通过学校创建班级, 班级关联课程.讲师5. 创建学员时,选择学校,关联班级5. 创建讲师角色时要关联学校, 6. 提供两个角色接口6.1 学员视图, 可以注册, 交学费, 选择班级,6.2 讲师视图, 讲师可管理自己的班级, 上课时选择班级, 查看班级学员列表 ,

Python模拟登陆3: 进入选课系统(手工输入验证码阶段)

其实最想做的是选课插件,于是这次试试了下选课系统,但是选课系统 有验证码. 很是蛋疼. 需要识别. 但是现在可以用另一种方法.就是下载到本地手动输入.也只需要一次就够了.因为登陆成功后就可以随意操作其他东西了. 后面再学习验证码的智能识别. 首先主要是模拟逻辑是.先设置一个cookie存储器,用它去访问验证码链接.然后会得到cookie.还有下载好的验证码图片,就在本地.然后再把验证码,用户名,密码,和那个cookie一起提交到登陆.于是cookie就一致了. 有点不舒服的就是需要在本地看下那个

Python开发程序:选课系统-改良版

程序名称: 选课系统 角色:学校.学员.课程.讲师要求:1. 创建北京.上海 2 所学校2. 创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开3. 课程包含,周期,价格,通过学校创建课程 4. 通过学校创建班级, 班级关联课程.讲师5. 创建学员时,选择学校,关联班级6. 创建讲师角色时要关联学校, 7. 提供两个角色接口8. 学员视图, 可以注册, 交学费, 选择班级,9. 讲师视图, 讲师可管理自己的班级, 上课时选择班级, 查看班级学员

Python开发程序:选课系统

本节作业: 选课系统 角色:学校.学员.课程.讲师要求:1. 创建北京.上海 2 所学校2. 创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开3. 课程包含,周期,价格,通过学校创建课程 4. 通过学校创建班级, 班级关联课程.讲师5. 创建学员时,选择学校,关联班级5. 创建讲师角色时要关联学校, 6. 提供两个角色接口7. 学员视图, 可以注册, 交学费, 选择班级,8. 讲师视图, 讲师可管理自己的班级, 上课时选择班级, 查看班级学员

Python选课系统

Python选课系统 一.程序介绍 需求: 开发一个简单的python计算器 角色:学校.学员.课程.讲师 要求: 1. 创建北京.上海 2 所学校 2. 创建linux , python , go 3个课程 , linux\py 在北京开, go 在上海开 3. 课程包含,周期,价格,通过学校创建课程 4. 通过学校创建班级, 班级关联课程.讲师 5. 创建学员时,选择学校,关联班级 6. 创建讲师角色时要关联学校, 7. 提供两个角色接口 7.1 学员视图, 可以注册, 交学费, 选择班级,