api_v1.4/hub_api/energy_plus/idf_generator.py

55 lines
1.9 KiB
Python
Raw Normal View History

2024-06-14 00:09:24 -04:00
import datetime
2024-06-10 00:31:49 -04:00
import json
import os
from pathlib import Path
from flask import request, Response, make_response, send_file
from flask_restful import Resource
2024-06-10 00:31:49 -04:00
from hub.city_model_structure.city import City
from hub.exports.energy_building_exports_factory import EnergyBuildingsExportsFactory
from hub.version import __version__ as version
from hub_api.config import Config
2024-06-10 00:31:49 -04:00
from hub_api.helpers.session_helper import refresh_session, session
class IdfGenerator(Resource, Config):
def __init__(self):
2024-06-10 00:31:49 -04:00
self._tmp_path = (Path(__file__).parent / 'tmp').resolve()
super().__init__()
def post(self):
"""
API call generate the IDF file for the input data
"""
2024-06-10 00:31:49 -04:00
session_id = request.headers.get('session-id', None)
token = request.headers.get('token', None)
application_uuid = request.headers.get('application-uuid', None)
_session = refresh_session(session_id, token, application_uuid)
if _session is None:
return Response(json.dumps({'error': 'unauthorized'}), status=403)
else:
token = _session['token']
application_id = session(session_id)['application_id']
user_id = session(session_id)['user_id']
2024-06-14 00:09:24 -04:00
2024-06-10 00:31:49 -04:00
tmp_path = (self._tmp_path / token).resolve()
try:
os.mkdir(tmp_path)
except FileExistsError:
pass
payload = request.get_json()
for key, value in payload.items():
db_city = self.database.get_city(self.database.building(value, user_id, application_id, key).city_id)
2024-06-14 00:11:57 -04:00
2024-06-10 00:31:49 -04:00
if version != db_city.hub_release:
return Response(json.dumps({
'error': 'The selected building belongs to an old hub release and cannot be loaded.'
}), status=422)
idf_file = tmp_path/db_city.name
city = City.load_compressed(db_city.pickle_path, idf_file)
EnergyBuildingsExportsFactory('idf', city, tmp_path, target_buildings=[value]).export()
response = make_response(send_file(idf_file))
response.headers['token'] = token
return response