码迷,mamicode.com
首页 > 编程语言 > 详细

Python学习笔记第八周

时间:2017-03-10 15:04:57      阅读:309      评论:0      收藏:0      [点我收藏+]

标签:instant   __init__   exit   stream   ges   mmu   cep   oca   建议   

本节内容:

1、动态导入模块

2、断言机制

3、SocketServer

 

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、断言机制

 

 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()
View Code

在上面代码,仍然不能同时处理多个链接,如果要处理多个链接,需要将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_addressRequestHandlerClass) 主要有以下方法

技术分享
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.
View Code

 

Python学习笔记第八周

标签:instant   __init__   exit   stream   ges   mmu   cep   oca   建议   

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

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!