Skip to content

Commit

Permalink
Ensure cache is set every time instead of branching
Browse files Browse the repository at this point in the history
Checking if the cached value exists every time is costly and an
unnecessary branch.
  • Loading branch information
lukasjuhrich committed Oct 16, 2023
1 parent 7ae0ed0 commit 9e7085d
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 8 deletions.
11 changes: 6 additions & 5 deletions sipa/babel.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,10 @@ def iter_preferred_locales(request: Request) -> t.Iterator[str]:
yield from request.accept_languages.values()


def preferred_locales(request: Request) -> list[str]:
pl = g.get("preferred_locales")
if not pl:
pl = g.preferred_locales = list(iter_preferred_locales(request))
def preferred_locales() -> list[str]:
return g.preferred_locales

return pl

def cache_preferred_locales(*a, **extra):
"""Store the preferred locales on the `g` object."""
g.preferred_locales = list(iter_preferred_locales(request))
2 changes: 1 addition & 1 deletion sipa/flatpages.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,7 +155,7 @@ def localized_page(self) -> Page:
:returns: The localized page
"""
negotiated_locale = negotiate_locale(
preferred_locales(request),
preferred_locales(),
self.available_locales,
sep="-",
)
Expand Down
10 changes: 8 additions & 2 deletions sipa/initialization.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,19 @@
from datetime import datetime

import sentry_sdk
from flask import g
from flask import g, request_started
from flask_babel import Babel, get_locale
from werkzeug import Response
from werkzeug.middleware.proxy_fix import ProxyFix
from flask_qrcode import QRcode
from sentry_sdk.integrations.flask import FlaskIntegration

from sipa.babel import possible_locales, save_user_locale_setting, select_locale
from sipa.babel import (
possible_locales,
save_user_locale_setting,
select_locale,
cache_preferred_locales,
)
from sipa.backends import Backends
from sipa.base import IntegerConverter, login_manager
from sipa.blueprints.usersuite import get_attribute_endpoint
Expand Down Expand Up @@ -51,6 +56,7 @@ def init_app(app, **kwargs):
babel = Babel()
babel.init_app(app)
babel.localeselector(select_locale)
request_started.connect(cache_preferred_locales)
app.before_request(save_user_locale_setting)
app.after_request(ensure_csp)
app.session_interface = SeparateLocaleCookieSessionInterface()
Expand Down

0 comments on commit 9e7085d

Please sign in to comment.