alchemyadmin / src / alchemyadmin / __init__.py

#
from werkzeug import Request, Response
from werkzeug.routing import Map, Rule
from werkzeug.exceptions import HTTPException
from jinja2 import Environment, PackageLoader
from sqlalchemy.orm import sessionmaker, scoped_session
from formalchemy import Grid

default_template_env = Environment(loader=PackageLoader('alchemyadmin', 'templates'))


class Application(object):
    def __init__(self, settings, *models, **modelsdict):
        self.template_env = default_template_env
        self.models = modelsdict.copy()
        self.DBSession = scoped_session(sessionmaker())
        for m in models:
            self.models[m.__name__.lower()] = m

        urls = Map([
                Rule('/', endpoint='index'),
                ])
        self.grids = {}
        for m in self.models:
            urls.add(Rule('/' + m, endpoint='model_index', 
                          defaults={'model':m}))
            self.grids[m] = grid = Grid(self.models[m])
            grid.configure(readonly=True)
        self.urls = urls

    def __call__(self, environ, start_response):
        try:
            adapter = self.urls.bind_to_environ(environ)
            endpoint, args = adapter.match()
            request = Request(environ)
            res = getattr(self, endpoint)(request, **args)
            
            return res(environ, start_response)
        except HTTPException, e:
            return e(environ, start_response)

    def index(self, request):
        res = Response(self.render('index.html', models=self.models),
                       content_type='text/html;charset=utf-8')
        return res

    def model_index(self, request, model):
        rows = self.DBSession.query(self.models[model]).all()
        grid = self.grids[model].bind(instances=rows)
        res = Response(self.render('model/index.html', 
                                   model=model,
                                   grid=grid,
                                   models=self.models),
                       content_type='text/html;charset=utf-8')
        return res

    def render(self, template_name, **kw):
        template = self.template_env.get_template(template_name)
        return template.render(**kw)
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.