Skip to content

Commit

Permalink
14: Move the types OmotesRestApp to its own file.
Browse files Browse the repository at this point in the history
  • Loading branch information
lfse-slafleur committed Apr 22, 2024
1 parent c0951b0 commit 6fd83b8
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 38 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,3 +22,5 @@ build/

venv/
.venv/
.coverage
test-results.xml
26 changes: 9 additions & 17 deletions src/omotes_rest/apis/job.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
import base64
import logging
import uuid
from typing import cast

from flask import current_app as flask_app, Flask, Response

from flask import Response
from flask_smorest import Blueprint
from flask.views import MethodView

from omotes_rest import RestInterface
from omotes_rest.apis.api_dataclasses import (
JobInput,
JobResponse,
Expand All @@ -17,9 +17,9 @@
JobDeleteResponse,
JobCancelResponse,
)
import logging

from omotes_rest.db_models.job_rest import JobRest
from omotes_rest.typed_app import current_app


logger = logging.getLogger("omotes_rest")

Expand All @@ -31,15 +31,6 @@
)


class OmotesRestApp(Flask):
"""Type-complete description with extensions of the Flask app."""

rest_if: RestInterface


current_app = cast(OmotesRestApp, flask_app)


@api.route("/")
class JobAPI(MethodView):
"""Requests."""
Expand Down Expand Up @@ -80,8 +71,9 @@ class JobCancelAPI(MethodView):
def get(self, job_id: str) -> JobCancelResponse:
"""Cancel job if queued or running."""
job_uuid = uuid.UUID(job_id)
return JobCancelResponse(job_id=job_uuid,
cancelled=current_app.rest_if.cancel_job(job_uuid))
return JobCancelResponse(
job_id=job_uuid, cancelled=current_app.rest_if.cancel_job(job_uuid)
)


@api.route("/<string:job_id>/status")
Expand All @@ -98,7 +90,7 @@ def get(self, job_id: str) -> JobStatusResponse | Response:
if status:
result = JobStatusResponse(job_id=job_uuid, status=status)
else:
result = Response(status=404, response=f'Unknown job {job_id}.')
result = Response(status=404, response=f"Unknown job {job_id}.")

Check warning

Code scanning / CodeQL

Reflected server-side cross-site scripting Medium

Cross-site scripting vulnerability due to a
user-provided value
.
return result


Expand Down
40 changes: 19 additions & 21 deletions src/omotes_rest/main.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,26 @@
import json
import logging
from os import PathLike
from time import strftime
from typing import cast

from flask import request, send_from_directory, current_app as flask_app, Response as FlaskResponse
from flask import request, send_from_directory, Response as FlaskResponse
from werkzeug.exceptions import HTTPException
from werkzeug.wrappers.response import Response as WerkzeugResponse
from gunicorn.arbiter import Arbiter
from gunicorn.workers.sync import SyncWorker
from omotes_sdk.workflow_type import WorkflowTypeManager, WorkflowType

from omotes_rest import create_app
from omotes_rest.apis.job import OmotesRestApp
from omotes_rest.rest_interface import RestInterface
from omotes_rest.settings import EnvSettings
import logging
from omotes_sdk.workflow_type import WorkflowTypeManager, WorkflowType
from omotes_rest.typed_app import current_app

"""logger."""
logger = logging.getLogger("omotes_rest")

"""Flask application."""
app = create_app("omotes_rest.settings.%sConfig" % EnvSettings.env().capitalize())

current_app = cast(OmotesRestApp, flask_app)


@app.before_request
def before_request() -> None:
Expand All @@ -33,7 +30,8 @@ def before_request() -> None:
logger.debug(
f"Request, timestamp '{timestamp}', remote_addr '{request.remote_addr}',"
f" method '{request.method}', scheme '{request.scheme}', full_path '{request.full_path},"
f" 'payload '{request.get_data()!r}', 'headers '{request.headers}'")
f" 'payload '{request.get_data()!r}', 'headers '{request.headers}'"
)
# return response


Expand All @@ -44,7 +42,8 @@ def after_request(response: FlaskResponse) -> FlaskResponse:
logger.debug(
f"Request, timestamp '{timestamp}', remote_addr '{request.remote_addr}',"
f" method '{request.method}', scheme '{request.scheme}', full_path '{request.full_path},"
f" 'response '{response.status}'")
f" 'response '{response.status}'"
)
return response


Expand All @@ -66,31 +65,30 @@ def handle_exception(e: HTTPException) -> WerkzeugResponse:
}
)
response.content_type = "application/json"
return WerkzeugResponse(response=data,
status=response.status_code,
headers=response.headers, mimetype=response.mimetype,
content_type=response.content_type)
return WerkzeugResponse(
response=data,
status=response.status_code,
headers=response.headers,
mimetype=response.mimetype,
content_type=response.content_type,
)


@app.errorhandler(Exception)
def handle_500(e: Exception) -> tuple[str, int]:
"""Handle exceptions."""
logger.exception(f"Unhandled exception occurred {str(e)}")
return json.dumps({
"message": "Internal Server Error"
}), 500
return json.dumps({"message": "Internal Server Error"}), 500


# TODO to be retrieved via de omotes_sdk in the future
workflow_type_manager = WorkflowTypeManager(
possible_workflows=[
WorkflowType(
workflow_type_name="grow_optimizer",
workflow_type_description_name="Grow Optimizer"
workflow_type_name="grow_optimizer", workflow_type_description_name="Grow Optimizer"
),
WorkflowType(
workflow_type_name="grow_simulator",
workflow_type_description_name="Grow Simulator"
workflow_type_name="grow_simulator", workflow_type_description_name="Grow Simulator"
),
WorkflowType(
workflow_type_name="grow_optimizer_no_heat_losses",
Expand All @@ -99,7 +97,7 @@ def handle_500(e: Exception) -> tuple[str, int]:
WorkflowType(
workflow_type_name="grow_optimizer_no_heat_losses_discounted_capex",
workflow_type_description_name="Grow Optimizer without heat losses and a "
"discounted CAPEX",
"discounted CAPEX",
),
WorkflowType(
workflow_type_name="simulator",
Expand Down
14 changes: 14 additions & 0 deletions src/omotes_rest/typed_app.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from typing import cast

from flask import current_app as flask_app, Flask

from omotes_rest import RestInterface


class OmotesRestApp(Flask):
"""Type-complete description with extensions of the Flask app."""

rest_if: RestInterface


current_app = cast(OmotesRestApp, flask_app)

0 comments on commit 6fd83b8

Please sign in to comment.