From 57bcf092dca572e50caab1ac98810cc3c44ba2c4 Mon Sep 17 00:00:00 2001 From: Samesh Lakhotia Date: Mon, 9 Mar 2020 19:32:28 +0530 Subject: [PATCH] FEAT: Add prototype of dynamic routes in hydrus the functions have been defined in app.py and not been imported from any other file is to avoid the circular dependency issues in flask at the prototype stage. I will fix this issue once the prototype is accepted related to #404 --- hydrus/app.py | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/hydrus/app.py b/hydrus/app.py index 92e328f3..945361d4 100644 --- a/hydrus/app.py +++ b/hydrus/app.py @@ -1,9 +1,14 @@ """Main route for the application""" import logging +import sys +from os.path import dirname, abspath +# insert the ./app.py file path in the PYTHONPATH variable for imports to work +sys.path.insert(0, dirname(dirname(abspath(__file__)))) from sqlalchemy import create_engine - +from flask import request +from collections import defaultdict from gevent.pywsgi import WSGIServer from sqlalchemy.orm import sessionmaker @@ -50,6 +55,42 @@ # Create a Hydrus app app = app_factory(API_NAME) socketio = create_socket(app, session) + +# global dict to store mapping of each function to be run before +# specified route. +# stores in the form {'path1': {'method1': function_before_path1_for_method1}} +before_request_funcs = defaultdict(dict) + + +@app.before_request +def before_request_callback(): + path = request.path + method = request.method + global before_request_funcs + func = before_request_funcs.get(path, {}).get(method, None) + if func: + func() + + +# decorator to define logic for custom before request methods +def custom_before_request(path, method): + def wrapper(f): + global before_request_funcs + before_request_funcs[path][method] = f + return f + return wrapper + + +@custom_before_request('/api/MessageCollection', 'PUT') +def do_this_before_put_on_drone_collections(): + print("Do something before PUT request on MessageCollection") + + +@custom_before_request('/api/MessageCollection', 'GET') +def do_this_before_get_on_drone_collections(): + print("Do something before GET request on MessageCollection") + + # # Nested context managers # @@ -72,3 +113,5 @@ http_server.serve_forever() except KeyboardInterrupt: pass + +