import datetime import json import os from pathlib import Path from flask import request, Response, make_response, send_file from flask_restful import Resource 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 from hub_api.helpers.session_helper import refresh_session, session class IdfGenerator(Resource, Config): def __init__(self): self._tmp_path = (Path(__file__).parent / 'tmp').resolve() super().__init__() def post(self): """ API call generate the IDF file for the input data """ 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'] 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) 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