Python3 SQLAlchemy sqlalchemy.exc.UnboundExecutionError:无法找到在mapper Mapper或此Session上配置的绑定

时间:2016-05-16 10:41:06

标签: python sqlalchemy

第一次使用SQL Alchemy,我在尝试提交时一直收到错误。

Python3 SQLAlchemy 1.0.12

database.py

private void clearBTN_Click(object sender, EventArgs e)
    {
        recipientBox.Items.Clear();
        UpdateNoOfEmails();
    }

models.py

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

engine = create_engine("sqlite:///db.test")
db_session = scoped_session(sessionmaker(autocommit=False,
                                         autoflush=False,
                                         bind=engine))
Base = declarative_base()
Base.query = db_session.query_property()


def init_db():
    # import all modules here that might define models so that
    # they will be registered properly on the metadata.  Otherwise
    # you will have to import them first before calling init_db()
    import src.models
    Base.metadata.create_all(bind=engine)

创建数据库

from datetime import datetime

from typing import List

from sqlalchemy import Column, Table
from sqlalchemy import Integer, String, DateTime
from sqlalchemy import ForeignKey
from sqlalchemy.orm import relationship

from src.database import Base

class Answer(Base):
    """
    The answer for a question.
    """
    __tablename__ = "answer"

    answer_id = Column(Integer(), primary_key=True)
    answer = Column(String(), nullable=False, index=True)
    question_id = Column(Integer(), ForeignKey("question.question_id"))

    question = relationship("Question", back_populates="answer")

    def __init__(self, answer: str, question_id: int = None):
        self.answer = answer
        self.question_id = question_id

class Question(Base):
    __tablename__ = "question"

    question_id = Column(Integer(), primary_key=True)
    question = Column(String(), nullable=False, unique=True, index=True)
    answer = relationship("Answer", uselist=False, back_populates="question")

    def __init__(self, question: str, answer: Answer, options: List[Option] = None):
        self.question = question
        self.answer = answer
        if options:
            self.options = options

这会按预期创建数据库

将项目添加到数据库

>>> from src.database import init_db
>>> init_db()

直到现在我没有收到错误

>>> from src.models import Question, Answer
>>> a = Answer("Yes")
>>> q = Question("Doctor Who?", a)
>>> from sqlalchemy.orm import Session
>>> s = Session()
>>> s.add(a)
>>> s.add(q)

我收到错误:

>>> s.commit()

我能做些什么才能让它发挥作用?

1 个答案:

答案 0 :(得分:2)

来自"Using the Session"

  

sessionmaker类通常用于创建顶级Session配置

您不应该尝试直接使用Session类创建会话。使用 database.py 中定义的scoped_session包裹的sessionmaker,因为它配置了正确的绑定等。

>>> from src.models import Question, Answer
>>> from src.database import db_session
>>> a = Answer("Yes")
>>> q = Question("Doctor Who?", a)
>>> s = db_session()
>>> s.add(a)
>>> s.add(q)
>>> s.commit()

您还可以使用scoped_session as a proxy