简体   繁体   English

在Python中与Singleton共享Declarative_Base(SQLAlchemy)

[英]Share Declarative_Base (SQLAlchemy) with Singleton in Python

I can run normally SQLAlchemy when everything is in one file. 当一切都在一个文件中时,我可以正常运行SQLAlchemy。 I now want to put my model into another file. 我现在想把我的模型放到另一个文件中。

However, this does not work because I can not find a way to share the base. 但是,这不起作用,因为我找不到共享基础的方法。 I tried with a Singleton but it is Null in model.py and the schema is never created in the database. 我尝试使用Singleton但它在model.py中是Null,并且从不在数据库中创建模式。

How can I do to fix this? 我该怎么做才能解决这个问题?

My files (simplified version) : 我的文件(简化版):

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

main/main.py : main / main.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 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

model/model.py 模型/ model.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)

EDIT @Lafaya 编辑@Lafaya

I changed model/__init__.py like that : 我更改了model/__init__.py

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

Then i changed model/model.py like that : 然后我改变了model/model.py

from model import Base

class User(Base):
    etc...

Now i can't import Base from model.py (because it aleady import by __init.py__ ). 现在我无法从model.py导入Base(因为它由__init.py__导入)。 But i need a reference to Base ! 但我需要参考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

Write the Base in the __init__.py of model package. 在模型包的__init__.py中写入Base Then you can import it and use it. 然后你可以导入并使用它。

Jut put Base in model/__init__.py . Jut将Base放在model/__init__.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 两个SQLAlchemy声明性模型必须共享相同的declarative_base()吗? - Must two SQLAlchemy declarative models share the same declarative_base()? SQLAlchemy - 什么是 declarative_base - SQLAlchemy - what is declarative_base 如何使用 SqlAlchemy declarative_base 创建单个表 - How to create a single table using SqlAlchemy declarative_base 如何正确使用 sqlalchemy declarative_base 与多个 model 文件 - How to properly use sqlalchemy declarative_base with multiple model files sqlalchemy declarative_base()schema_name无法正常工作 - sqlalchemy declarative_base() schema_name not working 我对 SQLalchemy declarative_base 使用什么类型? - What Type do I use for SQLalchemy declarative_base? Select 来自 SQLAlchemy declarative_base 定义的表 - Select from table defined by SQLAlchemy declarative_base SQLAlchemy的declarative_base与sqlalchemy_util的PasswordType不能很好地配合吗? - SQLAlchemy declarative_base doesn't play nicely with sqlalchemy_util PasswordType? 使用 SQLAlchemy declarative_base() 在 VS Code 中“继承不是类的‘Base’” - "Inheriting 'Base', which is not a class" in VS Code using SQLAlchemy declarative_base() 当我使用SqlAlchemy子类化`declarative_base`时,我会得到什么? - What the heck do I get when I subclass `declarative_base` using SqlAlchemy?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM