Created
March 30, 2016 17:34
-
-
Save michelp/77f0638d54fcec45e1b7d40cffa306bc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import re | |
| import psycopg2 | |
| import logging | |
| from json import dumps, loads | |
| from werkzeug.wrappers import Request, Response | |
| from werkzeug.wsgi import SharedDataMiddleware, DispatcherMiddleware | |
| from werkzeug.exceptions import NotFound | |
| from newsie.pgrpc import DB | |
| from psycopg2.extras import Json | |
| global conn | |
| conn = psycopg2.connect('postgresql://postgres:postgres@localhost/politips') | |
| logger = logging.getLogger(__name__) | |
| location_re = re.compile( | |
| r"/(?P<db>\w+)/(?P<schema>\w+)/(?P<function>\w+)(?P<path>/.*){0,}$" | |
| ) | |
| query_template = """ | |
| select array_to_json(array_agg(row_to_json(r, true)), true)::text | |
| from (select * from {}(%s, %s::jsonb, %s::jsonb | |
| """ | |
| @Request.application | |
| def api_app(request): | |
| conn.rollback() | |
| try: | |
| methods = dict(GET=query_template + ") as result ) r", | |
| POST=query_template + ", %s) as result ) r") | |
| groups = location_re.match(request.path).groups() | |
| if not groups: | |
| raise Exception('badz') | |
| db, schema, func_name, path = groups | |
| path = '' if path is None else path | |
| path = Json(filter(None, path.split('/'))) | |
| method = request.method | |
| function = '{}.{}_{}'.format(schema, method, func_name) | |
| template = methods.get(method) | |
| if not template: | |
| raise Exception('bad method') | |
| query = template.format(function) | |
| args = Json(dict(request.args)) | |
| environ = Json({k: v for k, v in request.environ.items() if k.isupper()}) | |
| if method == 'GET': | |
| args = (environ, path, args) | |
| elif method == 'POST': | |
| args = ('', path, args, Json(loads(request.get_data()))) | |
| with conn.cursor() as cur: | |
| cur.execute(query, args) | |
| result = cur.fetchone()[0] | |
| conn.commit() | |
| response = Response(result, mimetype='application/json') | |
| response.cache_control.max_age = 300 | |
| return response | |
| except: | |
| logger.exception(request.path) | |
| conn.rollback() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment