From 4f5aa00041d3388d0eea8da766f6ecdbad019c53 Mon Sep 17 00:00:00 2001 From: "Dustin C. Hatch" Date: Sun, 15 Feb 2015 16:37:12 -0600 Subject: [PATCH] Start work on HTML UI --- src/dyns/controllers.py | 38 +++++++++++++++++++++++++++++--- src/dyns/templates/index.html.j2 | 13 +++++++++++ 2 files changed, 48 insertions(+), 3 deletions(-) create mode 100644 src/dyns/templates/index.html.j2 diff --git a/src/dyns/controllers.py b/src/dyns/controllers.py index 72ca2ef..8b65a8e 100644 --- a/src/dyns/controllers.py +++ b/src/dyns/controllers.py @@ -1,10 +1,17 @@ from . import model +import jinja2 import json import milla +class XHTMLResponse(milla.Response): + default_content_type = 'application/xhtml+xml' + + class BaseController(milla.controllers.Controller): + TMPL_LOADER = jinja2.PackageLoader(__name__.rsplit('.', 1)[0]) + def __init__(self): # allowed_methods must be set on the instance rather than the # class because of how Milla does attribute copying to the @@ -18,6 +25,28 @@ class BaseController(milla.controllers.Controller): super(BaseController, self).__before__(request) self.session = model.Session() + offers = [ + 'application/json', + 'application/xhtml+xml', + 'text/html', + ] + default_format = request.ResponseClass.default_content_type + want_fmt = request.accept.best_match(offers, default_format) + if want_fmt == 'application/json': + request.want = 'json' + elif want_fmt == 'text/html': + request.want = 'html' + else: + request.ResponseClass = XHTMLResponse + request.want = 'xhtml' + + env = jinja2.Environment(loader=self.TMPL_LOADER) + env.globals.update( + url=request.create_href, + static=request.static_resource, + ) + self.render = lambda t, **k: env.get_template(t).render(**k) + def __after__(self, request): self.session.rollback() self.session.bind.dispose() @@ -37,9 +66,12 @@ class ZoneListController(BaseController): def GET(self, request): response = request.ResponseClass() - response.content_type = 'application/json' - zones = map(model.Zone.as_dict, self.session.query(model.Zone)) - json.dump(list(zones), response.body_file) + zones = self.session.query(model.Zone) + if request.want == 'json': + response.content_type = 'application/json' + json.dump(list(map(model.Zone.as_dict, zones)), response.body_file) + else: + response.text = self.render('index.html.j2', zones=zones) return response HEAD = GET diff --git a/src/dyns/templates/index.html.j2 b/src/dyns/templates/index.html.j2 new file mode 100644 index 0000000..6f9ec9c --- /dev/null +++ b/src/dyns/templates/index.html.j2 @@ -0,0 +1,13 @@ + + + + +Zones + + +

Zones

+{% for zone in zones -%} +
{{ zone.name }}
+{% endfor -%} + +