1、单例模式指的是创建单个实例,例如:数据库连接池中包含10个数据库连接,用户访问数据时随机从连接池中拿出一个进行连接,其他用户再次访问时不再创建对象进行连接
#!usr/bin/env python # -*- coding:utf-8 -*- class ConnecttionPool: __instance = None def __init__(self): self.ip = ‘222.133.177.67‘ self.port = ‘3306‘ self.username = ‘odoo‘ self.password = ‘123456‘ self.con_list = [1,2,3,4,5,6,7,8,9,10] @staticmethod def get_instance(): #创建实例的方法 if ConnecttionPool.__instance: return ConnecttionPool.__instance else: ConnecttionPool.__instance = ConnecttionPool() return ConnecttionPool.__instance def get_connection(self): #获得连接 import random r = self.con_list[random.randrange(1,10)] return r for i in range(10): pool = ConnecttionPool.get_instance() print(‘去连接池‘,pool,‘获得一个连接‘) r = pool.get_connection() print(‘获得的连接是:‘,r)
单例模式
2、简单的服务器请求框架
#!usr/bin/env python # -*- coding:utf-8 -*- from wsgiref.simple_server import make_server def RunServer(environ,start_response): start_response(status=‘200 OK‘,headers=[(‘Content-Type‘,‘text/html‘)]) url = environ[‘PATH_INFO‘] #url取的是访问时端口号后面的地址 return ‘谢谢你的访问!‘ #可以读取html文件 if __name__ == ‘__main__‘: httpd = make_server(‘‘,8000,RunServer) print(‘Server Http on 8000......‘) httpd.serve_forever() #循环监听访问,当有访问时,返回RunServer函数的返回值
网站服务器监听代码
时间: 2024-10-25 22:45:17