diff --git a/app-config/calculator-app/app.sh b/app-config/calculator-app/app.sh index 8555379e..6a808f8c 100755 --- a/app-config/calculator-app/app.sh +++ b/app-config/calculator-app/app.sh @@ -21,6 +21,8 @@ if [[ "$APP_NAME" == "calculator-app" ]]; then export "ARVE_CLIENT_ID"="$ARVE_CLIENT_ID" export "ARVE_CLIENT_SECRET"="$ARVE_CLIENT_SECRET" + export "EXTRA_PAGES"="$EXTRA_PAGES" + echo "Starting the caimira webservice with: python -m caimira.apps.calculator ${args[@]}" python -m caimira.apps.calculator "${args[@]}" elif [[ "$APP_NAME" == "caimira-voila" ]]; then diff --git a/app-config/docker-compose.yml b/app-config/docker-compose.yml index d9ddb34a..a8a0782e 100644 --- a/app-config/docker-compose.yml +++ b/app-config/docker-compose.yml @@ -20,6 +20,7 @@ services: - APPLICATION_ROOT=/ - CAIMIRA_CALCULATOR_PREFIX=/calculator-cern - CAIMIRA_THEME=caimira/apps/templates/cern + - EXTRA_PAGES=[{"url_path":"/about","filename":"about.html.j2"},{"url_path":"/calculator-cern/user-guide","filename":"userguide.html.j2"}] user: ${CURRENT_UID} calculator-open-app: @@ -29,6 +30,7 @@ services: - APP_NAME=calculator-app - APPLICATION_ROOT=/ - CAIMIRA_CALCULATOR_PREFIX=/calculator-open + - EXTRA_PAGES=[{"url_path":"/about","filename":"about.html.j2"},{"url_path":"/calculator-open/user-guide","filename":"userguide.html.j2"}] user: ${CURRENT_UID} auth-service: diff --git a/app-config/openshift/deploymentconfig.yaml b/app-config/openshift/deploymentconfig.yaml index e96d65a1..cda24258 100644 --- a/app-config/openshift/deploymentconfig.yaml +++ b/app-config/openshift/deploymentconfig.yaml @@ -283,6 +283,8 @@ secretKeyRef: key: ARVE_API_KEY name: arve-api + - name: EXTRA_PAGES + value: '[{"url_path":"/about","filename":"about.html.j2"},{"url_path":"/calculator-cern/user-guide","filename":"userguide.html.j2"}]' image: '${PROJECT_NAME}/calculator-app' ports: - containerPort: 8080 @@ -360,6 +362,8 @@ value: / - name: CAIMIRA_CALCULATOR_PREFIX value: /calculator-open + - name: EXTRA_PAGES + value: '[{"url_path":"/about","filename":"about.html.j2"},{"url_path":"/calculator-open/user-guide","filename":"userguide.html.j2"}]' image: '${PROJECT_NAME}/calculator-app' ports: - containerPort: 8080 diff --git a/caimira/apps/calculator/__init__.py b/caimira/apps/calculator/__init__.py index fef9ceaf..5f4ef9bd 100644 --- a/caimira/apps/calculator/__init__.py +++ b/caimira/apps/calculator/__init__.py @@ -1,6 +1,8 @@ # This module is part of CAiMIRA. Please see the repository at # https://gitlab.cern.ch/caimira/caimira for details of the license and terms of use. +import ast +import logging import asyncio import concurrent.futures import datetime @@ -17,6 +19,7 @@ import typing import uuid import zlib + import jinja2 import loky from tornado.web import Application, RequestHandler, StaticFileHandler @@ -35,7 +38,9 @@ from .user import AuthenticatedUser, AnonymousUser # calculator version. If the calculator needs to make breaking changes (e.g. change # form attributes) then it can also increase its MAJOR version without needing to # increase the overall CAiMIRA version (found at ``caimira.__version__``). -__version__ = "4.9" +__version__ = "4.10" + +LOG = logging.getLogger(__name__) class BaseRequestHandler(RequestHandler): @@ -201,20 +206,6 @@ class LandingPage(BaseRequestHandler): self.finish(report) -class AboutPage(BaseRequestHandler): - def get(self): - template_environment = self.settings["template_environment"] - template = template_environment.get_template("about.html.j2") - report = template.render( - user=self.current_user, - get_url = template.globals['get_url'], - get_calculator_url = template.globals["get_calculator_url"], - active_page="about", - text_blocks=template_environment.globals["common_text"] - ) - self.finish(report) - - class CalculatorForm(BaseRequestHandler): def get(self): template_environment = self.settings["template_environment"] @@ -242,20 +233,6 @@ class CompressedCalculatorFormInputs(BaseRequestHandler): return self.finish("Invalid calculator data: it seems incomplete. Was there an error copying & pasting the URL?") template_environment = self.settings["template_environment"] self.redirect(f'{template_environment.globals["get_calculator_url"]()}?{args}') - - -class ReadmeHandler(BaseRequestHandler): - def get(self): - template_environment = self.settings["template_environment"] - template = template_environment.get_template("userguide.html.j2") - readme = template.render( - active_page="calculator/user-guide", - user=self.current_user, - get_url = template.globals['get_url'], - get_calculator_url = template.globals["get_calculator_url"], - text_blocks=template_environment.globals["common_text"], - ) - self.finish(readme) class ArveData(BaseRequestHandler): @@ -345,6 +322,25 @@ class CasesData(BaseRequestHandler): return self.finish(str(round(cases.loc[eight_days_ago:current_date]['New_cases'].mean()))) +class GenericExtraPage(BaseRequestHandler): + + def initialize(self, active_page: str, filename: str): + self.active_page = active_page + # The endpoint that will be used as template name + self.filename = filename + + def get(self): + template_environment = self.settings["template_environment"] + template = template_environment.get_template(self.filename) + self.finish(template.render( + user=self.current_user, + get_url = template.globals['get_url'], + get_calculator_url = template.globals["get_calculator_url"], + active_page=self.active_page, + text_blocks=template_environment.globals["common_text"] + )) + + def get_url(app_root: str, relative_path: str = '/'): return app_root.rstrip('/') + relative_path.rstrip('/') @@ -363,21 +359,34 @@ def make_app( get_root_url = functools.partial(get_url, APPLICATION_ROOT) get_root_calculator_url = functools.partial(get_calculator_url, APPLICATION_ROOT, calculator_prefix) - urls: typing.Any = [ + urls: typing.List = [ (get_root_url(r'/?'), LandingPage), (get_root_url(r'/_c/(.*)'), CompressedCalculatorFormInputs), - (get_root_url(r'/about'), AboutPage), (get_root_url(r'/static/(.*)'), StaticFileHandler, {'path': static_dir}), (get_root_calculator_url(r'/?'), CalculatorForm), (get_root_calculator_url(r'/report'), ConcentrationModel), (get_root_calculator_url(r'/report-json'), ConcentrationModelJsonResponse), (get_root_calculator_url(r'/baseline-model/result'), StaticModel), - (get_root_calculator_url(r'/user-guide'), ReadmeHandler), (get_root_calculator_url(r'/api/arve/v1/(.*)/(.*)'), ArveData), (get_root_calculator_url(r'/cases/(.*)'), CasesData), (get_root_calculator_url(r'/static/(.*)'), StaticFileHandler, {'path': calculator_static_dir}), ] + # Any extra generic page must be declared in the env. variable "EXTRA_PAGES" + extra_pages: typing.Union[str, typing.List] = os.environ.get('EXTRA_PAGES', []) + pages: typing.List = [] + try: + pages = ast.literal_eval(extra_pages) # type: ignore + except (SyntaxError, ValueError): + LOG.warning('Warning: There was a problem with the extra pages. Is the "EXTRA_PAGES" environment variable correctly defined?') + pass + + for extra in pages: + urls.append((get_root_url(r'%s' % extra['url_path']), + GenericExtraPage, { + 'active_page': extra['url_path'].strip('/'), + 'filename': extra['filename'], })) + caimira_templates = Path(__file__).parent.parent / "templates" calculator_templates = Path(__file__).parent / "templates" templates_directories = [caimira_templates, calculator_templates] @@ -401,8 +410,6 @@ def make_app( return Application( urls, debug=debug, - # calculator_prefix=calculator_prefix, - # APPLICATION_ROOT=APPLICATION_ROOT, template_environment=template_environment, default_handler_class=Missing404Handler, report_generator=ReportGenerator(loader, get_root_url, get_root_calculator_url), diff --git a/caimira/tests/apps/calculator/test_webapp.py b/caimira/tests/apps/calculator/test_webapp.py index 6dc7d692..32d22352 100644 --- a/caimira/tests/apps/calculator/test_webapp.py +++ b/caimira/tests/apps/calculator/test_webapp.py @@ -29,16 +29,6 @@ async def test_calculator_form(http_server_client): assert response.code == 200 -async def test_user_guide(http_server_client): - resp = await http_server_client.fetch('/calculator/user-guide') - assert resp.code == 200 - - -async def test_about(http_server_client): - resp = await http_server_client.fetch('/about') - assert resp.code == 200 - - async def test_404(http_server_client): resp = await http_server_client.fetch('/doesnt-exist', raise_error=False) assert resp.code == 404 @@ -147,3 +137,29 @@ class TestError500(tornado.testing.AsyncHTTPTestCase): response = self.fetch('/') assert response.code == 500 assert 'Unfortunately an error occurred when processing your request' in response.body.decode() + + +class TestCERNGenericPage(tornado.testing.AsyncHTTPTestCase): + def get_app(self): + cern_theme = Path(caimira.apps.calculator.__file__).parent.parent / 'themes' / 'cern' + app = caimira.apps.calculator.make_app(theme_dir=cern_theme) + pages = [ + (r'/calculator/user-guide', caimira.apps.calculator.GenericExtraPage, {'active_page': 'calculator/user-guide', 'filename': 'userguide.html.j2'}), + (r'/about', caimira.apps.calculator.GenericExtraPage, {'active_page': 'about', 'filename': 'about.html.j2'}), + ] + + return tornado.web.Application(pages, **app.settings) + + @tornado.testing.gen_test(timeout=_TIMEOUT) + def test_user_guide(self): + response = yield self.http_client.fetch(self.get_url('/calculator/user-guide')) + self.assertEqual(response.code, 200) + + @tornado.testing.gen_test(timeout=_TIMEOUT) + def test_about(self): + response = yield self.http_client.fetch(self.get_url('/about')) + self.assertEqual(response.code, 200) + + def test_calculator_404(self): + response = self.fetch('/calculator') + assert response.code == 404