Flask框架单例模式实现方法详解

yipeiwu_com6年前Python基础

本文实例讲述了Flask框架单例模式实现方法。分享给大家供大家参考,具体如下:

单例模式:

程序运行时只能生成一个实例,避免对同一资源产生冲突的访问请求。

Django   admin.py下的admin.site.register() ,  site就是使用文件导入方式的单例模式

创建到单例模式4种方式:

  • 1.文件导入
  • 2. 类方式
  • 3.基于__new__方式实现
  • 4.基于metaclass方式实现

1.文件导入:

in  single.py

class Singleton():
  def __init__(self):
    pass
site = Singleton()

类似:

import time  第一次已经把导入的time模块,放入内存
import time  第二次内存已有就不导入了

in  app.py

from single.py import site #第一次导入,实例化site对象并放入内存

in  views.py

from single.py import site #第二次导入,直接从内存拿。

2.类方式:

缺点:改变了单例的创建方式

obj = Singleton.instance()

# 单例模式:无法支持多线程情况
import time
class Singleton(object):
  def __init__(self):
    import time
    time.sleep(1)
  @classmethod
  def instance(cls, *args, **kwargs):
    if not hasattr(Singleton, "_instance"):
      Singleton._instance = Singleton(*args, **kwargs)
    return Singleton._instance
# # 单例模式:支持多线程情况
import time
import threading
class Singleton(object):
  _instance_lock = threading.Lock()
  def __init__(self):
    time.sleep(1)
  @classmethod
  def instance(cls, *args, **kwargs):
    if not hasattr(Singleton, "_instance"):
      with Singleton._instance_lock:
        if not hasattr(Singleton, "_instance"):
          Singleton._instance = Singleton(*args, **kwargs)
    return Singleton._instance

3.基于__new__方式实现:

单例创建方式:

obj1 = Singleton()
obj2 = Singleton()

import time
import threading
class Singleton(object):
  _instance_lock = threading.Lock()
  def __init__(self):
    pass
  def __new__(cls, *args, **kwargs):
    if not hasattr(Singleton, "_instance"):
      with Singleton._instance_lock:
        if not hasattr(Singleton, "_instance"):
          Singleton._instance = object.__new__(cls, *args, **kwargs)
    return Singleton._instance

4.基于metaclass方式实现

基于metaclass方式实现的原理:

  • 1.对象是类创建,创建对象时候类的__init__方法自动执行,对象()执行类的 __call__ 方法
  • 2.类是type创建,创建类时候type的__init__方法自动执行,类() 执行type的 __call__方法

单例创建方式:

obj1 = Foo()
obj2 = Foo()

import threading
class SingletonType(type):
  _instance_lock = threading.Lock()
  def __call__(cls, *args, **kwargs):
    if not hasattr(cls, "_instance"):
      with SingletonType._instance_lock:
        if not hasattr(cls, "_instance"):
          cls._instance = super(SingletonType,cls).__call__(*args, **kwargs)
    return cls._instance
class Foo(metaclass=SingletonType):
  def __init__(self):
    pass

希望本文所述对大家基于flask框架的Python程序设计有所帮助。

相关文章

浅析Python的web.py框架中url的设定方法

浅析Python的web.py框架中url的设定方法

网页中的数据在传递的时候有GET和POST两种方式,GET是以网址的形式传参数,在web.py中有着很好的匹配,如果我们配置以下的urls urls =( '/','inde...

Python3 chardet模块查看编码格式的例子

Python3 chardet模块查看编码格式的例子

如下所示: 需要注意的是,如果遇到GBK2312等编码的,在decode和encode时,一律使用GBK进行编码或者解码,这是因为GBK是其他GBK编码的超集,向下兼容所有的GBK编码...

Python 专题六 局部变量、全局变量global、导入模块变量

Python 专题六 局部变量、全局变量global、导入模块变量

定义在函数内的变量有局部作用域,在一个模块中最高级别的变量有全局作用域。本文主要讲述全局变量、局部变量和导入模块变量的方法。 参考:《Python核心编程 (第二版)》 一. 局部变量...

Python中新式类与经典类的区别详析

1.新式类与经典类 在Python 2及以前的版本中,由任意内置类型派生出的类(只要一个内置类型位于类树的某个位置),都属于“新式类”,都会获得所有“新式类”的特性;反之,即不由任意内置...

在Debian下配置Python+Django+Nginx+uWSGI+MySQL的教程

最近尝试把项目迁移到Python环境下,特别新装了一台干净的Debian系统,准备重新配置环境,上网找了一些运行Python Web的环境方案,最后敲定Nginx+uWSGI组合,Ngi...