Example #1
0
    def test_duplicate(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertRaises(RuntimeError, pyamf.register_alias_type, DummyAlias, A)
Example #2
0
    def test_simple(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertEqual(util.get_class_alias(A), DummyAlias)
Example #3
0
    def test_duplicate(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertRaises(RuntimeError, pyamf.register_alias_type, DummyAlias, A)
Example #4
0
    def test_simple(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertEqual(util.get_class_alias(A), DummyAlias)
Example #5
0
    def test_single(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES.keys())
        self.assertEqual(pyamf.ALIAS_TYPES[DummyAlias], (A,))
Example #6
0
    def test_single(self):
        class A(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES.keys())
        self.assertEqual(pyamf.ALIAS_TYPES[DummyAlias], (A,))
Example #7
0
    def test_subclass(self):
        class A(object):
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertEquals(util.get_class_alias(B), DummyAlias)
Example #8
0
    def test_subclass(self):
        class A(object):
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)

        self.assertEquals(util.get_class_alias(B), DummyAlias)
Example #9
0
    def test_multiple(self):
        class A(object):
            pass

        class B(object):
            pass

        self.assertRaises(TypeError, pyamf.register_alias_type, DummyAlias, A, 'hello')

        pyamf.register_alias_type(DummyAlias, A, B)
        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES.keys())
        self.assertEquals(pyamf.ALIAS_TYPES[DummyAlias], (A, B))
Example #10
0
    def test_multiple(self):
        class A(object):
            pass

        class B(object):
            pass

        self.assertRaises(TypeError, pyamf.register_alias_type, DummyAlias, A, 'hello')

        pyamf.register_alias_type(DummyAlias, A, B)
        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES)
        self.assertEqual(pyamf.ALIAS_TYPES[DummyAlias], (A, B))
Example #11
0
    def test_registered_deep(self):
        class A:
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        self.addCleanup(pyamf.unregister_alias_type, DummyAlias)
        alias = self.context.getClassAlias(B)

        self.assertTrue(isinstance(alias, DummyAlias))
        self.assertIdentical(alias.klass, B)
Example #12
0
    def test_registered_deep(self):
        class A:
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        self.addCleanup(pyamf.unregister_alias_type, DummyAlias)
        alias = self.context.getClassAlias(B)

        self.assertTrue(isinstance(alias, DummyAlias))
        self.assertIdentical(alias.klass, B)
Example #13
0
    def test_nested(self):
        class A(object):
            pass

        class B(object):
            pass

        class C(object):
            pass

        pyamf.register_alias_type(DummyAlias, A, B, C)

        self.assertEqual(util.get_class_alias(B), DummyAlias)
Example #14
0
    def test_nested(self):
        class A(object):
            pass

        class B(object):
            pass

        class C(object):
            pass

        pyamf.register_alias_type(DummyAlias, A, B, C)

        self.assertEqual(util.get_class_alias(B), DummyAlias)
Example #15
0
    def test_unregister(self):
        """
        Tests for L{pyamf.unregister_alias_type}
        """
        class A(object):
            pass

        self.assertFalse(DummyAlias in pyamf.ALIAS_TYPES)
        self.assertEqual(pyamf.unregister_alias_type(A), None)

        pyamf.register_alias_type(DummyAlias, A)

        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES.keys())
        self.assertEqual(pyamf.unregister_alias_type(DummyAlias), (A,))
Example #16
0
    def test_unregister(self):
        """
        Tests for L{pyamf.unregister_alias_type}
        """
        class A(object):
            pass

        self.assertFalse(DummyAlias in pyamf.ALIAS_TYPES)
        self.assertEqual(pyamf.unregister_alias_type(A), None)

        pyamf.register_alias_type(DummyAlias, A)

        self.assertTrue(DummyAlias in pyamf.ALIAS_TYPES.keys())
        self.assertEqual(pyamf.unregister_alias_type(DummyAlias), (A,))
Example #17
0
    def test_registered_deep(self):
        x = pyamf.BaseContext()

        self.assertEquals(x.class_aliases, {})

        class A:
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        alias = x.getClassAlias(B)

        self.assertTrue(isinstance(alias, pyamf.ClassAlias))
        self.assertEquals(alias.__class__, DummyAlias)
        self.assertEquals(alias.klass, B)
Example #18
0
    def test_registered_deep(self):
        x = pyamf.BaseContext()

        self.assertEquals(x.class_aliases, {})

        class A:
            pass

        class B(A):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        alias = x.getClassAlias(B)

        self.assertTrue(isinstance(alias, pyamf.ClassAlias))
        self.assertEquals(alias.__class__, DummyAlias)
        self.assertEquals(alias.klass, B)
Example #19
0
    def test_multiple(self):
        class A(object):
            pass

        class B(object):
            pass

        class C(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        pyamf.register_alias_type(AnotherDummyAlias, B)
        pyamf.register_alias_type(YADummyAlias, C)

        self.assertEqual(util.get_class_alias(B), AnotherDummyAlias)
        self.assertEqual(util.get_class_alias(C), YADummyAlias)
        self.assertEqual(util.get_class_alias(A), DummyAlias)
Example #20
0
    def test_multiple(self):
        class A(object):
            pass

        class B(object):
            pass

        class C(object):
            pass

        pyamf.register_alias_type(DummyAlias, A)
        pyamf.register_alias_type(AnotherDummyAlias, B)
        pyamf.register_alias_type(YADummyAlias, C)

        self.assertEqual(util.get_class_alias(B), AnotherDummyAlias)
        self.assertEqual(util.get_class_alias(C), YADummyAlias)
        self.assertEqual(util.get_class_alias(A), DummyAlias)
Example #21
0
        if self.descriptor.parent:
            self.parent_descriptor = self.descriptor.parent._descriptor

        foreign_constraints = []

        for constraint in self.descriptor.constraints:
            for col in constraint.columns:
                col = str(col)

                if adapter.__version__.startswith('0.6'):
                    foreign_constraints.append(col)
                else:
                    if col.startswith(self.descriptor.tablename + '.'):
                        foreign_constraints.append(
                            col[len(self.descriptor.tablename) + 1:]
                        )

        if self.descriptor.polymorphic:
            self.exclude_attrs.update([self.descriptor.polymorphic])

        self.exclude_attrs.update(foreign_constraints)

    def _compile_base_class(self, klass):
        if klass is elixir.EntityBase or klass is elixir.Entity:
            return

        pyamf.ClassAlias._compile_base_class(self, klass)


pyamf.register_alias_type(ElixirAdapter, elixir.entity.is_entity)
    try:
        referenced_object = gae_objects.getClassKey(kls, s)
    except KeyError:
        gae_objects.addClassKey(kls, s, object)
        self.writeNonGAEObject(object, *args, **kwargs)

        return

    self.writeNonGAEObject(referenced_object, *args, **kwargs)

def install_gae_reference_model_hook(mod):
    """
    Called when L{pyamf.amf0} or L{pyamf.amf3} are imported. Attaches the
    L{writeGAEObject} method to the C{Encoder} class in that module.

    @param mod: The module imported.
    @since: 0.4.1
    """
    if not hasattr(mod.Encoder, 'writeNonGAEObject'):
        mod.Encoder.writeNonGAEObject = mod.Encoder.writeObject
        mod.Encoder.writeObject = writeGAEObject

# initialise the module here: hook into pyamf

pyamf.add_type(db.Query, util.to_list)
pyamf.register_alias_type(DataStoreClassAlias, db.Model, db.Expando)

# hook the L{writeGAEObject} method to the Encoder class on import
imports.whenImported('pyamf.amf0', install_gae_reference_model_hook)
imports.whenImported('pyamf.amf3', install_gae_reference_model_hook)
Example #23
0
 def test_subclass(self):
     self.assertFalse(issubclass(self.__class__, pyamf.ClassAlias))
     with self.assertRaises(ValueError):
         pyamf.register_alias_type(self.__class__)
Example #24
0
            for k in self.klass.properties().keys():
                setattr(obj, k, getattr(new_obj, k))

            for k in new_obj.dynamic_properties():
                setattr(obj, k, getattr(new_obj, k))

        obj.__class__ = self.klass

        for k, v in attrs.iteritems():
            if k in p_keys:
                prop = properties[k]

                if isinstance(v, datetime.datetime):
                    if isinstance(prop, db.DateProperty):
                        v = v.date()
                    elif isinstance(prop, db.TimeProperty):
                        v = v.time()

            setattr(obj, k, v)


def handleQuery(q):
    if q.count() == 0:
        return []

    return [i for i in q]


pyamf.add_type(db.Query, handleQuery)
pyamf.register_alias_type(DataStoreClassAlias, db.Model, db.Expando)
Example #25
0
        details_hash = Hash(details_hash)
        self.uid = details_hash.getlist('uid')
        self.givenName = details_hash.get('givenName')
        self.sn = details_hash.get('sn') # surname
        self.cn = details_hash.get('cn') # givenName + surname
        self.ispmanUserId = details_hash.get('ispmanUserId')
        self.mailLocalAddress = details_hash.get('mailLocalAddress')
        self.userPassword = details_hash.get('userPassword')
        self.mailForwardingAddress = details_hash.getlist('mailForwardingAddress')
        self.FTPStatus = details_hash.get('FTPStatus')
        self.FTPQuotaMBytes = details_hash.getint('FTPQuotaMBytes')
        self.mailQuota = details_hash.getint('mailQuota')
        self.ispmanCreateTimestamp = details_hash.getint('ispmanCreateTimestamp')
        self.mailAlias = details_hash.getlist('mailAlias')
        log.debug(self.uid)

    def __repr__(self):
        return "<%s - UID: %s; CN: '%s';>" % (self.__class__.__name__,
                                              self.uid, self.cn)

class DomainUserClassAlias(pyamf.ClassAlias):

    def createInstance(self, codec=None, *args, **kwargs):
        log.debug("CODEC: %r; ARGS: %r; KWARGS: %r", codec, args, kwargs)
        return DomainUser(args[0], kwargs)

    def checkClass(self, klass):
        pass

pyamf.register_alias_type(DomainUserClassAlias, DomainUser)
        datetime.time(0, 0, 0)
    )


def post_ndb_process(payload, context):
    """
    """
    stubs = context.get(NDB_STUB_NAME, None)

    if not stubs:
        return payload

    stubs.transform()

    return payload


# small optimisation to compile the ndb.Model base class
if hasattr(ndb.model, '_NotEqualMixin'):
    not_equal_mixin = pyamf.register_class(ndb.model._NotEqualMixin)
    not_equal_mixin.compile()

    del not_equal_mixin

# initialise the module here: hook into pyamf
pyamf.register_alias_type(NDBClassAlias, ndb.Model, ndb.Expando)
pyamf.add_type(ndb.Query, util.to_list)
pyamf.add_type(ndb.Model, encode_ndb_instance)
pyamf.add_post_decode_processor(post_ndb_process)
pyamf.add_type(ndb.Key, encode_ndb_key)
Example #27
0
    C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We
    use the datastore key to do the reference checking.

    @since: 0.4.1
    """
    if not obj.is_saved():
        encoder.writeObject(obj)

        return

    context = encoder.context
    kls = obj.__class__
    s = obj.key()

    gae_objects = getGAEObjects(context)

    try:
        referenced_object = gae_objects.getClassKey(kls, s)
    except KeyError:
        referenced_object = obj
        gae_objects.addClassKey(kls, s, obj)

    encoder.writeObject(referenced_object)


# initialise the module here: hook into pyamf

pyamf.register_alias_type(DataStoreClassAlias, db.Model)
pyamf.add_type(db.Query, util.to_list)
pyamf.add_type(db.Model, writeGAEObject)
    return datetime.datetime.combine(value, datetime.time(0, 0, 0))


def post_ndb_process(payload, context):
    """
    """
    stubs = context.get(NDB_STUB_NAME, None)

    if not stubs:
        return payload

    stubs.transform()

    return payload


# small optimisation to compile the ndb.Model base class
if hasattr(ndb.model, '_NotEqualMixin'):
    not_equal_mixin = pyamf.register_class(ndb.model._NotEqualMixin)
    not_equal_mixin.compile()

    del not_equal_mixin

# initialise the module here: hook into pyamf
pyamf.register_alias_type(NDBClassAlias, ndb.Model, ndb.Expando)
pyamf.add_type(ndb.Query, util.to_list)
pyamf.add_type(ndb.Model, encode_ndb_instance)
pyamf.add_post_decode_processor(post_ndb_process)
pyamf.add_type(ndb.Key, encode_ndb_key)
        read-only entities, we only care about the C{key} attribute.
        """
        assert type(obj) is BlobInfoStub

        key = attrs.pop('key', None)

        if not key:
            raise pyamf.DecodeError(
                "Unable to build blobstore.BlobInfo instance. Missing 'key' "
                "attribute."
            )

        try:
            key = blobstore.BlobKey(key)
        except:
            raise pyamf.DecodeError(
                "Unable to build a valid blobstore.BlobKey instance. Key "
                "supplied was %r" % (key,)
            )

        obj.__class__ = blobstore.BlobInfo

        obj.__init__(key)


pyamf.register_alias_type(BlobInfoClassAlias, blobstore.BlobInfo)
pyamf.register_class(blobstore.BlobInfo, '.'.join([
    blobstore.__name__,
    blobstore.BlobInfo.__name__
]))
Example #30
0
 def test_subclass(self):
     self.assertFalse(issubclass(self.__class__, pyamf.ClassAlias))
     with self.assertRaises(ValueError):
         pyamf.register_alias_type(self.__class__)
Example #31
0
                    static_attrs[name] = [x for x in getattr(obj, name).all()]
                elif isinstance(prop, models.ForeignKey):
                    if '_%s_cache' % name in obj.__dict__:
                        static_attrs[name] = getattr(obj, name)
                    else:
                        static_attrs[name] = None
                else:
                    static_attrs[name] = self._encodeValue(
                        prop, getattr(obj, name))

        return static_attrs, dynamic_attrs

    def applyAttributes(self, obj, attrs, codec=None):
        if not hasattr(self, 'static_attrs'):
            self.getAttrs(obj)

        for n, f in self.fields.iteritems():
            attrs[f.attname] = self._decodeValue(f, attrs[n])

        for f in self.klass.__dict__:
            prop = self.klass.__dict__[f]

            if isinstance(prop, property) and f in attrs.keys():
                if prop.fset is None:
                    del attrs[f]

        return pyamf.ClassAlias.applyAttributes(self, obj, attrs)


pyamf.register_alias_type(DjangoClassAlias, Model)
Example #32
0
        if self.descriptor.parent:
            self.parent_descriptor = self.descriptor.parent._descriptor

        foreign_constraints = []

        for constraint in self.descriptor.constraints:
            for col in constraint.columns:
                col = str(col)

                if adapter.__version__.startswith('0.6'):
                    foreign_constraints.append(col)
                else:
                    if col.startswith(self.descriptor.tablename + '.'):
                        foreign_constraints.append(
                            col[len(self.descriptor.tablename) + 1:])

        if self.descriptor.polymorphic:
            self.exclude_attrs.update([self.descriptor.polymorphic])

        self.exclude_attrs.update(foreign_constraints)

    def _compile_base_class(self, klass):
        if klass is elixir.EntityBase or klass is elixir.Entity:
            return

        pyamf.ClassAlias._compile_base_class(self, klass)


pyamf.register_alias_type(ElixirAdapter, elixir.entity.is_entity)
Example #33
0
    def applyAttributes(self, obj, attrs, **kwargs):
        """
        Applies C{attrs} to C{obj}. Since C{blobstore.BlobInfo} objects are
        read-only entities, we only care about the C{key} attribute.
        """
        assert type(obj) is BlobInfoStub

        key = attrs.pop('key', None)

        if not key:
            raise pyamf.DecodeError("Unable to build blobstore.BlobInfo "
                                    "instance. Missing 'key' attribute.")

        try:
            key = blobstore.BlobKey(key)
        except:
            raise pyamf.DecodeError(
                "Unable to build a valid blobstore.BlobKey "
                "instance. Key supplied was %r" % (key, ))

        obj.__class__ = blobstore.BlobInfo

        obj.__init__(key)


pyamf.register_alias_type(BlobInfoClassAlias, bi)
pyamf.register_class(bi, '.'.join([blobstore.__name__, bi.__name__]))

del bi
    C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We
    use the datastore key to do the reference checking.

    @since: 0.4.1
    """
    if not obj.is_saved():
        encoder.writeObject(obj)

        return

    context = encoder.context
    kls = obj.__class__
    s = obj.key()

    gae_objects = getGAEObjects(context)

    try:
        referenced_object = gae_objects.getClassKey(kls, s)
    except KeyError:
        referenced_object = obj
        gae_objects.addClassKey(kls, s, obj)

    encoder.writeObject(referenced_object)


# initialise the module here: hook into pyamf

pyamf.register_alias_type(DataStoreClassAlias, db.Model)
pyamf.add_type(db.Query, util.to_list)
pyamf.add_type(db.Model, writeGAEObject)
Example #35
0
    def applyAttributes(self, obj, attrs, **kwargs):
        """
        Applies C{attrs} to C{obj}. Since C{blobstore.BlobInfo} objects are
        read-only entities, we only care about the C{key} attribute.
        """
        assert type(obj) is BlobInfoStub

        key = attrs.pop('key', None)

        if not key:
            raise pyamf.DecodeError(
                "Unable to build blobstore.BlobInfo instance. Missing 'key' "
                "attribute.")

        try:
            key = blobstore.BlobKey(key)
        except:
            raise pyamf.DecodeError(
                "Unable to build a valid blobstore.BlobKey instance. Key "
                "supplied was %r" % (key, ))

        obj.__class__ = blobstore.BlobInfo

        obj.__init__(key)


pyamf.register_alias_type(BlobInfoClassAlias, blobstore.BlobInfo)
pyamf.register_class(
    blobstore.BlobInfo,
    '.'.join([blobstore.__name__, blobstore.BlobInfo.__name__]))
Example #36
0
        fields = obj._fields
        for key, value in attrs.items():
            if key not in fields.keys():
                print "Got unknown key '%s' for %r" % (key, obj)
                del attrs[key]
        return attrs


def map_mongoengine_document(klass):
    if not isinstance(klass, type):
        klass = type(klass)
    if issubclass(klass, BaseDocument):
        return True
    return False


def objectIDHack(obj, encoder=None):
    """
    For some reason ObjectIDs f**k everything up. I dont know why and when I try to find
    out I end up smashing things. So here a little hack!

    @param obj:
    @param encoder:
    @return:
    """
    encoder.writeObject({})


pyamf.register_alias_type(MongoEngineDocumentAlias, map_mongoengine_document)
pyamf.add_type(ObjectId, objectIDHack)
        return attrs

    def applyAttributes(self, obj, attrs, **kwargs):
        """
        Applies C{attrs} to C{obj}. Since C{blobstore.BlobInfo} objects are
        read-only entities, we only care about the C{key} attribute.
        """
        assert type(obj) is BlobInfoStub

        key = attrs.pop('key', None)

        if not key:
            raise pyamf.DecodeError("Unable to build blobstore.BlobInfo "
                "instance. Missing 'key' attribute.")

        try:
            key = blobstore.BlobKey(key)
        except:
            raise pyamf.DecodeError("Unable to build a valid blobstore.BlobKey "
                "instance. Key supplied was %r" % (key,))

        obj.__class__ = blobstore.BlobInfo

        obj.__init__(key)


pyamf.register_alias_type(BlobInfoClassAlias, bi)
pyamf.register_class(bi, '.'.join([blobstore.__name__, bi.__name__]))

del bi
Example #38
0
        if self.KEY_ATTR in attrs:
            del attrs[self.KEY_ATTR]

        return attrs

    def createInstance(self, *args, **kwargs):
        self.compile()

        return self.mapper.class_manager.new_instance()


def is_class_sa_mapped(klass):
    """
    @rtype: C{bool}
    """
    if not isinstance(klass, type):
        klass = type(klass)

    for c in class_checkers:
        if c(klass):
            return False

    try:
        class_mapper(klass)
    except UnmappedInstanceError:
        return False

    return True

pyamf.register_alias_type(SaMappedClassAlias, is_class_sa_mapped)
Example #39
0
            del attrs[self.KEY_ATTR]

        return attrs

    def createInstance(self, *args, **kwargs):
        self.compile()

        return self.mapper.class_manager.new_instance()


def is_class_sa_mapped(klass):
    """
    @rtype: C{bool}
    """
    if not isinstance(klass, type):
        klass = type(klass)

    for c in class_checkers:
        if c(klass):
            return False

    try:
        class_mapper(klass)
    except UnmappedInstanceError:
        return False

    return True


pyamf.register_alias_type(SaMappedClassAlias, is_class_sa_mapped)
Example #40
0
    given object graph.

    We create a new map on the encoder context object which contains a dict of
    C{object.__class__: {key1: object1, key2: object2, .., keyn: objectn}}. We
    use the primary key to do the reference checking.

    @since: 0.5
    """
    s = obj.pk

    if s is None:
        encoder.writeObject(obj)

        return

    django_objects = getDjangoObjects(encoder.context)
    kls = obj.__class__

    try:
        referenced_object = django_objects.getClassKey(kls, s)
    except KeyError:
        referenced_object = obj
        django_objects.addClassKey(kls, s, obj)

    encoder.writeObject(referenced_object)


# initialise the module here: hook into pyamf
pyamf.register_alias_type(DjangoClassAlias, Model)
pyamf.add_type(Model, writeDjangoObject)
from google.appengine.api import datastore_types

import pyamf


class GeoPtStub(object):
    pass


class GeoPtClassAlias(pyamf.ClassAlias):
    def createInstance(self, codec=None):
        return GeoPtStub()

    def getCustomProperties(self):
        self.static_attrs.extend(['lat', 'lon'])
        self.sealed = True

    def applyAttributes(self, obj, attrs, codec=None):
        obj.__dict__.clear()
        obj.__class__ = datastore_types.GeoPt

        obj.__init__(lat=attrs['lat'], lon=attrs['lon'])


pyamf.register_alias_type(GeoPtClassAlias, datastore_types.GeoPt)
pyamf.register_class(
    datastore_types.GeoPt, 'google.appengine.api.datastore_types.GeoPt'
)