SQLAlchemy वर्जनिंग क्लास इंपोर्ट ऑर्डर की परवाह करता है


111

मैं यहाँ गाइड का अनुसरण कर रहा था:

http://www.sqlalchemy.org/docs/orm/examples.html?highlight=versioning#versioned-objects

और एक मुद्दे पर आए हैं। मैंने अपने रिश्तों को परिभाषित किया है जैसे:

generic_ticker = relation('MyClass', backref=backref("stuffs"))

तार के साथ तो यह मेरे मॉडल मॉड्यूल के आयात के आदेश के बारे में परवाह नहीं करता है। यह सब सामान्य रूप से ठीक काम करता है, लेकिन जब मैं संस्करणकरण मेटा का उपयोग करता हूं तो मुझे निम्नलिखित त्रुटि मिलती है:

sqlalchemy.exc.InvalidRequestError: जब मैपर मैपर। MyClass, एक्‍सप्राइज़िंग '' ट्रेडर '' आरंभ करने में एक नाम खोजने में विफल रहा ("नाम 'MyClass' परिभाषित नहीं है)। यदि यह एक वर्ग का नाम है, तो दोनों निर्भर वर्गों को परिभाषित करने के बाद इस संबंध को वर्ग में जोड़ने पर विचार करें।

मैंने निम्न त्रुटि को ट्रैक किया:

  File "/home/nick/workspace/gm3/gm3/lib/history_meta.py", line 90, in __init__
    mapper = class_mapper(cls)
  File "/home/nick/venv/tg2env/lib/python2.6/site-packages/sqlalchemy/orm/util.py", line 622, in class_mapper
    mapper = mapper.compile()

class VersionedMeta(DeclarativeMeta):
    def __init__(cls, classname, bases, dict_):
        DeclarativeMeta.__init__(cls, classname, bases, dict_)

        try:
            mapper = class_mapper(cls)
            _history_mapper(mapper)
        except UnmappedClassError:
            pass

मैंने कोशिश डालकर समस्या को ठीक किया: एक मेमने में सामान छोड़कर और सभी आयात होने के बाद उन्हें चलाने। यह काम करता है लेकिन थोड़ा बकवास लगता है, इसे ठीक करने का कोई विचार बेहतर तरीका है?

धन्यवाद!

अपडेट करें

समस्या वास्तव में आयात आदेश के बारे में नहीं है। वर्जनिंग उदाहरण को इस तरह बनाया गया है कि मैपर को प्रत्येक वर्जन क्लास के कॉस्ट्रोक्टर में संकलन की आवश्यकता होती है। और संकलन तब विफल हो जाता है जब संबंधित कक्षाएं अभी तक परिभाषित नहीं की जाती हैं। परिपत्र संबंधों के मामले में, मैप की गई कक्षाओं की परिभाषा क्रम को बदलकर इसे काम करने का कोई तरीका नहीं है।

अपडेट २

जैसा कि उपरोक्त अपडेट में कहा गया है (मुझे नहीं पता था कि आप अन्य लोगों के पोस्ट को यहां संपादित कर सकते हैं :)) यह परिपत्र संदर्भों के कारण होने की संभावना है। जिस स्थिति में हो सकता है कि कोई व्यक्ति मेरे हैक को उपयोगी समझे (मैं इसे अशांति के साथ इस्तेमाल कर रहा हूं)

create_mappers = []
class VersionedMeta(DeclarativeMeta):
    def __init__(cls, classname, bases, dict_):
        DeclarativeMeta.__init__(cls, classname, bases, dict_)
        #I added this code in as it was crashing otherwise
        def make_mapper():
            try:
                mapper = class_mapper(cls)
                _history_mapper(mapper)
            except UnmappedClassError:
                pass

        create_mappers.append(lambda: make_mapper())

तब आप अपने मॉडल __init__.py में निम्न जैसा कुछ कर सकते हैं

# Import your model modules here.
from myproj.lib.history_meta import create_mappers

from myproj.model.misc import *
from myproj.model.actor import *
from myproj.model.stuff1 import *
from myproj.model.instrument import *
from myproj.model.stuff import *

#setup the history
[func() for func in create_mappers]

इस तरह यह सभी वर्गों को परिभाषित करने के बाद ही मैपर बनाता है।

अपडेट 3 थोड़ा असंबद्ध लेकिन मैं कुछ परिस्थितियों में एक डुप्लिकेट प्राथमिक कुंजी त्रुटि के लिए आया था (एक में एक ही वस्तु में 2 परिवर्तन करना)। मेरा वर्कअराउंड एक नया प्राथमिक ऑटो-इन्क्रिमेंटिंग कुंजी जोड़ने के लिए किया गया है। बेशक, आपके पास mysql के साथ 1 से अधिक नहीं हो सकता है, इसलिए मुझे इतिहास तालिका बनाने के लिए उपयोग किए जाने वाले मौजूदा सामान को प्राथमिक करना होगा। मेरा समग्र कोड देखें (एक hist_id सहित और विदेशी कुंजी बाधा से छुटकारा पाना):

"""Stolen from the offical sqlalchemy recpies
"""
from sqlalchemy.ext.declarative import DeclarativeMeta
from sqlalchemy.orm import mapper, class_mapper, attributes, object_mapper
from sqlalchemy.orm.exc import UnmappedClassError, UnmappedColumnError
from sqlalchemy import Table, Column, ForeignKeyConstraint, Integer
from sqlalchemy.orm.interfaces import SessionExtension
from sqlalchemy.orm.properties import RelationshipProperty
from sqlalchemy.types import DateTime
import datetime
from sqlalchemy.orm.session import Session

def col_references_table(col, table):
    for fk in col.foreign_keys:
        if fk.references(table):
            return True
    return False

def _history_mapper(local_mapper):
    cls = local_mapper.class_

    # set the "active_history" flag
    # on on column-mapped attributes so that the old version
    # of the info is always loaded (currently sets it on all attributes)
    for prop in local_mapper.iterate_properties:
        getattr(local_mapper.class_, prop.key).impl.active_history = True

    super_mapper = local_mapper.inherits
    super_history_mapper = getattr(cls, '__history_mapper__', None)

    polymorphic_on = None
    super_fks = []
    if not super_mapper or local_mapper.local_table is not super_mapper.local_table:
        cols = []
        for column in local_mapper.local_table.c:
            if column.name == 'version':
                continue

            col = column.copy()
            col.unique = False

            #don't auto increment stuff from the normal db
            if col.autoincrement:
                col.autoincrement = False
            #sqllite falls over with auto incrementing keys if we have a composite key
            if col.primary_key:
                col.primary_key = False

            if super_mapper and col_references_table(column, super_mapper.local_table):
                super_fks.append((col.key, list(super_history_mapper.base_mapper.local_table.primary_key)[0]))

            cols.append(col)

            if column is local_mapper.polymorphic_on:
                polymorphic_on = col

        #if super_mapper:
        #    super_fks.append(('version', super_history_mapper.base_mapper.local_table.c.version))

        cols.append(Column('hist_id', Integer, primary_key=True, autoincrement=True))
        cols.append(Column('version', Integer))
        cols.append(Column('changed', DateTime, default=datetime.datetime.now))

        if super_fks:
            cols.append(ForeignKeyConstraint(*zip(*super_fks)))

        table = Table(local_mapper.local_table.name + '_history', local_mapper.local_table.metadata,
                      *cols, mysql_engine='InnoDB')
    else:
        # single table inheritance.  take any additional columns that may have
        # been added and add them to the history table.
        for column in local_mapper.local_table.c:
            if column.key not in super_history_mapper.local_table.c:
                col = column.copy()
                super_history_mapper.local_table.append_column(col)
        table = None

    if super_history_mapper:
        bases = (super_history_mapper.class_,)
    else:
        bases = local_mapper.base_mapper.class_.__bases__
    versioned_cls = type.__new__(type, "%sHistory" % cls.__name__, bases, {})

    m = mapper(
            versioned_cls, 
            table, 
            inherits=super_history_mapper, 
            polymorphic_on=polymorphic_on,
            polymorphic_identity=local_mapper.polymorphic_identity
            )
    cls.__history_mapper__ = m

    if not super_history_mapper:
        cls.version = Column('version', Integer, default=1, nullable=False)

create_mappers = []

class VersionedMeta(DeclarativeMeta):
    def __init__(cls, classname, bases, dict_):
        DeclarativeMeta.__init__(cls, classname, bases, dict_)
        #I added this code in as it was crashing otherwise
        def make_mapper():
            try:
                mapper = class_mapper(cls)
                _history_mapper(mapper)
            except UnmappedClassError:
                pass

        create_mappers.append(lambda: make_mapper())

def versioned_objects(iter):
    for obj in iter:
        if hasattr(obj, '__history_mapper__'):
            yield obj

def create_version(obj, session, deleted = False):
    obj_mapper = object_mapper(obj)
    history_mapper = obj.__history_mapper__
    history_cls = history_mapper.class_

    obj_state = attributes.instance_state(obj)

    attr = {}

    obj_changed = False

    for om, hm in zip(obj_mapper.iterate_to_root(), history_mapper.iterate_to_root()):
        if hm.single:
            continue

        for hist_col in hm.local_table.c:
            if hist_col.key == 'version' or hist_col.key == 'changed' or hist_col.key == 'hist_id':
                continue

            obj_col = om.local_table.c[hist_col.key]

            # get the value of the
            # attribute based on the MapperProperty related to the
            # mapped column.  this will allow usage of MapperProperties
            # that have a different keyname than that of the mapped column.
            try:
                prop = obj_mapper.get_property_by_column(obj_col)
            except UnmappedColumnError:
                # in the case of single table inheritance, there may be 
                # columns on the mapped table intended for the subclass only.
                # the "unmapped" status of the subclass column on the 
                # base class is a feature of the declarative module as of sqla 0.5.2.
                continue

            # expired object attributes and also deferred cols might not be in the
            # dict.  force it to load no matter what by using getattr().
            if prop.key not in obj_state.dict:
                getattr(obj, prop.key)

            a, u, d = attributes.get_history(obj, prop.key)

            if d:
                attr[hist_col.key] = d[0]
                obj_changed = True
            elif u:
                attr[hist_col.key] = u[0]
            else:
                # if the attribute had no value.
                attr[hist_col.key] = a[0]
                obj_changed = True

    if not obj_changed:
        # not changed, but we have relationships.  OK
        # check those too
        for prop in obj_mapper.iterate_properties:
            if isinstance(prop, RelationshipProperty) and \
                attributes.get_history(obj, prop.key).has_changes():
                obj_changed = True
                break

    if not obj_changed and not deleted:
        return

    attr['version'] = obj.version
    hist = history_cls()
    for key, value in attr.iteritems():
        setattr(hist, key, value)

    obj.version += 1
    session.add(hist)

class VersionedListener(SessionExtension):
    def before_flush(self, session, flush_context, instances):
        for obj in versioned_objects(session.dirty):
            create_version(obj, session)
        for obj in versioned_objects(session.deleted):
            create_version(obj, session, deleted = True)

6
पदावनत नामों का उपयोग न करें; relation()होना चाहिएrelationship()
ThiefMaster

25
बेझिझक इस के एक हिस्से को उत्तर में स्थानांतरित करें और इसे स्वीकार करें।
तोबू

54
क्या कोई समझा सकता है कि इस अनुत्तरित प्रश्न को ४ explain उत्थान क्यों मिले? ब्याज से बाहर के रूप में मैं स्पष्ट नहीं हूँ कि यहाँ क्या हो रहा है (एक अजगर देव नहीं)
Moak

4
@ मोहक - मुझे यकीन है कि यह बहुत सारे लोग हैं, जिन्होंने एक ही गाइड का अनुसरण किया है। क्या कोई समझा सकता है कि आपकी टिप्पणी 36 को क्यों मिली? वह SO :) का जादू है
alf

2
@alfonso और आपको क्यों मिला 1 :), यह youtube के अंगूठे की तरह शुरू हो रहा है :-)
Mouna Cheikhna

जवाबों:


2

मैंने कोशिश डालकर समस्या को ठीक किया: एक मेमने में सामान छोड़कर और सभी आयात होने के बाद उन्हें चलाने।

महान!

हमारी साइट का प्रयोग करके, आप स्वीकार करते हैं कि आपने हमारी Cookie Policy और निजता नीति को पढ़ और समझा लिया है।
Licensed under cc by-sa 3.0 with attribution required.