Skip to content

Commit

Permalink
Major work to use response builder and mock backend
Browse files Browse the repository at this point in the history
  • Loading branch information
symroe committed Apr 30, 2024
1 parent 54027b2 commit ecd6f19
Show file tree
Hide file tree
Showing 42 changed files with 2,110 additions and 3,964 deletions.
2 changes: 1 addition & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ all: install_requirements makemessages
install_requirements:
pipenv requirements > postcode_lookup/requirements.txt

.PHONY: i18n
.PHONY: i18n_extract
i18n_extract:
pybabel extract -F ./babel.cfg -o /tmp/_messages.pot postcode_lookup/
pybabel update -i /tmp/_messages.pot -d postcode_lookup/locale/
Expand Down
2 changes: 1 addition & 1 deletion Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ sentry-sdk = {extras = ["starlette"], version = "*"}
urllib3 = "<2"
ruff = "*"
typing-extensions = ">=3.7.4"

starlette-babel = "*"

[dev-packages]
uvicorn = "*"
Expand Down
2,319 changes: 3 additions & 2,316 deletions Pipfile.lock

Large diffs are not rendered by default.

4 changes: 4 additions & 0 deletions babel.cfg
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[jinja2: **/templates/**.html]
encoding = utf-8
trimmed = True

[python: **.py]
encoding = utf-8
trimmed = True
1 change: 1 addition & 0 deletions lib/template_generator/generate_base_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,7 @@ def add_local_font_css(soup):
}
</style>
{% endif %}
{% include 'includes/extra_header.html' %}
""",
"html.parser",
),
Expand Down
16 changes: 16 additions & 0 deletions postcode_lookup/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
from mangum import Mangum
from starlette.applications import Starlette
from starlette.middleware import Middleware
from starlette.requests import HTTPConnection
from starlette.routing import Mount, Route
from starlette.staticfiles import StaticFiles
from starlette_babel import LocaleMiddleware, get_translator
from utils import ForwardedForMiddleware, i18nMiddleware

if sentry_dsn := os.environ.get("SENTRY_DSN"):
Expand Down Expand Up @@ -130,11 +132,25 @@
),
]

shared_translator = get_translator() # process global instance
shared_translator.load_from_directories([Path(__file__).parent / "locale"])


def current_language_selector(conn: HTTPConnection) -> str | None:
return conn.scope["current_language"]


app = Starlette(
debug=True,
routes=routes,
middleware=[
Middleware(i18nMiddleware),
Middleware(
LocaleMiddleware,
locales=["en", "cy"],
default_locale="en",
selectors=[current_language_selector],
),
Middleware(ForwardedForMiddleware),
],
)
Expand Down
17 changes: 14 additions & 3 deletions postcode_lookup/dc_api_client.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import re
from abc import ABC, abstractmethod
from copy import deepcopy
from urllib.parse import urljoin

import httpx
from mock_responses import example_responses
from response_builder.v1.builders.base import RootBuilder
from response_builder.v1.models.base import RootModel
from response_builder.v1.sandbox import SANDBOX_BASE_URL, SANDBOX_POSTCODES
from starlette.requests import Request


class InvalidPostcodeException(Exception): ...
Expand Down Expand Up @@ -36,8 +39,9 @@ def valid_postcode(postcode: str):
class BaseAPIClient(ABC):
URL_PREFIX = None

def __init__(self, api_key: str):
def __init__(self, api_key: str, request: Request):
self.api_key = api_key
self.request = request
self.api_version = "v1"
assert self.URL_PREFIX is not None, "URL_PREFIX must be set on backend"

Expand Down Expand Up @@ -113,11 +117,18 @@ def get_uprn(self, uprn: str) -> dict:


class MockAPIBackend(BaseAPIClient):
def get_mock_response(self, postcode):
builder: RootBuilder = example_responses[postcode]["response"]
if baseline_date := self.request.query_params.get("baseline_date"):
builder = deepcopy(builder)
builder = builder.set_date_baseline(baseline_date)
return builder.build().dict()

def get_uprn(self, uprn: str) -> dict:
pass
return self.get_mock_response(uprn)

def get_postcode(self, postcode: str) -> dict:
return example_responses[postcode]["response"].build().dict()
return self.get_mock_response(postcode)

POSTCODES = example_responses
URL_PREFIX = "mock"
14 changes: 13 additions & 1 deletion postcode_lookup/endpoints.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import datetime
import functools
import os

Expand Down Expand Up @@ -60,14 +61,16 @@ async def base_postcode_endpoint(
return RedirectResponse(
request.url_for(backend.URL_PREFIX + "_postcode_form_en")
)

if postcode == "FA1LL":
return Response(status_code=400)
if postcode == "FA2LL":
assert False

try:
api_response = backend(
api_key=os.environ.get("API_KEY", "ec-postcode-testing")
api_key=os.environ.get("API_KEY", "ec-postcode-testing"),
request=request,
).get_postcode(postcode)
except InvalidPostcodeException:
return RedirectResponse(
Expand All @@ -89,6 +92,7 @@ async def base_postcode_endpoint(
context["parl_recall_petition"]["signing_end"] = parse(
context["parl_recall_petition"]["signing_end"]
)
context["current_date"] = str(datetime.date.today())
template_sorter = TemplateSorter(context["api_response"])
context["template_sorter"] = template_sorter
template_name = template_sorter.main_template_name
Expand Down Expand Up @@ -177,12 +181,20 @@ async def redirect_root_to_postcode_form(request: Request):
if not request.app.debug:
return Response(status_code=404)

poll_open_date = datetime.date.today()
ballot_stages = {
"Polling day": poll_open_date,
"After SOPNs": poll_open_date + datetime.timedelta(days=20),
"Before SOPNs": poll_open_date + datetime.timedelta(days=35),
}

return get_loader(request).TemplateResponse(
"debug_page.html",
{
"request": request,
"sandbox_postcodes": SANDBOX_POSTCODES,
"mock_postcodes": example_responses,
"ballot_stages": ballot_stages,
},
)

Expand Down
84 changes: 78 additions & 6 deletions postcode_lookup/locale/cy/LC_MESSAGES/messages.po
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,42 @@ msgstr ""
"Content-Transfer-Encoding: 8bit\n"
"Generated-By: Babel 2.11.0\n"

#: postcode_lookup/utils.py:58
msgid "one"
msgstr ""

#: postcode_lookup/utils.py:59
msgid "two"
msgstr ""

#: postcode_lookup/utils.py:60
msgid "three"
msgstr ""

#: postcode_lookup/utils.py:61
msgid "four"
msgstr ""

#: postcode_lookup/utils.py:62
msgid "five"
msgstr ""

#: postcode_lookup/utils.py:63
msgid "six"
msgstr ""

#: postcode_lookup/utils.py:64
msgid "seven"
msgstr ""

#: postcode_lookup/utils.py:65
msgid "eight"
msgstr ""

#: postcode_lookup/utils.py:66
msgid "nine"
msgstr ""

#: postcode_lookup/templates/includes/html_meta.html:12
#: postcode_lookup/templates/includes/html_meta.html:20
#: postcode_lookup/templates/index.html:4
Expand All @@ -26,6 +62,8 @@ msgstr "Gwybodaeth etholiadol"
#, fuzzy
msgid "Upcoming election information"
msgstr "Gwybodaeth etholiad sydd i ddod"
msgid "Enter your postcode"
msgstr "Nodwch eich cod post"

#: postcode_lookup/templates/index.html:30
msgid ""
Expand All @@ -37,6 +75,9 @@ msgstr ""
"ble mae eich gorsaf bleidleisio. Gallwch hefyd ddod o hyd i fanylion cyswllt "
"eich cyngor lleol."

#: postcode_lookup/templates/index.html:35
msgid "Enter a postcode"
msgstr "Nodwch god post"

#: postcode_lookup/templates/index.html:38
msgid "Submit Postcode"
Expand Down Expand Up @@ -80,15 +121,43 @@ msgstr "Mae gennych etholiad sydd ar y gweill"

#: postcode_lookup/templates/result.html:21
#: postcode_lookup/templates/result.html:45
#: postcode_lookup/templates/old_result.html:6
#: postcode_lookup/templates/old_result.html:12
#: postcode_lookup/templates/old_result.html:31
#: postcode_lookup/templates/old_result.html:37
msgid "You have upcoming elections"
msgstr "Mae gennych etholiadau sydd ar y gweill"

#: postcode_lookup/templates/old_result.html:14
#: postcode_lookup/templates/old_result.html:39
#: postcode_lookup/templates/results_multiple_dates.html:7
#: postcode_lookup/templates/results_multiple_dates.html:15
#: postcode_lookup/templates/results_one_current_ballot.html:7
#: postcode_lookup/templates/results_one_current_ballot.html:15
#: postcode_lookup/templates/results_one_current_date.html:7
#: postcode_lookup/templates/results_one_current_date.html:15
msgid "You have an upcoming election"
msgstr "Mae gennych etholiad sydd ar y gweill"

#: postcode_lookup/templates/old_result.html:21
#: postcode_lookup/templates/old_result.html:45
#, fuzzy
msgid "There is a recall petition in your area"
msgstr "Nid oes etholiadau ar y gweill yn eich ardal chi"

#: postcode_lookup/templates/result.html:23
#: postcode_lookup/templates/result.html:47
#: postcode_lookup/templates/old_result.html:23
#: postcode_lookup/templates/old_result.html:47
#: postcode_lookup/templates/results_no_upcoming.html:4
msgid "There are no upcoming elections in your area"
msgstr "Nid oes etholiadau ar y gweill yn eich ardal chi"

#: postcode_lookup/templates/results_no_upcoming.html:8
#, fuzzy
msgid "There are no upcoming elections in your areas"
msgstr "Nid oes etholiadau ar y gweill yn eich ardal chi"

#: postcode_lookup/templates/includes/html_meta.html:9
#, fuzzy
msgid ""
Expand All @@ -109,24 +178,25 @@ msgstr ""
"bleidleisio, ymgeiswyr, a manylion cyswllt eich tîm gwasanaethau "
"etholiadol lleol"

#: postcode_lookup/templates/includes/polling_station.html:3
#: postcode_lookup/templates/includes/polling_station.html:1
msgid "Your polling station"
msgstr "Eich gorsaf bleidleisio"

#: postcode_lookup/templates/includes/polling_station.html:14
#: postcode_lookup/templates/includes/polling_station.html:12
#, fuzzy
msgid ""
"Youll get a poll card in the post before the election. This will tell "
"you where to vote. If you havent got one, contact your local council."
"You'll get a poll card in the post before the election. This will tell "
"you where to vote. If you haven't got one, contact your local council."
msgstr ""
"Fe gewch chi gerdyn pleidleisio yn y post cyn yr etholiad. Bydd hyn yn "
"dweud wrthych ble i bleidleisio. Os nad oes gennych un, cysylltwch â'ch "
"cyngor lleol."

#: postcode_lookup/templates/includes/polling_station.html:17
#: postcode_lookup/templates/includes/polling_station.html:15
msgid "Opening times"
msgstr "Oriau agor"

#: postcode_lookup/templates/includes/polling_station.html:20
#: postcode_lookup/templates/includes/polling_station.html:18
#, python-format
msgid "%(ballot_date)s - 7am to 10pm"
msgstr "%(ballot_date)s - 7am i 10pm"
Expand All @@ -146,3 +216,5 @@ msgstr "%(ballot_date)s - 7am i 10pm"

#~ msgid "Enter a postcode"
#~ msgstr "Nodwch god post"
#~ msgid "%(title)s"
#~ msgstr ""
Loading

0 comments on commit ecd6f19

Please sign in to comment.