---恢复内容开始---
week8
1、动态导入模块
2、断言
3、ftp
4、socketserver
1、动态导入模块
import importlib
a = importlib.import_module('aa.aa') # aa目录下的aa模块
print(aa.import_C().name)
2、断言
跟if有点类似,判断是否符合条件,是则继续,否则报错。
a = 'name'
assert type(a) is str
3、FTP(文件传输:单下载)
客户端
1、读取文件名
2、检测文件是否存在
3、打开文件
4、检测文件大小
5、发送文件大小给客户端
6、客户端确认
7、开始边读边发数据
8、md5 import socket,os,hashlib
server = socket.socket()
server.bind(('localhost',9999))
server.lisen()
m = hashlib.md5()
while True:
try:
conn,addr = server.accept()
data = conn.recv(1024)
cmd,filename =data.split()
if os.path.isfile(filename):
f = open(filename,'rb')
filesize = f.stat(filename).st_size
conn.send(str(filesize).encode())
conn.recv(1024)
for line in f:
m.update(line)
conn.send(line)
print(m.hexdigest())
conn.send(str(hexdigest).encode)
f.close
print(send done')
except ConnectionResetError as e:
print('连接错误',e)
server.close()
客户端
import socket,os,hashlib
client = socket.socket()
client.connect(('localhost',9999))
m = hashlib.md5
while True:
cmd = imput('>>>:').strip()
if len(cmd) == 0:continue
filesize = client.recv(1024)
client.send('请求发送’) #无实际意义的交互,防止粘包
filename = cmd.split[1]
f = open(filename+'.new','wb')
rec_filesize = 0
filesize = int(filesize.decode())
while filesize > rec_filesize:
if filesize - rec_filesize > 1024: # 做判断防止最后一次接收出现粘包
res_size = 1024
else:
res_size = filesize - rec_filesize
data = client.recv(res_size)
f.write(data)
rec_filesize += len(data)
m.update(data)
else:
new_file_md5 = m.hexdigest()
print('new file md5:',new_file_md5)
server_file_md5 = client.recv(1024)
print('server file md5',server_file_md5) #接收服务端读取的md5,与自己生成的md5进行比较
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 请求处理后的事项
import socketserver class MyTCPServer(socketserver.BaseRequestHandler):
def setup(self): #交互前的动作
pass
def handle(self): #与用户的所有交互都在这里进行
self.data = self.request.recv(1024)
print("{} wrote:".format(self.client_address[0]))
self.request.sendall(self.data.upper)
def finish(self): #与用户交互后的动作
pass if __name__ == '__main__'
HOST , PORT = 'localhost',9999
server = socketserver.ThreadingTCPServer((HOST,PORT),MyTCPServer)
#ThreadingTCPServer 多线程
#ForingTCPServer 多进程 在win不好使
server.server_forever()
客户端