Skip to content

Commit

Permalink
fix the interface to generate standard http response
Browse files Browse the repository at this point in the history
  • Loading branch information
Huang committed May 7, 2022
1 parent 977b99e commit 497c9e9
Show file tree
Hide file tree
Showing 6 changed files with 81 additions and 95 deletions.
9 changes: 3 additions & 6 deletions examples/python/interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,13 +35,10 @@ def check_response(response):
"""
if isinstance(response, requests.Response):
response = response.json()
status = response["status"]
message = response["message"]
payload = response["payload"]
status = response.status_code
response = response.json()
if status == 200:
print(message)
return payload
return response
print("Unexpected error: {}".format(message))
print("Exiting!")
sys.exit()
Expand Down
21 changes: 9 additions & 12 deletions restapi.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,21 @@

# GENERAL PACKAGE IMPORT
# ----------------------
from flask import Flask, request, jsonify
from flask import Flask, jsonify, make_response
from flask_restful import Resource, Api, reqparse
from flask_cors import CORS
import logging
import argparse


def construct(status, message, payload):
return {"status": status, "message": message, "payload": payload}


# LOGGING SETTING
if status == 200:
return make_response(jsonify(payload), 200)
elif status == 400:
return make_response(message, 400)
elif status == 500:
return make_response(message, 500)

# HELP MESSAGE
# ----------------
parser = argparse.ArgumentParser()
parser.add_argument("-l", "--log", dest="logLevel", choices=['DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL'],
help="Provide logging level. Example --log DEBUG'")
log_level = parser.parse_args()
logging.basicConfig(level=log_level.logLevel)
error_number_input = "{} cannot be blank and it should be a number"
# ----------------

Expand Down
66 changes: 29 additions & 37 deletions testcase.py
Original file line number Diff line number Diff line change
Expand Up @@ -272,21 +272,21 @@ def advance(self, u):
self.tic_time = time.time()
# Get full current state
payload = self._get_full_current_state()
message = "Advance simulation successful."
message = "Advancing simulation successfully."
logging.info(message)
return status, message, payload

else:
# Error in
status = 500
message = "Error Advancing Simulation : {}"
message = "Failed to advancing simulation: {}"
payload = res
logging.error(message.format(res))
return status, message, payload
else:
# Simulation at end time
payload = dict()
message = "Advance, simulation complete."
message = "Simulation completes."
logging.info(message)
return status, message, payload

Expand Down Expand Up @@ -338,24 +338,24 @@ def initialize(self, start_time, warmup_period, end_time=np.inf):
self.cal.initialize()
# Get full current state
payload = self._get_full_current_state()
message = "Initialize simulation, success."
message = "Initializing simulation successfully."
logging.info(message)
return status, message, payload

else:
status = 500
message = "Initialize simulation failed: {}".format(res)
message = "Failed to initialize simulation : {}".format(res)
logging.warning(message)
return status, message, {}

def get_step(self):
'''Returns the current simulation step in seconds.'''
status = 200
message = "Query simulation step successful."
message = "Query the simulation step successful."
if self.step is not None:
return status, message, self.step
status = 500
message = "Query simulation step failed."
message = "Query the simulation step failed."
return status, message, self.step

def set_step(self, step):
Expand All @@ -372,12 +372,12 @@ def set_step(self, step):
'''
status = 200
message = "Successfully set simulation step."
message = "Setting the simulation step successfully."
try:
self.step = float(step)
except:
status = 500
message = "Failed set simulation step."
message = "Failed to set the simulation step."
return status, message, None

def get_inputs(self):
Expand All @@ -394,17 +394,13 @@ def get_inputs(self):
'''
status = 200
message = "Query input list successful."
message = "Querying the input list successfully."
inputs = None
if self.inputs_metadata is not None:
try:
inputs = self.inputs_metadata
except:
status = 500
message = "Query input list failed."
inputs = self.inputs_metadata
else:
status = 500
message = "Query input list failed."
message = "Failed to query the input list."
return status, message, inputs

def get_measurements(self):
Expand All @@ -422,17 +418,13 @@ def get_measurements(self):
'''

status = 200
message = "Query measurement list successful."
message = "Querying the measurement list successfully."
measurements = None
if self.outputs_metadata is not None:
try:
measurements = self.outputs_metadata
except:
status = 500
message = "Query measurement list failed."
measurements = self.outputs_metadata
else:
status = 500
message = "Query measurement list failed."
message = "Failed to query the measurement list."
return status, message, measurements

def get_results(self, var, start_time, final_time):
Expand All @@ -458,7 +450,7 @@ def get_results(self, var, start_time, final_time):
'''
status = 200
message = "Successfully queried simulation for results."
message = "Querying simulation results successfully."
y = []
try:
# Get correct point
Expand All @@ -484,7 +476,7 @@ def get_results(self, var, start_time, final_time):
y[key] = y[key][time2<=final_time]
except:
status = 500
message = "Failed to query simulation for results: {}".format(traceback.format_exc())
message = "Failed to query simulation results: {}".format(traceback.format_exc())
if not isinstance(y, (list, type(None))):
for key in y:
y[key] = y[key].tolist()
Expand All @@ -507,7 +499,7 @@ def get_kpis(self):
'''
status = 200
message = "Query simulation for KPIs successful."
message = "Query simulation for KPIs successfulyl."
kpis = None
try:
# Set correct price scenario for cost
Expand All @@ -521,7 +513,7 @@ def get_kpis(self):
kpis = self.cal.get_core_kpis(price_scenario=price_scenario)
except:
status = 500
message = "Query simulation for KPIs failed: {}".format(traceback.format_exc())
message = "Failed to query KPIs: {}".format(traceback.format_exc())

return status, message, kpis

Expand All @@ -541,7 +533,7 @@ def set_forecast_parameters(self,horizon,interval):
'''
status = 200
message = "Set forecast horizon and interval successful."
message = "Set forecast horizon and interval successfully."
forecast_parameters = dict()
try:
self.horizon = float(horizon)
Expand All @@ -550,7 +542,7 @@ def set_forecast_parameters(self,horizon,interval):
forecast_parameters['interval'] = self.interval
except:
status = 500
message = "Set forecast horizon and interval failed: {}".format(traceback.format_exc())
message = "Failed to set forecast horizon and interval: {}".format(traceback.format_exc())

return status, message, forecast_parameters

Expand All @@ -564,7 +556,7 @@ def get_forecast_parameters(self):
forecast_parameters['interval'] = self.interval
else:
status = 500
message = "Query simulation for forecast parameters failed."
message = "Failed to query the forecast parameters."

return status, message, forecast_parameters

Expand Down Expand Up @@ -594,7 +586,7 @@ def get_forecast(self):
interval=self.interval)
except:
status = 500
message = "Query simulation for forecast failed: {}".format(traceback.format_exc())
message = "Failed to query the test case data forecast: {}".format(traceback.format_exc())
forecast = None

return status, message, forecast
Expand All @@ -618,7 +610,7 @@ def set_scenario(self, scenario):
}
'''
status = 200
message = "Set simulation scenario successful."
message = "Setting simulation scenario successfully."
try:
result = {
'electricity_price': None,
Expand All @@ -644,7 +636,7 @@ def set_scenario(self, scenario):
self.cal.initialize()
except:
status = 500
message = "Set simulation scenario failed: {}".format(traceback.format_exc())
message = "Failed to set the case scenario: {}".format(traceback.format_exc())
result = None

return status, message, result
Expand All @@ -653,12 +645,12 @@ def get_scenario(self):
'''Returns the current case scenario.'''
scenario = None
status = 200
message = "Query simulation for scenario successful."
message = "Querying simulation for scenario successfully."
if self.scenario is not None:
scenario = self.scenario
else:
status = 500
message = "Query simulation for scenario failed."
message = "Failed to query simulation for scenario."

return status, message, scenario

Expand All @@ -676,7 +668,7 @@ def get_name(self):
'''
status = 200
message = "Query simulation for name successful"
message = "Querying the name of the test case successful"
name = {'name': self.name}

return status, message, name
Expand Down Expand Up @@ -713,7 +705,7 @@ def get_version(self):
'''
status = 200
message = "Query simulation for version number successful"
message = "Querying the version number successfully"
return status, message, {'version': self.version}

def _get_var_metadata(self, fmu, var_list, inputs=False):
Expand Down
22 changes: 11 additions & 11 deletions testing/test_testcase1.py
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ def test_min(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
y = requests.post('{0}/advance'.format(self.url), data={"oveAct_activate":1,"oveAct_u":-500000}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={"oveAct_activate":1,"oveAct_u":-500000}).json()
# Check kpis
value = float(y['PHea_y'])
self.assertAlmostEqual(value, 10101.010101010103, places=3)
Expand All @@ -176,7 +176,7 @@ def test_max(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
y = requests.post('{0}/advance'.format(self.url), data={"oveAct_activate":1,"oveAct_u":500000}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={"oveAct_activate":1,"oveAct_u":500000}).json()
# Check kpis
value = float(y['PHea_y'])
self.assertAlmostEqual(value, 10101.010101010103, places=3)
Expand Down Expand Up @@ -205,7 +205,7 @@ def test_extra_step(self):
step = 7*24*3600
requests.put('{0}/step'.format(self.url), data={'step':step})
for i in [0, 1, 2]:
y = requests.post('{0}/advance'.format(self.url), data={}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={}).json()
# Check y[2] indicates no simulation (empty dict)
self.assertDictEqual(y,dict())
# Check results
Expand Down Expand Up @@ -240,7 +240,7 @@ def test_longer_initialize(self):
# Try simulating past a typical test period
step = 5*7*24*3600
requests.put('{0}/step'.format(self.url), data={'step':step})
y = requests.post('{0}/advance'.format(self.url), data={}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={}).json()
# Check results
self.assertEqual(y['time'], start_time+step)

Expand All @@ -254,7 +254,7 @@ def test_return(self):
scenario_time = {'time_period':'test_day'}
scenario_elec = {'electricity_price':'dynamic'}
# Both
res = requests.put('{0}/scenario'.format(self.url), data=scenario_both).json()["payload"]
res = requests.put('{0}/scenario'.format(self.url), data=scenario_both).json()
# Check return is valid for electricity price
self.assertTrue(res['electricity_price'])
# Check return is valid for time period
Expand All @@ -263,7 +263,7 @@ def test_return(self):
ref_filepath = os.path.join(utilities.get_root_path(), 'testing', 'references', self.name, 'initial_values_set_scenario.csv')
self.compare_ref_values_df(df, ref_filepath)
# Time only
res = (requests.put('{0}/scenario'.format(self.url), data=scenario_time).json()["payload"])
res = (requests.put('{0}/scenario'.format(self.url), data=scenario_time).json())
# Check return is valid for electricity price
self.assertTrue(res['electricity_price'] is None)
# Check return is valid for time period
Expand All @@ -272,7 +272,7 @@ def test_return(self):
ref_filepath = os.path.join(utilities.get_root_path(), 'testing', 'references', self.name, 'initial_values_set_scenario.csv')
self.compare_ref_values_df(df, ref_filepath)
# Electricity price only
res = requests.put('{0}/scenario'.format(self.url), data=scenario_elec).json()["payload"]
res = requests.put('{0}/scenario'.format(self.url), data=scenario_elec).json()
# Check return is valid for electricity price
self.assertTrue(res['electricity_price'])
# Check return is valid for time period
Expand All @@ -297,12 +297,12 @@ def test_constant_step(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
step = requests.get('{0}/step'.format(self.url)).json()["payload"]
step = requests.get('{0}/step'.format(self.url)).json()
for i in range(5):
requests.post('{0}/advance'.format(self.url), data={})
time.sleep(2)
# Check kpis
kpi = requests.get('{0}/kpi'.format(self.url)).json()["payload"]
kpi = requests.get('{0}/kpi'.format(self.url)).json()
self.assertAlmostEqual(kpi['time_rat'], 2.0/step, places=2)
requests.put('{0}/step'.format(self.url), data={'step':step})

Expand All @@ -313,14 +313,14 @@ def test_variable_step(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
step = requests.get('{0}/step'.format(self.url)).json()["payload"]
step = requests.get('{0}/step'.format(self.url)).json()
for i in range(5):
if i > 2:
requests.put('{0}/step'.format(self.url), data={'step':2*step})
requests.post('{0}/advance'.format(self.url), data={})
time.sleep(2)
# Check kpis
kpi = requests.get('{0}/kpi'.format(self.url)).json()["payload"]
kpi = requests.get('{0}/kpi'.format(self.url)).json()
self.assertAlmostEqual(kpi['time_rat'], (3*2.0/step+2*2.0/(2*step))/5, places=2)
requests.put('{0}/step'.format(self.url), data={'step':step})

Expand Down
4 changes: 2 additions & 2 deletions testing/test_testcase2.py
Original file line number Diff line number Diff line change
Expand Up @@ -135,7 +135,7 @@ def test_min(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
y = requests.post('{0}/advance'.format(self.url), data={"oveTSetRooHea_activate":1,"oveTSetRooHea_u":273.15}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={"oveTSetRooHea_activate":1,"oveTSetRooHea_u":273.15}).json()
# Check kpis
value = float(y['oveTSetRooHea_u'])
self.assertAlmostEqual(value, 273.15+10, places=3)
Expand All @@ -147,7 +147,7 @@ def test_max(self):

# Run test
requests.put('{0}/initialize'.format(self.url), data={'start_time':0, 'warmup_period':0})
y = requests.post('{0}/advance'.format(self.url), data={"oveTSetRooHea_activate":1,"oveTSetRooHea_u":310.15}).json()["payload"]
y = requests.post('{0}/advance'.format(self.url), data={"oveTSetRooHea_activate":1,"oveTSetRooHea_u":310.15}).json()
# Check kpis
value = float(y['oveTSetRooHea_u'])
self.assertAlmostEqual(value, 273.15+35, places=3)
Expand Down
Loading

0 comments on commit 497c9e9

Please sign in to comment.