2

我想创建一个数据库模式并使用 SQLalchemy 插入数据。但由于某种原因,SQLAlchemy 不会在create_fixture.py. 当我提交会话时,SQLAlchemy 引发错误,因为它找不到任何表。

这是我的代码的简化版本。我的__init__.py

  from sqlalchemy import create_engine                                                           
  from sqlalchemy.orm import sessionmaker, scoped_session                                        
  from sqlalchemy.ext.declarative import declarative_base                                        

  engine = create_engine('postgresql://postgres@localhost/syncer', echo=True)                    
  Base = declarative_base(bind=engine)                                                           
  session = scoped_session(sessionmaker(engine))        

entity.py

  from sqlalchemy import Column, String, Integer                                                                            
  from __init__ import Base, session    


  class Zone(Base):                                                               
         __tablename__ = 'zone'                                                      

         id = Column(Integer, primary_key=True)                                      
         name = Column(String(50))  

create_fixture.py

 from __init__ import Base, session                                                                                
 from entity import Zone                                                                           
 from sqlalchemy import create_engine                                                         

 Base.metadata.create_all() 
 zone = Zone('zone_1')
 session.add(zone)
 session.commit()

输出

   2013-09-13 20:06:12,340 INFO sqlalchemy.engine.base.Engine select version()
    2013-09-13 20:06:12,341 INFO sqlalchemy.engine.base.Engine {}
    2013-09-13 20:06:12,345 INFO sqlalchemy.engine.base.Engine select current_schema()
    2013-09-13 20:06:12,345 INFO sqlalchemy.engine.base.Engine {}
    2013-09-13 20:06:12,352 INFO sqlalchemy.engine.base.Engine BEGIN (implicit)
    2013-09-13 20:06:12,354 INFO sqlalchemy.engine.base.Engine INSERT INTO zone (name) VALUES (%(name)s) RETURNING zone.id
    2013-09-13 20:06:12,354 INFO sqlalchemy.engine.base.Engine {'name': 'zone_1'}
    2013-09-13 20:06:12,356 INFO sqlalchemy.engine.base.Engine ROLLBACK

    sqlalchemy.exc.ProgrammingError: (ProgrammingError) relation "zone" does not exist
    LINE 1: INSERT INTO zone (name) VALUES ('zone_1') RETURNING zone.id

为什么不应用 SQLAlchemy 我的架构?如何修复它以便它应用我的架构?

4

0 回答 0