|
| 1 | +from textwrap import indent |
| 2 | +from pathlib import Path |
| 3 | +import os |
| 4 | +import yaml |
| 5 | + |
| 6 | + |
| 7 | +def populate_api(): |
| 8 | + header_template = """ |
| 9 | +# Auto-generated rest api |
| 10 | +from .server import app, protected_route |
| 11 | +from .interface import _DJConnector, dj |
| 12 | +import json |
| 13 | +import numpy as np |
| 14 | +
|
| 15 | +
|
| 16 | +class NumpyEncoder(json.JSONEncoder): |
| 17 | + def default(self, obj): |
| 18 | + if isinstance(obj, np.ndarray): |
| 19 | + return obj.tolist() |
| 20 | + return json.JSONEncoder.default(self, obj) |
| 21 | +""" |
| 22 | + route_template = """ |
| 23 | +
|
| 24 | +@app.route('{route}', methods=['GET']) |
| 25 | +@protected_route |
| 26 | +def {method_name}(jwt_payload: dict) -> dict: |
| 27 | +
|
| 28 | +{query} |
| 29 | + djconn = _DJConnector._set_datajoint_config(jwt_payload) |
| 30 | + vm_dict = {{s: dj.VirtualModule(s, s, connection=djconn) for s in dj.list_schemas()}} |
| 31 | + query, fetch_args = dj_query(vm_dict) |
| 32 | + return json.dumps(query.fetch(**fetch_args), cls=NumpyEncoder) |
| 33 | +""" |
| 34 | + |
| 35 | + spec_path = os.environ.get('API_SPEC_PATH') |
| 36 | + api_path = 'pharus/dynamic_api.py' |
| 37 | + with open(Path(api_path), 'w') as f, open(Path(spec_path), 'r') as y: |
| 38 | + f.write(header_template) |
| 39 | + values_yaml = yaml.load(y, Loader=yaml.FullLoader) |
| 40 | + pages = values_yaml['SciViz']['pages'] |
| 41 | + |
| 42 | + # Crawl through the yaml file for the routes in the components |
| 43 | + for page in pages.values(): |
| 44 | + for grid in page['grids'].values(): |
| 45 | + for comp in grid['components'].values(): |
| 46 | + f.write(route_template.format(route=comp['route'], |
| 47 | + method_name=comp['route'].replace('/', ''), |
| 48 | + query=indent(comp['dj_query'], ' '))) |
0 commit comments