Skip to content

Commit

Permalink
Merge branch 'feature/env_var_urls' into 'master'
Browse files Browse the repository at this point in the history
Env var urls

See merge request caimira/caimira!441
  • Loading branch information
lrdossan committed May 12, 2023
2 parents 8e318eb + c17fffe commit 6b1b626
Show file tree
Hide file tree
Showing 5 changed files with 75 additions and 44 deletions.
2 changes: 2 additions & 0 deletions app-config/calculator-app/app.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 2 additions & 0 deletions app-config/docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
4 changes: 4 additions & 0 deletions app-config/openshift/deploymentconfig.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
75 changes: 41 additions & 34 deletions caimira/apps/calculator/__init__.py
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -17,6 +19,7 @@
import uuid
import zlib


import jinja2
import loky
from tornado.web import Application, RequestHandler, StaticFileHandler
Expand All @@ -35,7 +38,9 @@
# 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):
Expand Down Expand Up @@ -201,20 +206,6 @@ def get(self):
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"]
Expand Down Expand Up @@ -242,20 +233,6 @@ def get(self, compressed_args: str):
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):
Expand Down Expand Up @@ -345,6 +322,25 @@ async def get(self, country):
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('/')

Expand All @@ -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]
Expand All @@ -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),
Expand Down
36 changes: 26 additions & 10 deletions caimira/tests/apps/calculator/test_webapp.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -147,3 +137,29 @@ def test_500(self):
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

0 comments on commit 6b1b626

Please sign in to comment.