Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/340.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 手动插入联接表继承模型的测试数据_Python_Sqlalchemy - Fatal编程技术网

Python 手动插入联接表继承模型的测试数据

Python 手动插入联接表继承模型的测试数据,python,sqlalchemy,Python,Sqlalchemy,我在SQLAlchemy的助手类中有一个get_或_create方法,但会话从不从查询中返回任何数据,因此总是尝试创建新行,即使数据库中存在相同的数据(然后抛出一个唯一CONSTRANT错误) 通过create方法单独添加数据确实可以成功地工作,并且数据会持久化到数据库中。在get\u或\u create()方法中,实例总是None,因此试图再次将数据添加到数据库中 下面的代码是来自完整应用程序的一个片段,应该足以说明问题 models.py: from sqlalchemy import Co

我在SQLAlchemy的助手类中有一个get_或_create方法,但会话从不从查询中返回任何数据,因此总是尝试创建新行,即使数据库中存在相同的数据(然后抛出一个
唯一CONSTRANT
错误)

通过create方法单独添加数据确实可以成功地工作,并且数据会持久化到数据库中。在
get\u或\u create()
方法中,实例总是
None
,因此试图再次将数据添加到数据库中

下面的代码是来自完整应用程序的一个片段,应该足以说明问题

models.py

from sqlalchemy import Column, Integer, String, ForeignKey, Float, Enum
from sqlalchemy.ext.declarative import declarative_base
import enum

Base = declarative_base()


class DepositStatus(enum.Enum):
    not_yet_paid = 1
    paid = 2
    to_be_refunded = 3
    deposit_kept = 4
    refunded = 5


class RiderStatus(enum.Enum):
    not_yet_started = 1
    active = 2
    finished = 3
    scratched = 4


class RiderCategories(enum.Enum):
    solo = 1
    pair = 2


class RiderGenders(enum.Enum):
    male = 1
    female = 2


class TrackerLocations(Base):
    __tablename__ = 'tracker_locations'
    id = Column('id', Integer, primary_key=True)
    types = Column(String)
    __mapper_args__ = {
        'polymorphic_on': types
    }


class Riders(TrackerLocations):

    __tablename__ = 'riders'
    id = Column(Integer, ForeignKey('tracker_locations.id'), primary_key=True,
                autoincrement=True)
    first_name = Column('first_name', String)
    last_name = Column('last_name', String)
    cap_number = Column('cap_number', String)
    category = Column('category', Enum(RiderCategories))
    status = Column('status', Enum(RiderStatus))
    gender = Column('gender', Enum(RiderGenders))
    deposit_status = Column('deposit_status', Enum(DepositStatus))
    deposit_amount = Column('deposit_amount', Float)
    email = Column('email', String)

    __mapper_args__ = {
        'polymorphic_identity': 'riders'
    }
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine
from models import Base

class DB(object):
    """
    To be used to interact with SQLAlchemy's ORM.
    """

    def __init__(self, db_uri):
        self.engine = create_engine(db_uri)
        Base.metadata.create_all(self.engine)
        self._session = scoped_session(sessionmaker(bind=self.engine))

    def close(self):
        self.session.close()

    def rollback(self):
        self.session.rollback()

    @property
    def session(self):
        return self._session()

    def get_or_create(self, model, commit=True, **kwargs):
        instance = self.session.query(model).filter_by(**kwargs).first()
        if instance:
            return instance, False
        else:
            instance = self.create(model, commit=commit, **kwargs)
            return instance, True

    def create(self, model, commit=True, **kwargs):
        instance = model(**kwargs)
        self.session.add(instance)
        if commit:
            self.session.commit()
        return instance
db.py

from sqlalchemy import Column, Integer, String, ForeignKey, Float, Enum
from sqlalchemy.ext.declarative import declarative_base
import enum

Base = declarative_base()


class DepositStatus(enum.Enum):
    not_yet_paid = 1
    paid = 2
    to_be_refunded = 3
    deposit_kept = 4
    refunded = 5


class RiderStatus(enum.Enum):
    not_yet_started = 1
    active = 2
    finished = 3
    scratched = 4


class RiderCategories(enum.Enum):
    solo = 1
    pair = 2


class RiderGenders(enum.Enum):
    male = 1
    female = 2


class TrackerLocations(Base):
    __tablename__ = 'tracker_locations'
    id = Column('id', Integer, primary_key=True)
    types = Column(String)
    __mapper_args__ = {
        'polymorphic_on': types
    }


class Riders(TrackerLocations):

    __tablename__ = 'riders'
    id = Column(Integer, ForeignKey('tracker_locations.id'), primary_key=True,
                autoincrement=True)
    first_name = Column('first_name', String)
    last_name = Column('last_name', String)
    cap_number = Column('cap_number', String)
    category = Column('category', Enum(RiderCategories))
    status = Column('status', Enum(RiderStatus))
    gender = Column('gender', Enum(RiderGenders))
    deposit_status = Column('deposit_status', Enum(DepositStatus))
    deposit_amount = Column('deposit_amount', Float)
    email = Column('email', String)

    __mapper_args__ = {
        'polymorphic_identity': 'riders'
    }
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy import create_engine
from models import Base

class DB(object):
    """
    To be used to interact with SQLAlchemy's ORM.
    """

    def __init__(self, db_uri):
        self.engine = create_engine(db_uri)
        Base.metadata.create_all(self.engine)
        self._session = scoped_session(sessionmaker(bind=self.engine))

    def close(self):
        self.session.close()

    def rollback(self):
        self.session.rollback()

    @property
    def session(self):
        return self._session()

    def get_or_create(self, model, commit=True, **kwargs):
        instance = self.session.query(model).filter_by(**kwargs).first()
        if instance:
            return instance, False
        else:
            instance = self.create(model, commit=commit, **kwargs)
            return instance, True

    def create(self, model, commit=True, **kwargs):
        instance = model(**kwargs)
        self.session.add(instance)
        if commit:
            self.session.commit()
        return instance
tests.py:

import os
import sqlite3
from tempfile import mkdtemp
from unittest import TestCase

from models import Riders
from db import DB

class TestDBInteractions(TestCase):

    @classmethod
    def setUpClass(cls):
        cls.temp_ = mkdtemp()
        cls.temp_db = os.path.join(cls.temp_, 'test_db.db')

    def setUp(self):
        self.db_uri = 'sqlite:///' + self.temp_db
        self.db = DB(self.db_uri)
        self.conn = sqlite3.connect(self.temp_db)
        self.cur = self.conn.cursor()

    def tearDown(self):
        self.db.close()

    def test_get_or_create(self):
        test_data = {
            'id': 1,
            'first_name': 'Bobby',
            'last_name': 'Hill',
            'cap_number': '123',
            'category': 'solo',
            'status': 'finished',
            'gender': 'male',
            'deposit_status': 'paid',
            'deposit_amount': 123.1,
            'email': 'hello@bob.com'
        }
        params = tuple(test_data.values())
        query = "INSERT INTO riders VALUES (?,?,?,?,?,?,?,?,?,?)"
        self.cur.execute(query, params)
        # # sqlite doesn't allow multiple write connections to the same DB, so close this connection
        self.conn.commit()
        self.conn.close()
        self.db1 = DB(db_uri=self.db_uri)
        response = self.db1.get_or_create(Riders, **{'id': 1})
        print(response)
使用SQLA,您可以很好地忘记甚至有两个表在使用

您的测试设置不会将任何数据插入到
跟踪器\u位置
,如果您实例化了
骑手的一个实例并通过ORM插入数据,则会出现这种情况

以下是SQLA生成的查询的连接部分:

FROM tracker_locations JOIN riders ON tracker_locations.id = riders.id
在您的测试数据集中,
tracker\u locations
中没有行,因此连接条件
tracker\u locations.id=riders.id
不会计算为true

因此,如果您还将一些测试数据包括在
tracker\u locations
表中,它将起作用:

tracker_locations_test_data = {'id': 1, 'type': 'riders'}
self.cur.execute(
    'INSERT INTO tracker_locations VALUES (?,?)', 
    tuple(tracker_locations_test_data.values()))

仅使用
sqlite3
手动将数据加载到
riders
表中,不足以尊重
riders
模型从
TrackerLocations
模型中的“联合继承”。您还必须将正确的数据填充到sqlalchemy的
跟踪器位置
,以便能够使用
模型
中的信息并进行正确的查找

使用:


对于测试,它应该可以工作。

太棒了!非常感谢。关于查看SQLA执行的SQL查询,学到了很好的一课。我已经在这个问题上纠缠太久了,我应该早点转向stackoverflow。再次感谢。是的,
echo=True
可以节省时间!您好,非常感谢您的帮助,这是您和Supershot强调的正确方法。由于外部链接和SQL查询的详细信息,仅接受他们的答案。再次感谢