---恢复内容开始---
week8
1、动态导入模块
2、断言
3、ftp
4、socketserver
1、动态导入模块
1 import importlib2 a = importlib.import_module('aa.aa') # aa目录下的aa模块3 print(aa.import_C().name)
2、断言
跟if有点类似,判断是否符合条件,是则继续,否则报错。
1 a = 'name'2 assert type(a) is str
3、FTP(文件传输:单下载)
1 客户端 2 1、读取文件名 3 2、检测文件是否存在 4 3、打开文件 5 4、检测文件大小 6 5、发送文件大小给客户端 7 6、客户端确认 8 7、开始边读边发数据 9 8、md510 11 import socket,os,hashlib12 server = socket.socket()13 server.bind(('localhost',9999))14 server.lisen()15 m = hashlib.md5()16 while True:17 try:18 conn,addr = server.accept() 19 data = conn.recv(1024)20 cmd,filename =data.split()21 if os.path.isfile(filename):22 f = open(filename,'rb')23 filesize = f.stat(filename).st_size24 conn.send(str(filesize).encode())25 conn.recv(1024)26 for line in f:27 m.update(line)28 conn.send(line)29 print(m.hexdigest())30 conn.send(str(hexdigest).encode)31 f.close32 print(send done')33 except ConnectionResetError as e:34 print('连接错误',e)35 server.close()
1 import socket,os,hashlib 2 client = socket.socket() 3 client.connect(('localhost',9999)) 4 m = hashlib.md5 5 while True: 6 cmd = imput('>>>:').strip() 7 if len(cmd) == 0:continue 8 filesize = client.recv(1024) 9 client.send('请求发送’) #无实际意义的交互,防止粘包10 filename = cmd.split[1]11 f = open(filename+'.new','wb')12 rec_filesize = 013 filesize = int(filesize.decode())14 while filesize > rec_filesize:15 if filesize - rec_filesize > 1024: # 做判断防止最后一次接收出现粘包16 res_size = 102417 else:18 res_size = filesize - rec_filesize19 data = client.recv(res_size)20 f.write(data)21 rec_filesize += len(data)22 m.update(data)23 else:24 new_file_md5 = m.hexdigest()25 print('new file md5:',new_file_md5)26 server_file_md5 = client.recv(1024)27 print('server file md5',server_file_md5) #接收服务端读取的md5,与自己生成的md5进行比较28 client.close
4、socketserver(面向对象的方法进行文件传输)
创建方式:
创建一个socketserver 至少分以下几步: First, you must create a request handler class by subclassing the BaseRequestHandlerclass and overriding its handle() method; this method will process incoming requests. Second, you must instantiate one of the server classes, passing it the server’s address and the request handler class. Then call the handle_request() orserve_forever() method of the server object to process one or many requests. Finally, call server_close() to close the socket. self.setup 请求处理前进行的事项 self.handle 请求处理中的事项 self.finish 请求处理后的事项
1 import socketserver 2 3 class MyTCPServer(socketserver.BaseRequestHandler): 4 def setup(self): #交互前的动作 5 pass 6 def handle(self): #与用户的所有交互都在这里进行 7 self.data = self.request.recv(1024) 8 print("{} wrote:".format(self.client_address[0])) 9 self.request.sendall(self.data.upper)10 def finish(self): #与用户交互后的动作11 pass12 13 14 if __name__ == '__main__'15 HOST , PORT = 'localhost',999916 server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPServer)17 #ThreadingTCPServer 多线程18 #ForingTCPServer 多进程 在win不好使19 server.server_forever()