python第八周小测验答案_Python学习笔记第八周

本节内容:

1、动态导入模块

2、断言机制

3、SocketServer

1、动态导入模块

有时在编程过程中,如果知道模块对应的字符串,可以通过动态导入的方式将该字符对应的模块进行动态导入

导入的方式有两种:

1、python解释器默认的方式导入

2、官方推荐动态导入方式

下面来分别介绍以下两种方式:

20180110223515957447.png

lib模块中包括aa文件,aa文件内容如下:

classC(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)

通过方法二导入:

importimportlib

mod= importlib.import_module(‘lib.aa‘) #官方建议这种方法更有效,mod直接表示了lib.aa

obj =mod.C()print(obj.name)

2、断言机制

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代码

jia.gif

jian.gif

importsocketserverclassMyTCPHandler(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."""

defhandle(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()

View Code

在上面代码,仍然不能同时处理多个链接,如果要处理多个链接,需要将socketserver.TCPServer变为以下类:

classsocketserver.ForkingTCPServer

classsocketserver.ForkingUDPServer

classsocketserver.ThreadingTCPServer

classsocketserver.ThreadingUDPServer

所以只需要替换

server = socketserver.TCPServer((HOST, PORT), MyTCPHandler)

变为下面这个,就可以多并发了

server = socketserver.ThreadingTCPServer((HOST, PORT), MyTCPHandler)

classsocketserver.BaseServer(server_address, RequestHandlerClass) 主要有以下方法

jia.gif

jian.gif

classsocketserver.BaseServer(server_address, RequestHandlerClass)

Thisis 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 andRequestHandlerClass attributes.

fileno()

Return an integer file descriptorfor the socket on which the server is listening. This function is most commonly passed to selectors, to allow monitoring multiple servers inthe same process.

handle_request()

Process a single request. This function calls the following methodsin 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. Pollfor 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 classuses service_actions() to clean up zombie child processes.

Changedin version 3.3: Added service_actions call to the serve_forever method.

service_actions()

Thisis called in the serve_forever() loop. This method can be overridden by subclasses ormixin classes to perform actions specific to a given service, such as cleanup actions.

Newin version 3.3.

shutdown()

Tell the serve_forever() loop to stopandwait 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_INETandsocket.AF_UNIX.

RequestHandlerClass

The user-provided request handler class; an instance of this class is created foreach request.

server_address

The address on which the serveris 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), forexample.

socket

The socket object on which the server will listenforincoming requests.

The server classes support the followingclassvariables:

allow_reuse_address

Whether the server will allow the reuse of an address. This defaults to False,and can be set insubclasses 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 arrivewhile 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_STREAMandsocket.SOCK_DGRAM are two common values.

timeout

Timeout duration, measuredin seconds, or None if no timeout is desired. If handle_request() receives no incoming requests within the timeout period, the handle_timeout() method iscalled.

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 RequestHandlerClassandcalling its handle() method.

get_request()

Must accept a requestfrom the socket, and return a 2-tuple containing the new socket object to be used to communicate with the client, andthe client’s address.

handle_error(request, client_address)

This functionis called if the handle() method of a RequestHandlerClass instance raises an exception. The default action is to print the traceback to standard output and continuehandling further requests.

handle_timeout()

This functionis 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 inthreading 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 processor thread to handle the request; the ForkingMixIn andThreadingMixIn classes do this.

server_activate()

Called by the server’s constructor to activate the server. The default behaviorfora 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)

Mustreturn 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.

View Code

原文:http://www.cnblogs.com/xiaopi-python/p/6530490.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值