diff options
author | Simen Linderud <simen.linderud@gmail.com> | 2019-12-08 15:55:10 +0100 |
---|---|---|
committer | GitHub <noreply@github.com> | 2019-12-08 15:55:10 +0100 |
commit | 4dece982e5630dd57d49a10bd043b1e21da1b669 (patch) | |
tree | 6b94e93e30eb75bb149ca5dd7101d505e7d462ce /templating/templating.py | |
parent | 96fa1c1278850113cbbb86e098f3ec74d4fa61fd (diff) | |
parent | e3f94592109a476426b6c2945c4a8a8943f572ad (diff) |
Merge pull request #214 from slinderud/master
Templating: improved templating.py, added readme with examples, and a test template that uses the API
Diffstat (limited to 'templating/templating.py')
-rwxr-xr-x | templating/templating.py | 37 |
1 files changed, 26 insertions, 11 deletions
diff --git a/templating/templating.py b/templating/templating.py index 87853b6..1eff4a3 100755 --- a/templating/templating.py +++ b/templating/templating.py @@ -8,20 +8,26 @@ import netaddr import requests from flask import Flask, request -from jinja2 import Environment, FileSystemLoader, TemplateNotFound +from jinja2 import Environment, FileSystemLoader, TemplateNotFound, TemplateError -endpoints = "read/networks read/oplog read/snmp read/switches-management public/distro-tree public/config public/dhcp public/dhcp-summary public/ping public/switches public/switch-state".split() +endpoints = ["read/networks", "read/oplog", "read/snmp", "read/switches-management", "public/distro-tree", + "public/config", "public/dhcp", "public/dhcp-summary", "public/ping", "public/switches", + "public/switch-state"] objects = {} -def getEndpoint(endpoint): - r = requests.get("http://localhost:80/api/{}".format(endpoint)) - if r.status_code != 200: - raise Exception("Bad status code for endpoint {}: {}".format(endpoint, r.status_code)) - return r.json() +def getEndpoint(endpoint: str) -> dict: + """ + Fetches an endpoint and returns the data as a dict. + """ + uri = f"{args.server}/api/{endpoint}" + r = requests.get(uri, timeout=args.timeout) + r.raise_for_status() + return r.json() + def updateData(): for a in endpoints: objects[a] = getEndpoint(a) @@ -52,14 +58,20 @@ def add_header(response): @app.route("/<path>", methods=["GET"]) def root_get(path): - updateData() try: + updateData() template = env.get_template(path) body = template.render(objects=objects, options=request.args) + except (requests.exceptions.ConnectTimeout, requests.exceptions.ConnectionError) as error: + return f'Timeout or connection error from gondul: {err}', 500 except TemplateNotFound: - return 'Template "{}" not found\n'.format(path), 404 + return f'Template "{path}" not found\n', 404 + except TemplateError as err: + return f'Templating of "{path}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{err}\n----\n\n{traceback.format_exc()}\n', 400 + except requests.exceptions.HTTPError as err: + return f'HTTP error from gondul: {err}', 500 except Exception as err: - return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 + return f'Uncaught error: {err}', 500 return body, 200 @@ -71,7 +83,7 @@ def root_post(path): template = env.from_string(content.decode("utf-8")) body = template.render(objects=objects, options=request.args) except Exception as err: - return 'Templating of "{}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{}\n----\n\n{}\n'.format(path, err, traceback.format_exc()), 400 + return 'Templating of "{path}" failed to render. Most likely due to an error in the template. Error transcript:\n\n{err}\n----\n\n{traceback.format_exc()}\n', 400 return body, 200 @@ -80,11 +92,14 @@ parser.add_argument("-t", "--templates", type=str, nargs="+", help="location of parser.add_argument("-h", "--host", type=str, default="127.0.0.1", help="host address") parser.add_argument("-p", "--port", type=int, default=8080, help="host port") parser.add_argument("-d", "--debug", action="store_true", help="enable debug mode") +parser.add_argument("-s", "--server", type=str, default="http://localhost:80", help="gondul server address") +parser.add_argument("-x", "--timeout", type=int, default=2, help="gondul server timeout") args = parser.parse_args() env.loader.searchpath = args.templates if not sys.argv[1:]: parser.print_help() + sys.exit(1) app.run(host=args.host, port=args.port, debug=args.debug) |