prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  MultiValueDictKeyError: 'language'
  Sentry Issue: (https://sentry.calitp.org/organizations/sentry/issues/69523/?referrer=github_integration)
  
  ```
  KeyError: 'language'
    File "django/utils/datastructures.py", line 84, in __getitem__
      list_ = super().__getitem__(key)
  
  MultiValueDictKeyError: 'language'
    File "benefits/core/middleware.py", line 157, in process_view
      new_lang = request.POST["language"]
  ```
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `benefits/core/middleware.py`
  Content:
  ```
  1 """
  2 The core application: middleware definitions for request/response cycle.
  3 """
  4 import logging
  5 
  6 from django.conf import settings
  7 from django.http import HttpResponse
  8 from django.shortcuts import redirect
  9 from django.template.response import TemplateResponse
  10 from django.urls import reverse
  11 from django.utils.decorators import decorator_from_middleware
  12 from django.utils.deprecation import MiddlewareMixin
  13 from django.views import i18n
  14 
  15 from . import analytics, recaptcha, session
  16 
  17 
  18 logger = logging.getLogger(__name__)
  19 
  20 HEALTHCHECK_PATH = "/healthcheck"
  21 ROUTE_INDEX = "core:index"
  22 TEMPLATE_USER_ERROR = "200-user-error.html"
  23 
  24 
  25 def user_error(request):
  26     return TemplateResponse(request, TEMPLATE_USER_ERROR)
  27 
  28 
  29 class AgencySessionRequired(MiddlewareMixin):
  30     """Middleware raises an exception for sessions lacking an agency configuration."""
  31 
  32     def process_request(self, request):
  33         if session.active_agency(request):
  34             logger.debug("Session configured with agency")
  35             return None
  36         else:
  37             logger.debug("Session not configured with agency")
  38             return user_error(request)
  39 
  40 
  41 class EligibleSessionRequired(MiddlewareMixin):
  42     """Middleware raises an exception for sessions lacking confirmed eligibility."""
  43 
  44     def process_request(self, request):
  45         if session.eligible(request):
  46             logger.debug("Session has confirmed eligibility")
  47             return None
  48         else:
  49             logger.debug("Session has no confirmed eligibility")
  50             return user_error(request)
  51 
  52 
  53 class DebugSession(MiddlewareMixin):
  54     """Middleware to configure debug context in the request session."""
  55 
  56     def process_request(self, request):
  57         session.update(request, debug=settings.DEBUG)
  58         return None
  59 
  60 
  61 class Healthcheck:
  62     """Middleware intercepts and accepts /healthcheck requests."""
  63 
  64     def __init__(self, get_response):
  65         self.get_response = get_response
  66 
  67     def __call__(self, request):
  68         if request.path == HEALTHCHECK_PATH:
  69             return HttpResponse("Healthy", content_type="text/plain")
  70         return self.get_response(request)
  71 
  72 
  73 class HealthcheckUserAgents(MiddlewareMixin):
  74     """Middleware to return healthcheck for user agents specified in HEALTHCHECK_USER_AGENTS."""
  75 
  76     def process_request(self, request):
  77         if hasattr(request, "META"):
  78             user_agent = request.META.get("HTTP_USER_AGENT", "")
  79             if user_agent in settings.HEALTHCHECK_USER_AGENTS:
  80                 return HttpResponse("Healthy", content_type="text/plain")
  81 
  82         return self.get_response(request)
  83 
  84 
  85 class VerifierSessionRequired(MiddlewareMixin):
  86     """Middleware raises an exception for sessions lacking an eligibility verifier configuration."""
  87 
  88     def process_request(self, request):
  89         if session.verifier(request):
  90             logger.debug("Session configured with eligibility verifier")
  91             return None
  92         else:
  93             logger.debug("Session not configured with eligibility verifier")
  94             return user_error(request)
  95 
  96 
  97 class ViewedPageEvent(MiddlewareMixin):
  98     """Middleware sends an analytics event for page views."""
  99 
  100     def process_response(self, request, response):
  101         event = analytics.ViewedPageEvent(request)
  102         try:
  103             analytics.send_event(event)
  104         except Exception:
  105             logger.warning(f"Failed to send event: {event}")
  106         finally:
  107             return response
  108 
  109 
  110 pageview_decorator = decorator_from_middleware(ViewedPageEvent)
  111 
  112 
  113 class ChangedLanguageEvent(MiddlewareMixin):
  114     """Middleware hooks into django.views.i18n.set_language to send an analytics event."""
  115 
  116     def process_view(self, request, view_func, view_args, view_kwargs):
  117         if view_func == i18n.set_language:
  118             new_lang = request.POST["language"]
  119             event = analytics.ChangedLanguageEvent(request, new_lang)
  120             analytics.send_event(event)
  121         return None
  122 
  123 
  124 class LoginRequired(MiddlewareMixin):
  125     """Middleware that checks whether a user is logged in."""
  126 
  127     def process_view(self, request, view_func, view_args, view_kwargs):
  128         # only require login if verifier requires it
  129         verifier = session.verifier(request)
  130         if not verifier or not verifier.is_auth_required or session.logged_in(request):
  131             # pass through
  132             return None
  133 
  134         return redirect("oauth:login")
  135 
  136 
  137 class RecaptchaEnabled(MiddlewareMixin):
  138     """Middleware configures the request with required reCAPTCHA settings."""
  139 
  140     def process_request(self, request):
  141         if settings.RECAPTCHA_ENABLED:
  142             request.recaptcha = {
  143                 "data_field": recaptcha.DATA_FIELD,
  144                 "script_api": settings.RECAPTCHA_API_KEY_URL,
  145                 "site_key": settings.RECAPTCHA_SITE_KEY,
  146             }
  147         return None
  148 
  149 
  150 class IndexOrAgencyIndexOrigin(MiddlewareMixin):
  151     """Middleware sets the session.origin to either the core:index or core:agency_index depending on agency config."""
  152 
  153     def process_request(self, request):
  154         if session.active_agency(request):
  155             session.update(request, origin=session.agency(request).index_url)
  156         else:
  157             session.update(request, origin=reverse(ROUTE_INDEX))
  158         return None
  159 
  160 
  161 index_or_agencyindex_origin_decorator = decorator_from_middleware(IndexOrAgencyIndexOrigin)
  162
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/benefits/core/middleware.py b/benefits/core/middleware.py
  --- a/benefits/core/middleware.py
  +++ b/benefits/core/middleware.py
  @@ -115,9 +115,12 @@
   
       def process_view(self, request, view_func, view_args, view_kwargs):
           if view_func == i18n.set_language:
  -            new_lang = request.POST["language"]
  -            event = analytics.ChangedLanguageEvent(request, new_lang)
  -            analytics.send_event(event)
  +            new_lang = request.POST.get("language")
  +            if new_lang:
  +                event = analytics.ChangedLanguageEvent(request, new_lang)
  +                analytics.send_event(event)
  +            else:
  +                logger.warning("i18n.set_language POST without language")
           return None
  
verification_info: {"golden_diff": "diff --git a/benefits/core/middleware.py b/benefits/core/middleware.py\n--- a/benefits/core/middleware.py\n+++ b/benefits/core/middleware.py\n@@ -115,9 +115,12 @@\n \n     def process_view(self, request, view_func, view_args, view_kwargs):\n         if view_func == i18n.set_language:\n-            new_lang = request.POST[\"language\"]\n-            event = analytics.ChangedLanguageEvent(request, new_lang)\n-            analytics.send_event(event)\n+            new_lang = request.POST.get(\"language\")\n+            if new_lang:\n+                event = analytics.ChangedLanguageEvent(request, new_lang)\n+                analytics.send_event(event)\n+            else:\n+                logger.warning(\"i18n.set_language POST without language\")\n         return None\n", "issue": "MultiValueDictKeyError: 'language'\nSentry Issue: (https://sentry.calitp.org/organizations/sentry/issues/69523/?referrer=github_integration)\n\n```\nKeyError: 'language'\n  File \"django/utils/datastructures.py\", line 84, in __getitem__\n    list_ = super().__getitem__(key)\n\nMultiValueDictKeyError: 'language'\n  File \"benefits/core/middleware.py\", line 157, in process_view\n    new_lang = request.POST[\"language\"]\n```\n", "before_files": [{"content": "\"\"\"\nThe core application: middleware definitions for request/response cycle.\n\"\"\"\nimport logging\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import reverse\nfrom django.utils.decorators import decorator_from_middleware\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.views import i18n\n\nfrom . import analytics, recaptcha, session\n\n\nlogger = logging.getLogger(__name__)\n\nHEALTHCHECK_PATH = \"/healthcheck\"\nROUTE_INDEX = \"core:index\"\nTEMPLATE_USER_ERROR = \"200-user-error.html\"\n\n\ndef user_error(request):\n    return TemplateResponse(request, TEMPLATE_USER_ERROR)\n\n\nclass AgencySessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking an agency configuration.\"\"\"\n\n    def process_request(self, request):\n        if session.active_agency(request):\n            logger.debug(\"Session configured with agency\")\n            return None\n        else:\n            logger.debug(\"Session not configured with agency\")\n            return user_error(request)\n\n\nclass EligibleSessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking confirmed eligibility.\"\"\"\n\n    def process_request(self, request):\n        if session.eligible(request):\n            logger.debug(\"Session has confirmed eligibility\")\n            return None\n        else:\n            logger.debug(\"Session has no confirmed eligibility\")\n            return user_error(request)\n\n\nclass DebugSession(MiddlewareMixin):\n    \"\"\"Middleware to configure debug context in the request session.\"\"\"\n\n    def process_request(self, request):\n        session.update(request, debug=settings.DEBUG)\n        return None\n\n\nclass Healthcheck:\n    \"\"\"Middleware intercepts and accepts /healthcheck requests.\"\"\"\n\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        if request.path == HEALTHCHECK_PATH:\n            return HttpResponse(\"Healthy\", content_type=\"text/plain\")\n        return self.get_response(request)\n\n\nclass HealthcheckUserAgents(MiddlewareMixin):\n    \"\"\"Middleware to return healthcheck for user agents specified in HEALTHCHECK_USER_AGENTS.\"\"\"\n\n    def process_request(self, request):\n        if hasattr(request, \"META\"):\n            user_agent = request.META.get(\"HTTP_USER_AGENT\", \"\")\n            if user_agent in settings.HEALTHCHECK_USER_AGENTS:\n                return HttpResponse(\"Healthy\", content_type=\"text/plain\")\n\n        return self.get_response(request)\n\n\nclass VerifierSessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking an eligibility verifier configuration.\"\"\"\n\n    def process_request(self, request):\n        if session.verifier(request):\n            logger.debug(\"Session configured with eligibility verifier\")\n            return None\n        else:\n            logger.debug(\"Session not configured with eligibility verifier\")\n            return user_error(request)\n\n\nclass ViewedPageEvent(MiddlewareMixin):\n    \"\"\"Middleware sends an analytics event for page views.\"\"\"\n\n    def process_response(self, request, response):\n        event = analytics.ViewedPageEvent(request)\n        try:\n            analytics.send_event(event)\n        except Exception:\n            logger.warning(f\"Failed to send event: {event}\")\n        finally:\n            return response\n\n\npageview_decorator = decorator_from_middleware(ViewedPageEvent)\n\n\nclass ChangedLanguageEvent(MiddlewareMixin):\n    \"\"\"Middleware hooks into django.views.i18n.set_language to send an analytics event.\"\"\"\n\n    def process_view(self, request, view_func, view_args, view_kwargs):\n        if view_func == i18n.set_language:\n            new_lang = request.POST[\"language\"]\n            event = analytics.ChangedLanguageEvent(request, new_lang)\n            analytics.send_event(event)\n        return None\n\n\nclass LoginRequired(MiddlewareMixin):\n    \"\"\"Middleware that checks whether a user is logged in.\"\"\"\n\n    def process_view(self, request, view_func, view_args, view_kwargs):\n        # only require login if verifier requires it\n        verifier = session.verifier(request)\n        if not verifier or not verifier.is_auth_required or session.logged_in(request):\n            # pass through\n            return None\n\n        return redirect(\"oauth:login\")\n\n\nclass RecaptchaEnabled(MiddlewareMixin):\n    \"\"\"Middleware configures the request with required reCAPTCHA settings.\"\"\"\n\n    def process_request(self, request):\n        if settings.RECAPTCHA_ENABLED:\n            request.recaptcha = {\n                \"data_field\": recaptcha.DATA_FIELD,\n                \"script_api\": settings.RECAPTCHA_API_KEY_URL,\n                \"site_key\": settings.RECAPTCHA_SITE_KEY,\n            }\n        return None\n\n\nclass IndexOrAgencyIndexOrigin(MiddlewareMixin):\n    \"\"\"Middleware sets the session.origin to either the core:index or core:agency_index depending on agency config.\"\"\"\n\n    def process_request(self, request):\n        if session.active_agency(request):\n            session.update(request, origin=session.agency(request).index_url)\n        else:\n            session.update(request, origin=reverse(ROUTE_INDEX))\n        return None\n\n\nindex_or_agencyindex_origin_decorator = decorator_from_middleware(IndexOrAgencyIndexOrigin)\n", "path": "benefits/core/middleware.py"}], "after_files": [{"content": "\"\"\"\nThe core application: middleware definitions for request/response cycle.\n\"\"\"\nimport logging\n\nfrom django.conf import settings\nfrom django.http import HttpResponse\nfrom django.shortcuts import redirect\nfrom django.template.response import TemplateResponse\nfrom django.urls import reverse\nfrom django.utils.decorators import decorator_from_middleware\nfrom django.utils.deprecation import MiddlewareMixin\nfrom django.views import i18n\n\nfrom . import analytics, recaptcha, session\n\n\nlogger = logging.getLogger(__name__)\n\nHEALTHCHECK_PATH = \"/healthcheck\"\nROUTE_INDEX = \"core:index\"\nTEMPLATE_USER_ERROR = \"200-user-error.html\"\n\n\ndef user_error(request):\n    return TemplateResponse(request, TEMPLATE_USER_ERROR)\n\n\nclass AgencySessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking an agency configuration.\"\"\"\n\n    def process_request(self, request):\n        if session.active_agency(request):\n            logger.debug(\"Session configured with agency\")\n            return None\n        else:\n            logger.debug(\"Session not configured with agency\")\n            return user_error(request)\n\n\nclass EligibleSessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking confirmed eligibility.\"\"\"\n\n    def process_request(self, request):\n        if session.eligible(request):\n            logger.debug(\"Session has confirmed eligibility\")\n            return None\n        else:\n            logger.debug(\"Session has no confirmed eligibility\")\n            return user_error(request)\n\n\nclass DebugSession(MiddlewareMixin):\n    \"\"\"Middleware to configure debug context in the request session.\"\"\"\n\n    def process_request(self, request):\n        session.update(request, debug=settings.DEBUG)\n        return None\n\n\nclass Healthcheck:\n    \"\"\"Middleware intercepts and accepts /healthcheck requests.\"\"\"\n\n    def __init__(self, get_response):\n        self.get_response = get_response\n\n    def __call__(self, request):\n        if request.path == HEALTHCHECK_PATH:\n            return HttpResponse(\"Healthy\", content_type=\"text/plain\")\n        return self.get_response(request)\n\n\nclass HealthcheckUserAgents(MiddlewareMixin):\n    \"\"\"Middleware to return healthcheck for user agents specified in HEALTHCHECK_USER_AGENTS.\"\"\"\n\n    def process_request(self, request):\n        if hasattr(request, \"META\"):\n            user_agent = request.META.get(\"HTTP_USER_AGENT\", \"\")\n            if user_agent in settings.HEALTHCHECK_USER_AGENTS:\n                return HttpResponse(\"Healthy\", content_type=\"text/plain\")\n\n        return self.get_response(request)\n\n\nclass VerifierSessionRequired(MiddlewareMixin):\n    \"\"\"Middleware raises an exception for sessions lacking an eligibility verifier configuration.\"\"\"\n\n    def process_request(self, request):\n        if session.verifier(request):\n            logger.debug(\"Session configured with eligibility verifier\")\n            return None\n        else:\n            logger.debug(\"Session not configured with eligibility verifier\")\n            return user_error(request)\n\n\nclass ViewedPageEvent(MiddlewareMixin):\n    \"\"\"Middleware sends an analytics event for page views.\"\"\"\n\n    def process_response(self, request, response):\n        event = analytics.ViewedPageEvent(request)\n        try:\n            analytics.send_event(event)\n        except Exception:\n            logger.warning(f\"Failed to send event: {event}\")\n        finally:\n            return response\n\n\npageview_decorator = decorator_from_middleware(ViewedPageEvent)\n\n\nclass ChangedLanguageEvent(MiddlewareMixin):\n    \"\"\"Middleware hooks into django.views.i18n.set_language to send an analytics event.\"\"\"\n\n    def process_view(self, request, view_func, view_args, view_kwargs):\n        if view_func == i18n.set_language:\n            new_lang = request.POST.get(\"language\")\n            if new_lang:\n                event = analytics.ChangedLanguageEvent(request, new_lang)\n                analytics.send_event(event)\n            else:\n                logger.warning(\"i18n.set_language POST without language\")\n        return None\n\n\nclass LoginRequired(MiddlewareMixin):\n    \"\"\"Middleware that checks whether a user is logged in.\"\"\"\n\n    def process_view(self, request, view_func, view_args, view_kwargs):\n        # only require login if verifier requires it\n        verifier = session.verifier(request)\n        if not verifier or not verifier.is_auth_required or session.logged_in(request):\n            # pass through\n            return None\n\n        return redirect(\"oauth:login\")\n\n\nclass RecaptchaEnabled(MiddlewareMixin):\n    \"\"\"Middleware configures the request with required reCAPTCHA settings.\"\"\"\n\n    def process_request(self, request):\n        if settings.RECAPTCHA_ENABLED:\n            request.recaptcha = {\n                \"data_field\": recaptcha.DATA_FIELD,\n                \"script_api\": settings.RECAPTCHA_API_KEY_URL,\n                \"site_key\": settings.RECAPTCHA_SITE_KEY,\n            }\n        return None\n\n\nclass IndexOrAgencyIndexOrigin(MiddlewareMixin):\n    \"\"\"Middleware sets the session.origin to either the core:index or core:agency_index depending on agency config.\"\"\"\n\n    def process_request(self, request):\n        if session.active_agency(request):\n            session.update(request, origin=session.agency(request).index_url)\n        else:\n            session.update(request, origin=reverse(ROUTE_INDEX))\n        return None\n\n\nindex_or_agencyindex_origin_decorator = decorator_from_middleware(IndexOrAgencyIndexOrigin)\n", "path": "benefits/core/middleware.py"}]}