#!/usr/bin/env python3 import os from datetime import datetime from configparser import ConfigParser from starlette.routing import Route, Router from starlette.responses import PlainTextResponse, JSONResponse from starlette.exceptions import HTTPException from pprint import pprint import uvicorn import json # pyHeatpump modules from pyheatpump.models.variable import Variable from pyheatpump.models.variable_type import VariableType from pyheatpump.models.variable_value import VariableValue async def get_variable_values(request): return JSONResponse({}) async def set_variable_values(request): raise NotImplementedError async def get_variable_value(type: str, address: int, time: str=None): try: args = { 'type': type, 'address': address, 'time': time } if time is None: args.pop('time') else: args['time'] = datetime.fromisoformat(time) row = VariableValue.get(**args) return PlainTextResponse(str(row.value)) except StopIteration: raise HTTPException(404) async def set_variable_value(request): raise NotImplementedError async def variable_values_routes(request, *args, **kwargs): if request['method'] == 'GET': return await get_variable_values(request) elif request['method'] == 'POST': return await set_variable_values(request) async def variable_value_routes(request, *args, **kwargs): if request['method'] == 'GET': if 'type' not in request.path_params.keys(): raise HTTPException(422) if 'address' not in request.path_params.keys(): raise HTTPException(422) if 'time' not in request.path_params.keys(): return await get_variable_value( request.path_params['type'], request.path_params['address']) return await get_variable_value( request.path_params['type'], request.path_params['address'], request.path_params['time']) elif request['method'] == 'POST': return await set_variable_value(request *args, **kwargs) ROUTES=[ Route('/', variable_values_routes, methods=['GET', 'POST']), Route('/{type:str}/{address:int}', variable_value_routes, methods=['GET', 'POST']), Route('/{type:str}/{address:int}/{time:str}', variable_value_routes, methods=['GET']) ] app = Router(routes=ROUTES) if __name__ == '__main__': uvicorn.run('pyHeatpump:variable_values.app', host='127.0.0.1', port=8000)