dodotable

Latest PyPI version Documentation Status https://travis-ci.org/spoqa/dodotable.svg?branch=master

HTML table representation for SQLAlchemy .

SQLAlchemy to <table>

Assume you have an entity called Music. It looks like the below.

class Music(Base):

    id = Column(Integer, primary_key=True)

    name = Column(Unicode, nullable=False)

The following code renders a sortable <table> consisting of a list of music.

from dodotable.schema import Table, Column

table = Table(
    cls=Music,
    label='music table',
    columns=[
        Column(attr='id', label=u'id', order_by='id.desc'),
        Column(attr='name', label=u'name'),
    ],
    sqlalchemy_session=session
)
print(table.select(offset=0, limit=10).__html__())

Using with Flask

Flask uses Jinja2 as the template engine. As they mentioned on document[1]_, it is one of strategy that implement __html__ on every class inherit dodotable.schema.Renderable to convert a instance into HTML directly in Jinja2. Re-write the example written before with Flask.

from dodotable.schema import Table, Column
from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/musics/', methods=['GET'])
def list_musics():
    table = Table(
        cls=Music,
        label='music table',
        columns=[
            Column(attr='id', label=u'id',
                   order_by=request.args.get('order_by')),
            Column(attr='name', label=u'name'),
        ],
        sqlalchemy_session=session
    )
    return render_template(
        'list_musics.html',
        table=table.select(limit=request.args.get('limit'),
                           offset=request.args.get('offset'))
    )

And list_musics.html which is jinja2 template is look like below.

[1]http://jinja.pocoo.org/docs/dev/api/#jinja2.Markup

Contents:

dodotable — HTML table representation for SQLAlchemy

dodotable.condition — Hello filter!

class dodotable.condition.Ilike(cls, attribute_name, request_args)

SQL ILIKE 연산을 담당하는 필터

Column 에 포함 가능한 필터로, 단어를 받아서 그 단어에 대한 조건을 생성합니다.

>>> print(Ilike(Music, 'name', request_args))
lower(music.name) LIKE lower(:name_1)
Parameters:
  • cls
  • attribute_name
  • request_args
class dodotable.condition.IlikeAlias(identifier, alias_attr, request_args)

sqlalchemy alias 를 위한 ilike 필터.

Parameters:
  • identifier
  • alias_attr
  • request_args (Mapping) –
class dodotable.condition.IlikeSet(table, request_args, identifier=None)

모든 ILIKE 관련 연산을 묶습니다.

Table 에 포함 가능한 필터로, 해당 테이블에 있는 ILIKE 조건을 묶어서 OR 연산으로 묶습니다.

>>> table = Table(AdminRole, columns=[...])
>>> table.add_filter(IlikeSet(table, request_args))
>>> print(table.query)
SELECT ...
FROM admin_role AS admin_role_1
...
WHERE lower(name) LIKE lower(:name_1)
  OR lower(authority) LIKE lower(:authority_1)
...
Parameters:
  • table (dodotable.Table) –
  • request_args (Mapping) –
  • identifier
class dodotable.condition.Order(cls, attribute_name, order=None)

정렬 조건을 내보냅니다.

Parameters:
  • cls
  • attribute_name
  • order
ASCENDANT = 'asc'

오름차순

DESCENDANT = 'desc'

내림차순

class dodotable.condition.SelectFilter(cls, attribute_name, choices, request_args, default=None)

여러 옵션중 하나를 선택하는 필터를 만듭니다.

Parameters:
  • cls
  • attribute_name
  • choices
  • request_args (Mapping) –
  • default
dodotable.condition.create_search_name(name)

HTML form의 name을 생성합니다.

Parameters:cls
Returns:

dodotable.environment — Environment for dodotable

Customize your table

Dodotable has dodotable.environment.Environment to render data to template and get a instance of sqlalchemy.orm.session.Session to requeset a query to database.

Usually dodotable.environment.Environment used in dodotable.schema.Schema. dodotable.schema.Schema.environment generate template loader and define custom function to Jinja’s environment to call a functions in template.

So, you have to inherit environment class and implement some methods,

A good example is dodotable.environment.flask.FlaskEnvironment. more examples are in it.

dodotable.environment.flask — Flask environment

Yet, dodotable only supports Jinja2 for template, it can be possible to use another template engine but if you have a mind to use Jinja2, maybe you have interest with Flask either.

Originally dodotable are intended to use with Flask, so its environment class is provided.

Customize HTML

Maybe you wish to change a design of your table or add some help message, give your class name on HTML elements. So all you have to do is inehrit one of environment class, and use it in your table.

# yourapplication/dodotable.py
from dodotable.schema import Column as SchemaColumn, Table as SchemaTable
from dodotable.environment.flask import FlaskEnvironment
from jinja2 import PackageLoader

class CustomEnvironment(FlaskEnvironment):

    @property
    def template_loader(self):
        return PackageLoader('yourapplication', 'templates')


class Column(SchemaColumn):

    environment = CustomEnvironment()


class Table(SchemaTable):

    environment = CustomEnvironment()
#yourapplication/app.py
from flask import Flask, render_template

from .dodotable import Table, Column

app = Flask(__name__)


@app.route('/', methods=['GET'])
def index():
    table = Table(columns=[
        Column(...)
    ], ...)
    return render_template('index.html', table=table.select(0, 10))
class dodotable.environment.flask.FlaskEnvironment(locale_selector=None, *args, **kwargs)

Build table with flask

class dodotable.environment.Environment(locale_selector=None)

Top-level environment class, every environment class implemented by inherit this class.

Parameters:locale_selector (Callable) – a locale returning nullary function for selection of the right translation. the type of a return value can be str or babel.core.Locale as well. if it’s omitted or a return value is None English is shown.
template_loader

Get custom template loader

Returns:jinja template loader
Return type:jinja2.loaders.BaseLoader

dodotable.exc — Errors

exception dodotable.exc.BadChoice

예상하지 못한 선택지를 골랐을 때 발생합니다.

dodotable.helper — helper

class dodotable.helper.Limit(table, request_args, identifier=None)

querystring 중에 limit를 조작해서 100개보기 같은 기능을 제공합니다.

dodotable.schema — table schema

class dodotable.schema.Cell(col, row, data, _repr=<class 'str'>, classes=())

테이블의 셀을 나타내는 클래스

Parameters:
  • col (int) – column 위치
  • row (int) – row 위치
  • data – 셀에 채워질 데이터
class dodotable.schema.Column(label, attr, order_by=(), filters=None, _repr=<class 'str'>, sortable=True, visible=True, classes=())

테이블의 열을 나타내는 클래스

Parameters:
  • label (str) – 컬럼 레이블
  • attr (str) – 가져올 attribute 이름
  • order_by (list) – 정렬 기준
  • filters (list) – 정렬 기준
  • _repr (function) – 보여질 형식
  • sortable (bool) – 정렬 가능 여부
  • visible (bool) – 테이블에 해당 칼럼이 보일지 말지의 여부. 해당 값이 False여도 :class:`~dodotable.condition.IlikeSet`의 필터에는 보이므로 검색에는 사용할 수 있습니다.
class dodotable.schema.LinkedColumn(*args, **kwargs)

링크가 걸려야 하는 열 나타내는 클래스

Parameters:
  • label (str) – 컬럼 레이블
  • attr (str) – 가져올 attribute 이름
  • or function endpoint (str) – 걸릴 링크 형식
  • order_by (list) – 정렬 기준
class dodotable.schema.ObjectColumn(label, attr, order_by=(), filters=None, _repr=<class 'str'>, sortable=True, visible=True, classes=())

Get __cell_.data as result instead of attribute.

class dodotable.schema.Queryable

Query 로 변환 가능한 객체

쿼리를 내뱉는 모든 필더들은 Queryable 을 상속받고 __query__() 를 구현하여 sqlalchemy 쿼리로 사용할 수 있도록 변환해야합니다.

class dodotable.schema.Renderable

jinja에서 바로 렌더링되는 클래스의 상위 클래스

jinja에서는 __html__ 를 호출하여 렌더링을 하므로 Renderable 을 상속받아 __html__() 을 구현하는 경우 바로 렌더링 할 수 있습니다.

class SomeElem(Renderable):

    def __html__(self):
         return "<h1>Hello World</h1>"
{{ SomeElem() }} <!-- == <h1>Hello World</h1> -->
class dodotable.schema.Row

테이블에 행을 나타내는 클래스

append(cell)

행에 cell을 붙입니다.

class dodotable.schema.Table(cls, label, unit_label='row', columns=None, sqlalchemy_session=None)

데이터를 나타내는 테이블의 틀

Parameters:
  • cls
  • label
  • columns
  • sqlalchemy_session
query

쿼리를 만듭니다.

Returns:
class dodotable.schema.Schema
Parameters:environment (Environment) –

dodotable.util — utilities

dodotable.util.camel_to_underscore(name)

CamelCase로 주어진 name을 underscore_with_lower_case로 변환합니다

>>> camel_to_underscore('SomePythonClass')
'some_python_class'
Parameters:name (str) – name to convert
Returns:converted name
Return type:str
dodotable.util.render(template_name, extra_environments=None, **kwargs)

주어진 템플릿을 jinja로 렌더링합니다

Parameters:template_name
Returns:
dodotable.util.string_literal

alias of str

Changelog

Version 0.5.1

To be released.

Indices and tables