Only initialised service model once per request

`_get_current_service` is a function which gets called every time
`current_service` is referenced in a view method or Jinja template.

Because the service model was getting initialised inside this function
it was being reconstructed many times in one request. On the service
settings page, for example, it was getting initialised 43 times, adding
about 200ms to the response time.

This commit moves its initialisation to the point where we’re getting
the data from the API, which only happens once per request.
This commit is contained in:
Chris Hill-Scott
2018-10-26 08:20:00 +01:00
parent f6ff070f80
commit d69e8b50cd
2 changed files with 8 additions and 5 deletions

View File

@@ -99,7 +99,7 @@ platform_stats_api_client = PlatformStatsAPIClient()
# The current service attached to the request stack.
def _get_current_service():
return Service(_lookup_req_object('service'))
return _lookup_req_object('service')
current_service = LocalProxy(_get_current_service)
@@ -465,7 +465,9 @@ def load_service_before_request():
if service_id:
try:
_request_ctx_stack.top.service = service_api_client.get_service(service_id)['data']
_request_ctx_stack.top.service = Service(
service_api_client.get_service(service_id)['data']
)
except HTTPError as exc:
# if service id isn't real, then 404 rather than 500ing later because we expect service to be set
if exc.status_code == 404:

View File

@@ -5,6 +5,7 @@ import pytest
import werkzeug
from app.notify_client import NotifyAdminAPIClient
from app.notify_client.models import Service
from tests import service_json
from tests.conftest import api_user_active, platform_admin_user, set_config
@@ -29,7 +30,7 @@ def test_active_service_can_be_modified(app_, method, user, service):
with app_.test_request_context() as request_context, app_.test_client() as client:
client.login(user)
request_context.service = service
request_context.service = Service(service)
with patch.object(api_client, 'request') as request:
ret = getattr(api_client, method)('url', 'data')
@@ -48,7 +49,7 @@ def test_inactive_service_cannot_be_modified_by_normal_user(app_, api_user_activ
with app_.test_request_context() as request_context, app_.test_client() as client:
client.login(api_user_active)
request_context.service = service_json(active=False)
request_context.service = Service(service_json(active=False))
with patch.object(api_client, 'request') as request:
with pytest.raises(werkzeug.exceptions.Forbidden):
@@ -67,7 +68,7 @@ def test_inactive_service_can_be_modified_by_platform_admin(app_, platform_admin
with app_.test_request_context() as request_context, app_.test_client() as client:
client.login(platform_admin_user)
request_context.service = service_json(active=False)
request_context.service = Service(service_json(active=False))
with patch.object(api_client, 'request') as request:
ret = getattr(api_client, method)('url', 'data')