SQLAlchemy,创建类时语法无效

时间:2016-02-27 04:04:25

标签: python sqlalchemy pytest

我在运行pytest时遇到错误,无法创建SQLAlchemy定义的对象。

from sqlalchemy import Table, ForeignKey, Column, Integer, String, Text, Date
from sqlalchemy.orm import relationship
from .constants import *
from .core import Base

attendsTable = Table("attends", Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))

class User(Base): << Invalid syntax
    __tablename__ = 'users'

    uid = Column(Integer, primary_key=True, autoincrement=True)
    name = Column(String, nullable=False)
    email = Column(String, nullable=False)
    picPath = Column(String, unique=True)
    description = Column(Text)

    #one-to-many relationship with groups
    created_groups = relationship("Group", back_populates="users")

    #many-to-many relationship with groups
    registered_groups = relationship("Group", secondary=attendsTable,
    back_populates="registered_users")

    def __repr__(self):
        return "<User(uid=%s, name=%s)>" %(self.uid, self.name)

这是我的pytest:

DB_CONN_URI = 'postgresql:://groupit:hx8889@localhost:5432/groupitdbtest'
SessionMaker = None
engine = None

@pytest.fixture(scope='module')
def postgresql_setup():
    from sqlalchemy.orm import sessionmaker
    from sqlalchemy import create_engine
    from models import model
    SessionMaker = sessionmaker()
    engine = create_engine(DB_CONN_URI)
    SessionMaker.configure(bind=engine)

def create_user(name_p, email_p, picPath_p, description_p):
    new_user = User(name=name_p, email=email_p, picPath=picPath_p,
                        descripton=description_p)
    return new_user

pytest的输出:

     @pytest.fixture(scope='module')
    def postgresql_setup():
        from sqlalchemy.orm import sessionmaker
        from sqlalchemy import create_engine
>       from models import model

sqlalchemy_createtables.py:15: 
_ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _

>   from .model import *
E     File "/home/ubuntu/workspace/groupitapp/groupit/models/model.py", line 10
E       class User(Base):
E           ^
E   SyntaxError: invalid syntax

../models/__init__.py:1: SyntaxError

这是pytest的问题还是在我运行应用程序时会出现的真正错误?

1 个答案:

答案 0 :(得分:1)

您缺少右括号

attendsTable = Table("attends", Base.metadata,
    Column('left_id', Integer, ForeignKey('left.id')),
    Column('right_id', Integer, ForeignKey('right.id'))
) # < HERE

class User(Base): 
    __tablename__ = 'users'

    # rest of the code