python - 在 Python 中与 Singleton 共享 Declarative_Base (SQLAlchemy)

标签 python sql singleton sqlalchemy

当一切都在一个文件中时,我可以正常运行 SQLAlchemy。我现在想将我的模型放入另一个文件。

但是,这不起作用,因为我找不到共享基础的方法。我尝试使用 Singleton,但它在 model.py 中为 Null,并且从未在数据库中创建模式。

我该如何解决这个问题?

我的文件(简化版):

     - /main/__init__.py
     - /main/main.py
     - /utils/__init__.py
     - /utils/utils.py
     - /model/__init__.py
     - /model/model.py

主要/主要.py :

from model import User
from utils.utils import readConf,createSession,getBase

class Worker(threading.Thread): 

    def __init__(self, queue, session):
        self.__queue = queue
        threading.Thread.__init__(self)
        self._stopevent = threading.Event( )

    def run(self):
        session.merge(User(queue.get()))
        session.commit()


class Collector(threading.Thread):

    def __init__(self, nom = ''):
        threading.Thread.__init__(self)
        self.nom = nom
        self._stopevent = threading.Event( )


    def run(self):
        while not self._stopevent.isSet():
            queue.put("Name")

if __name__ == '__main__':
    conf = readConf("file.")
    session = createSession(conf)
    queue = Queue.Queue(0)      
    Worker(queue, session).start()
    Collector("Start").start()

utils/utils.py

from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.schema import MetaData

def createSession(conf):
    schema = conf['bdd']['type'] + '://' + conf['bdd']['user'] + ':' + conf['bdd']['password'] + '@' + conf['bdd']['host'] + '/' + conf['bdd']['db']
    engine = create_engine(schema, echo=True)

    b = getBase("Utils")
    b.set_base(declarative_base())

    Base = b.get_base()    
    Base.metadata.create_all(engine)     

    Session = sessionmaker(bind=engine)
    session = Session()
    return session

class getBase(object):
    __single = None # the one, true Singleton
    __base = None
    __text = None
    __base = None

    def __new__(cls, *args, **kwargs):
        # Check to see if a __single exists already for this class
        # Compare class types instead of just looking for None so
        # that subclasses will create their own __single objects
        if cls != type(cls.__single):
            cls.__single = object.__new__(cls, *args, **kwargs)
            __base = declarative_base()

        return cls.__single

    def __init__(self,name=None):
        self.name = name

    def get_base(self):
        return self.__base


    def set_base(self, value):
        self.__base = value

模型/模型.py

from utils.utils import getBase

b = getBase("model")
b.set_base(declarative_base())
Base = b.get_base()

class User(Base):
    __tablename__ = 'users'

    def __init__(self, name):
        self.screen_name = name

    name_id = Column(Integer, primary_key=True, autoincrement=True)
    screen_name = Column(BigInteger(), primary_key=True, nullable=False)

编辑@Lafaya

我这样更改了 model/__init__.py :

#!/usr/bin/python
Base = declarative_base()

然后我像那样更改了 model/model.py :

from model import Base

class User(Base):
    etc...

现在我无法从 model.py 导入 Base(因为它已通过 __init.py__ 导入)。但我需要对 Base 的引用!

Traceback (most recent call last):
  File "../main/main.py", line 12, in <module>
    from model.model import User
  File "../model/model.py", line 3, in <module>
    from model import Base
ImportError: cannot import name Base

最佳答案

在模型包的__init__.py中写入Base。然后您可以导入并使用它。

只需将 Base 放在 model/__init__.py 中。

关于python - 在 Python 中与 Singleton 共享 Declarative_Base (SQLAlchemy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8925845/

相关文章:

python - 使用pivot_table时将分类数据与数值数据相结合

python - Python numpy 中的无循环卡方网格搜索

sql - PostgreSQL 中不存在列(WHERE 列名称 = 列值)

sql - 与以下 sql 查询相关的 sequelize 查询是什么?

python - 在 PyCharm Professional 中,运行 docker 和 docker-compose Python 解释器的能力去了哪里?

sql - 按生成的列分组

flutter - Dart 中的 Lazy Singleton 与 Singleton

Java 如何销毁单例实例

iphone - 在全局范围内使用 MBProgressHUD + 使其成为单例

python - python 中的相交列表不起作用