目录:
一、基础概念
1、动态导入模块
2、断言机制
3、SocketServer
二、作业 FTP服务器
三、单独注明
1、类中装饰器
2、进度条
一、基础概念
1、动态导入模块
有时在编程过程中,如果知道模块对应的字符串,可以通过动态导入的方式将该字符对应的模块进行动态导入
导入的方式有两种:
1、python解释器默认的方式导入
2、官方推荐动态导入方式
下面来分别介绍以下两种方式:
lib模块中包括aa文件,aa文件内容如下:
class C(object): def __init__(self): self.name = 'gavin'
通过方法一导入:
modname = 'lib' #知道模块名字对应字符串 mod = __import__('lib.aa') #导入lib同时导入lib模块下的aa,但是这个mod只是lib,而不是lib.aa 要记住 obj = mod.aa.C()#因为mod只表示lib,所以需要写成mod.aa表示lib.aa print(obj.name)
通过方法二导入:
import importlib mod = importlib.import_module('lib.aa') #官方建议这种方法更有效,mod直接表示了lib.aa
obj = mod.C() print(obj.name)
2、断言机制
断言的作用:
当后续的程序很重要,不允许出错,可以在该程序前添加断言机制,当断言不正确就不执行,断言正确会继续执行后续的程序
例子:
借用上面的lib模块引用,当引用该模块后,发现其中的类型为str类型后,打印,然后将类型断言变为int类型,此时会发现原来正常打印执行的语句不再执行
1、正确打印:
import importlib mod_name = 'lib.aa' mod = importlib.import_module(mod_name) obj = mod.C() assert type(obj.name) is str print('断言正确执行') #输出 断言正确执行
2、忽略打印动作
import importlib mod_name = 'lib.aa' mod = importlib.import_module(mod_name) obj = mod.C() assert type(obj.name) is int print('断言正确执行') #输出 raceback (most recent call last): File "/Users/Gavin/PycharmProjects/python/day8/复现/2-断言/断言.py", line 7, in <module> assert type(obj.name) is int AssertionError
3、socketserver
socketserver是一个模块,该模块简化了编写网络服务器的任务复杂度
socketserver一共有这么几种类型
1、tcp类型
class socketserver.TCPServer(server_address, RequestHandlerClass,bind_and_activate=True)
2、udp类型
class socketserver.UDPServer(server_address, RequestHandlerClass, bind_and_activate=True)
3、使用Unix domain方式socket类型
class socketserver.UnixStreamServer(server_address, RequestHandlerClass, bind_and_activate=True) class socketserver.UnixDatagramServer(server_address, RequestHandlerClass,bind_and_activate=True)
这几种类的继承关系如下:
+------------+
| BaseServer |
+------------+
|
v
+-----------+ +------------------+
| TCPServer |------->| UnixStreamServer |
+-----------+ +------------------+
|
v
+-----------+ +--------------------+
| UDPServer |------->| UnixDatagramServer |
+-----------+ +--------------------+
创建一个socketserver至少分以下几个步骤:
1、必须创建一个请求处理类,这个要继承BaseRequestHandler类并且要重写父类里的handle方法
2、必须要实例化一个其中任意类型的类,同时传递Server IP和上面创建的请求处理类给这个任意类
3、调用类方法
类方法包含以下两种:
1、server.serve_request() #只处理一个请求,不会使用这个
2、server.serve_forever()#处理多个请求,永远执行着调用
4、关闭server.serve_forever()
注意:跟客户端所有交互,都是在handle()方法中完成的,每个请求过来以后,都是通过handle来规定处理行为
基本的sockerserver代码
import socketserver class MyTCPHandler(socketserver.BaseRequestHandler): """ The request handler class for our server. It is instantiated once per connection to the server, and must override the handle() method to implement communication to the client. """ def handle(self): # self.request is the TCP socket connected to the client self.data = self.request.recv(1024).strip() print("{} wrote:".format(self.client_address[0])) print(self.data) # just send back the same data, but upper-cased self.request.sendall(self.data.upper()) if __name__ == "__main__": HOST, PORT = "localhost", 9999 # Create the server, binding to localhost on port 9999 server = socketserver.TCPServer((HOST, PORT), MyTCPHandler) # Activate the server; this will keep running until you # interrupt the program with Ctrl-C server.serve_forever()
在上面代码,仍然不能同时处理多个链接,如果要处理多个链接,需要将socketserver.TCPServer变为以下类:
class socketserver.
ForkingTCPServer
class socketserver.
ForkingUDPServer
class socketserver.
ThreadingTCPServer
class socketserver.
ThreadingUDPServer
所以只需要替换
server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)
变为下面这个,就可以多并发了
server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)
class socketserver.
BaseServer
(server_address, RequestHandlerClass) 主要有以下方法
class socketserver.BaseServer(server_address, RequestHandlerClass) This is the superclass of all Server objects in the module. It defines the interface, given below, but does not implement most of the methods, which is done in subclasses. The two parameters are stored in the respective server_address and RequestHandlerClass attributes. fileno() Return an integer file descriptor for the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers in the same process. handle_request() Process a single request. This function calls the following methods in order: get_request(), verify_request(), and process_request(). If the user-provided handle() method of the handler class raises an exception, the server’s handle_error() method will be called. If no request is received within timeout seconds, handle_timeout() will be called and handle_request() will return. serve_forever(poll_interval=0.5) Handle requests until an explicit shutdown() request. Poll for shutdown every poll_interval seconds. Ignores the timeout attribute. It also calls service_actions(), which may be used by a subclass or mixin to provide actions specific to a given service. For example, the ForkingMixIn class uses service_actions() to clean up zombie child processes. Changed in version 3.3: Added service_actions call to the serve_forever method. service_actions() This is called in the serve_forever() loop. This method can be overridden by subclasses or mixin classes to perform actions specific to a given service, such as cleanup actions. New in version 3.3. shutdown() Tell the serve_forever() loop to stop and wait until it does. server_close() Clean up the server. May be overridden. address_family The family of protocols to which the server’s socket belongs. Common examples are socket.AF_INET and socket.AF_UNIX. RequestHandlerClass The user-provided request handler class; an instance of this class is created for each request. server_address The address on which the server is listening. The format of addresses varies depending on the protocol family; see the documentation for the socket module for details. For Internet protocols, this is a tuple containing a string giving the address, and an integer port number: ('127.0.0.1', 80), for example. socket The socket object on which the server will listen for incoming requests. The server classes support the following class variables: allow_reuse_address Whether the server will allow the reuse of an address. This defaults to False, and can be set in subclasses to change the policy. request_queue_size The size of the request queue. If it takes a long time to process a single request, any requests that arrive while the server is busy are placed into a queue, up to request_queue_size requests. Once the queue is full, further requests from clients will get a “Connection denied” error. The default value is usually 5, but this can be overridden by subclasses. socket_type The type of socket used by the server; socket.SOCK_STREAM and socket.SOCK_DGRAM are two common values. timeout Timeout duration, measured in seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method is called. There are various server methods that can be overridden by subclasses of base server classes like TCPServer; these methods aren’t useful to external users of the server object. finish_request() Actually processes the request by instantiating RequestHandlerClass and calling its handle() method. get_request() Must accept a request from the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, and the client’s address. handle_error(request, client_address) This function is called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard output and continue handling further requests. handle_timeout() This function is called when the timeout attribute has been set to a value other than None and the timeout period has passed with no requests being received. The default action for forking servers is to collect the status of any child processes that have exited, while in threading servers this method does nothing. process_request(request, client_address) Calls finish_request() to create an instance of the RequestHandlerClass. If desired, this function can create a new process or thread to handle the request; the ForkingMixIn and ThreadingMixIn classes do this. server_activate() Called by the server’s constructor to activate the server. The default behavior for a TCP server just invokes listen() on the server’s socket. May be overridden. server_bind() Called by the server’s constructor to bind the socket to the desired address. May be overridden. verify_request(request, client_address) Must return a Boolean value; if the value is True, the request will be processed, and if it’s False, the request will be denied. This function can be overridden to implement access controls for a server. The default implementation always returns True.
二、作业
开发一个支持多用户在线的FTP程序
要求:
- 用户加密认证
- 允许同时多用户登录
- 每个用户有自己的家目录 ,且只能访问自己的家目录
- 对用户进行磁盘配额,每个用户的可用空间不同
- 允许用户在ftp server上随意切换目录(切换目录命令参数只包括 '.' '..' 和绝对路径)
- 允许用户查看当前目录下文件
- 允许上传和下载文件,保证文件一致性
- 文件传输过程中显示进度条
- 附加功能:支持文件的断点续传(没实现,可以通过抓取异常处理,然后通过tell记录字节数,下一次传递通过seek到记录的字节数开始继续传输来实现
目录结构:
代码实现:
FTP_Client:
import os import sys BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) print(BASEDIR) sys.path.insert(0,BASEDIR) from core import main if __name__ == '__main__': #HOST = input('输入你链接的地址:').strip() #PORT = int(input('输入你要链接的端口:').strip()) obj = main.FtpClient('localhost',9999) obj.FtpManager()
import os import sys import logging BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,BASEDIR) USER_HOME = os.path.join(BASEDIR,'user_data/')
import socket import os import sys import hashlib import json BASEDIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0,BASEDIR) from config import settings class FtpClient(object): def __init__(self,host,port): #构造函数,初始化时可以指定服务器IP与端口 self.host = host self.port = port self.client = socket.socket() def help(self): #认证成功后,显示该客户端功能菜单 msg = { 'cd': 'cd .|cd .. |cd abspath 三种方式切换路径', 'ls': '显示目录内容', 'pwd': '显示当前路径', 'put filename': '上传文件', 'get filename': '下载文件', 'quit': '退出程序', } for line in msg: print(line, msg[line]) def FtpManager(self): self.client.connect((self.host,self.port)) while True: username = input('