Python学习笔记第八周

本节内容:

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

在上面代码,仍然不能同时处理多个链接,如果要处理多个链接,需要将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.

时间: 2024-11-05 22:37:53

Python学习笔记第八周的相关文章

Python学习笔记(八)

一.变量可以指向一个函数 a = abs 二.通过调用指向函数的变量可以执行该函数 a = abs a(-10) 三.指向函数的变量可以作为参数传递给一个函数 def add(x,y,f): return f(x) + f(y) add(-5,-6,abs) 四.map()函数 map() 函数可以为其传入一个函数以及一个可Iterator的对象,map将使用该函数依次作用于每个Iterator的元素 list1 = [ x for x in range(1,11)] def fun(x): r

Python学习笔记第六周

一.基础概念 面向对象编程 OOP编程是利用"类"和"对象"来创建各种模型来实现对真实世界的描述,使用面向对象编程的原因一方面是因为它可以使程序的维护和扩展变得更简单,并且可以大大提高程序开发效率 ,另外,基于面向对象的程序可以使它人更加容易理解你的代码逻辑,从而使团队开发变得更从容. 面向对象的几个核心特性如下 Class 类一个类即是对一类拥有相同属性的对象的抽象.蓝图.原型.在类中定义了这些对象的都具备的属性(variables(data)).共同的方法 Ob

[Python]Python学习笔记(八)——问题

1,python如果import指定文件夹下的文件 答:将路径添加到sys.path,然后import,需要解决一个问题,避免由于之前存在一个同名模块导致加载失败 [cpp] view plaincopy import sys; if not "/home/a/" in sys.path: sys.path.append("/home/a/") if not 'b' in sys.modules: b = __import__('b') else: eval('im

python学习笔记-(八)装饰器、生成器&迭代器

本节课程内容概览: 1.装饰器 2.列表生成式&迭代器&生成器 3.json&pickle数据序列化 1. 装饰器 1.1 定义: 本质上是个函数,功能是装饰其他函数—就是为其他函数添加附加功能 1.2 装饰器原则: 1)  不能修改被装饰函数的源代码: 2)  不能修改被装饰函数的调用方式: 1.3 实现装饰器知识储备: 1.3.1 函数即“变量” 定义一个函数相当于把函数体赋值给了函数名 变量可以指向函数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

python学习笔记(八)函数return多个值,列表推导式和交换两个变量的值

函数return多个值: 补充知识点:写代码得到时候少用全局变量: 1.不安全 2.会一直占着内存不释放 函数多个return值,那么会把这几个return的值都放在一个元组里面,然后返回 1 def hello(a,b,c,d): 2 return a,b,c,d 3 res=hello('ybq','ede','rfv','deq') 4 print(res)#('ybq', 'ede', 'dede', 'deq') 列表推导式: 1 #列表推导式 2 nums=[0,1,3,4,5,6,

Python 学习笔记(八)Python列表(二)

列表函数 追加和扩展 list.append() 在列表末尾追加新的对象 1 >>> dir(list) #dir 查看列表的函数 2 ['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__delslice__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getslice

python学习笔记(第一周):变量

在python中申明一个变量,不需要申明变量的类型,如下: name = "Eraser Li" 打印变量,代码如下: print("My name is",name) 控制台输出结果: My name is Eraser Li 变量赋值给变量: name2 = name print("My name is",name2) 控制台输出结果: My name is Eraser Li 现在给name重新赋值: name = "Eraser

Python学习笔记第二十周

目录: 一.ORM 1.查询补充 内容: 一.ORM 1.查询补充: 1.models.USR.objects.all().values('id','name') 这个语句相当于SQL语句中的select id,name from USER  ,表示可以单独取某几列的值,取得的值仍然是QuerySet,但是内部元素变为字典 2.models.USR.objects.all().value_list('id','name') 表示可以单独取某几列的值,取得的值仍然是QuerySet,但是内部元素变

Python学习笔记第二十七周(Bootstrap)

目录: 一.栅格系统 二.表单 三.按钮 内容: 前言: 首先通过https://cdn.bootcss.com/bootstrap/3.3.7/css/bootstrap.min.css 链接下载bootstrap.min.css保存到本地,然后执行下面操作 一.栅格系统 栅格系统是页面布局使用,是区分列布局使用的,一般bootstrap将整个页面分为12份,可以任意组合自己想要的列分割方式,在div标签中使用col-XX的方式来实现,该方式有几种方法: col-md-XX   其中md表示中