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 当前全局变量和入口参数的所有属性

def cndebug(obj=False): """ Author : Nemon Update : 2009.7.1 TO use : cndebug(obj) or cndebug...

python使用pandas处理大数据节省内存技巧(推荐)

python使用pandas处理大数据节省内存技巧(推荐)

一般来说,用pandas处理小于100兆的数据,性能不是问题。当用pandas来处理100兆至几个G的数据时,将会比较耗时,同时会导致程序因内存不足而运行失败。 当然,像Spark这类的...

Python运行报错UnicodeDecodeError的解决方法

Python2.7在Windows上有一个bug,运行报错: UnicodeDecodeError: 'ascii' codec can't decode byte 0xc4 in...

wxPython事件驱动实例详解

wxPython事件驱动实例详解

本文实例讲述了wxPython的事件驱动机制,分享给大家供大家参考。具体方法如下: 先来看看如下代码: #!/usr/bin/python # moveevent.py...

Tensorflow之构建自己的图片数据集TFrecords的方法

学习谷歌的深度学习终于有点眉目了,给大家分享我的Tensorflow学习历程。 tensorflow的官方中文文档比较生涩,数据集一直采用的MNIST二进制数据集。并没有过多讲述怎么构建...