vmware-nsx/quantum/db/model_base.py
Avishay Balderman 5d41c5c817 Implementing string representation for model classes
We want to have meaningfull representation. This is
useful when we debug and want to see the actual
attributes of the object. The current __repr__
of those classes is the default python implementation
 and does not provide
information about the object attributes.
Solve Bug #1084231

Change-Id: I1ea5d741d2fd2da13712e0d51d2c73dfba4991cf
Solve the conflict below:
Conflicts:
	quantum/tests/unit/test_db_plugin.py
2012-12-26 14:14:33 +02:00

72 lines
2.3 KiB
Python

# Copyright (c) 2012 OpenStack, LLC.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
# implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from sqlalchemy.ext import declarative
from sqlalchemy import orm
class QuantumBase(object):
"""Base class for Quantum Models."""
def __setitem__(self, key, value):
setattr(self, key, value)
def __getitem__(self, key):
return getattr(self, key)
def get(self, key, default=None):
return getattr(self, key, default)
def __iter__(self):
self._i = iter(orm.object_mapper(self).columns)
return self
def next(self):
n = self._i.next().name
return n, getattr(self, n)
def update(self, values):
"""Make the model object behave like a dict"""
for k, v in values.iteritems():
setattr(self, k, v)
def iteritems(self):
"""Make the model object behave like a dict.
Includes attributes from joins."""
local = dict(self)
joined = dict([(k, v) for k, v in self.__dict__.iteritems()
if not k[0] == '_'])
local.update(joined)
return local.iteritems()
def __repr__(self):
"""sqlalchemy based automatic __repr__ method"""
items = ['%s=%r' % (col.name, getattr(self, col.name))
for col in self.__table__.columns]
return "<%s.%s[object at %x] {%s}>" % (self.__class__.__module__,
self.__class__.__name__,
id(self), ', '.join(items))
class QuantumBaseV2(QuantumBase):
@declarative.declared_attr
def __tablename__(cls):
# NOTE(jkoelker) use the pluralized name of the class as the table
return cls.__name__.lower() + 's'
BASEV2 = declarative.declarative_base(cls=QuantumBaseV2)