diff options
author | Kristian Lyngstol <kly@kly.no> | 2016-11-07 19:58:47 +0100 |
---|---|---|
committer | Kristian Lyngstol <kly@kly.no> | 2016-11-07 19:58:47 +0100 |
commit | fc1b028e555a3703fbc643965620dea919f3fe19 (patch) | |
tree | 5b39a3e9f942cd17172f9803872d310bbf21e8cb /templating/templating.py | |
parent | af7409a81be08a4e5b25adf0f1afb41fedce5e12 (diff) |
Add basic templating engine
It works fine.
Build scaffolding incoming
Diffstat (limited to 'templating/templating.py')
-rwxr-xr-x | templating/templating.py | 45 |
1 files changed, 45 insertions, 0 deletions
diff --git a/templating/templating.py b/templating/templating.py new file mode 100755 index 0000000..47c886d --- /dev/null +++ b/templating/templating.py @@ -0,0 +1,45 @@ +#!/usr/bin/env python3.4 + +import requests +from jinja2 import Template,Environment,FileSystemLoader +import json + +endpoints = "read/oplog read/snmp read/switches-management public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() +objects = dict() + +def getEndpoint(endpoint): + r = requests.get("http://localhost/api/%s" % endpoint, auth=('demo','demo')) + if (r.status_code != 200): + raise Exception("Bad status code for endpoint %s: %s" % (endpoint, r.status_code)) + return r.json() + +def updateData(): + for a in endpoints: + objects[a] = getEndpoint(a) + +env = Environment(loader=FileSystemLoader('templates/')) + +import http.server +class MyHandler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + print (self.path[1:]) + updateData() + try: + template = env.get_template(self.path[1:]) + body = template.render(objects=objects).encode('UTF-8') + self.send_response(200) + except: + body = "baaad\n".encode('UTF-8') + self.send_response(500) + self.send_header('Cache-Control','max-age=30, s-maxage=5') + self.send_header('Content-Length', int(len(body))) + self.end_headers() + self.wfile.write(body) + self.wfile.flush() + +def run(server_class=http.server.HTTPServer, handler_class=http.server.BaseHTTPRequestHandler): + server_address = ('', 8000) + httpd = server_class(server_address, handler_class) + httpd.serve_forever() + +run(handler_class=MyHandler) |