sqlalchemy.py 文件源码

python
阅读 24 收藏 0 点赞 0 评论 0

项目:ormeasy 作者: spoqa 项目源码 文件源码
def repr_entity(entity: object) -> str:
    """Make a representation string for the given ``entity`` object.
    If the class specified ``__repr_columns__`` it prints
    these attributes instead of its primary keys.


    .. code-block::

       from sqlalchemy.ext.declarative import as_declarative
       from ormeasy.sqlalchemy import repr_entity

       @as_declarative()
       class Base:

          def __repr__(self):
              return repr_entity(self)


       class Song(Base):

          __tablename__ = 'song'

          __repr_columns__ = 'name', 'genre'

          id = Column(Integer, primary_key=True)

          name = Column(Unicode)

          genre = Column(Unicode)


       print(repr(Song(name='hello', genre='brit-pop'))) # it prints `<Song name=hello, genre=brit-pop>`

    .. seealso::

       ``as_declarative``
          http://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/api.html#sqlalchemy.ext.declarative.as_declarative

    :param entity: an object to make a representation string
    :return: a representation string
    :rtype: :class:`str`

    """  # noqa
    cls = type(entity)
    mod = cls.__module__
    name = ('' if mod == '__main__ ' else mod + '.') + cls.__qualname__
    try:
        columns = entity.__repr_columns__
    except AttributeError:
        columns = cls.__mapper__.primary_key
    names = (column if isinstance(column, str) else column.name
             for column in columns)
    pairs = ((name, getattr(entity, name))
             for name in names
             if hasattr(entity, name))
    args = ' '.join(k + '=' + repr(v) for k, v in pairs)
    return '<{0} {1}>'.format(name, args)
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号