Exemplo n.º 1
0
    def instantiate(self, **extra_attrs):
        """
        Create an instance of a SQLAlchemy model class corresponding to
        my OFX tag, with attributes given by my contained OFX elements.

        If an instance that matches the given primary key signature has
        already been given, return that instead of creating a new one.
        """
        self.extra_attributes = extra_attrs
        # SECID needs to instantiate as SECINFO
        if self.tag == 'SECID':
            SubClass = models.SECINFO
        else:
            SubClass = getattr(models, self.tag)
        self._preflatten()
        self.attributes = self._flatten()
        self._postflatten()
        self.attributes.update(self.extra_attributes)
        self.extra_attributes = {}

        try:
            fingerprint = SubClass._fingerprint(**self.attributes)
            instance = DBSession.query(SubClass).filter_by(**fingerprint).one()
        except NoResultFound:
            instance = SubClass(**self.attributes)
            DBSession.add(instance)

        return instance