Problem statement
In this Django project, implement the request pipeline the reporting app does not have. There is nothing at all between the server and the views, so support cannot say which request broke, operations cannot take the site down for a release while staff click through the new build, and an unhandled error in a view escapes as a raw 500 that tells a caller nothing. Build the layers in app/middleware.py and register them in MIDDLEWARE, where the order they run in is what decides whether each concern can see what it needs.
Requirements
Implement:
- the request-id, logging, maintenance-gate and error-capture layers in app/middleware.py, as one class or as several
- their entries in the MIDDLEWARE list in project/settings.py
The following files are already implemented and provided: app/views.py, app/urls.py and app/probes.py. There is no model and no form in this question. The tests grade what the pipeline does, not how it is split up, and every class you write has to be listed in MIDDLEWARE; the entries already there are the given stack and stay in the order they are in. The routes are given: / (home) prints a banner, /accounts/login/ (login) is Django's own login page, /reports/ (report-index) answers 200 and sets its own X-Report-Version: 2 header, /reports/slow/ (report-slow) answers 200 after spending a known 50ms in the view, /reports/missing/ (report-missing) returns a 404 response of its own with the body report not found and the header X-Report-Id: r-404, /reports/export/ (report-export) is the half-written exporter and raises on every call, /reports/<pk>/ (report-detail) answers 200 for ids 1 and 2 and raises Http404 for anything else, and /status/, /status/deep/ and /statusboard/ (status, deep-status, statusboard) are the two health checks and an ordinary page whose path merely starts like them. Every view appends its own name to app.views.VIEW_CALLS before it answers, so a request stopped in front of a view is told apart from one that reached it. Four settings are given and the tests flip only the first: MAINTENANCE_MODE = False, MAINTENANCE_MESSAGE = "Site is down for maintenance. Please try again shortly.", MAINTENANCE_RETRY_AFTER = 120 and MAINTENANCE_ALLOWED_PATHS = ["/status/", "/accounts/login/"]. app/probes.py holds StampMiddleware, a given stamping layer the tests slide into the stack at a chosen depth to find out how far down a request got; it is not part of your task.
1. The request id
- Every request carries its own id, minted when the request arrives. Its shape is yours - uuid.uuid4().hex, a hex token, your own scheme - and the demands are that it is non-empty, that it is one value everywhere within one request, and that two requests never share one. A value computed once at import time is one trace shared by every visitor for the life of the process.
- It leaves on the response as the header X-Request-Id, on every response the project can produce: a page that worked, a request the gate answered, and a request that failed.
2. One log entry per request
- Exactly one entry per request, on the logger app.requests, at INFO, written once the response exists.
- It carries exactly these five fields: method, path, status, elapsed and request_id. Fields attached with extra={...} land on the record as attributes, and fields written as key=value pairs in the message are parsed back out of it; either shape is read the same way, and separators, order, quoting and the wording around them are not graded.
- method and path come off the request, status is the status the response actually carries, and request_id is that request's id, the same value the response header carries.
- The gated 503 and the converted 500 are logged too, reporting the status the response ended up with.
3. elapsed is a measurement, not a constant
- elapsed is how long the handling below the layer took, as a number, in whatever unit you like, and it is never negative.
- /reports/slow/ sleeps 50ms inside the view and reports at least 0.04, while /reports/ answers at once and reports less than half of that. The two routes are compared against each other rather than against a unit, and no fixed value and no single clock reading can satisfy both halves.
4. The maintenance gate
- While MAINTENANCE_MODE is on, a general request is answered with 503, a body that is exactly MAINTENANCE_MESSAGE and a Retry-After header carrying MAINTENANCE_RETRY_AFTER, returned instead of calling the layers below, so no view runs.
- Two exemptions pass straight through to the real page: a user whose is_staff is true, and any path starting with one of the MAINTENANCE_ALLOWED_PATHS prefixes. Being signed in is not the exemption: a signed-in user who is not staff is gated like an anonymous visitor.
- The entries are prefixes, not exact paths, so /status/ and /status/deep/ pass through and /statusboard/ is gated. /accounts/login/ is listed as shipped, so the login page stays reachable while the site is down.
- With the flag off the gate does nothing at all, for any tier, and Retry-After belongs only to the 503: an exempt or ungated response comes back without it.
- The message, the retry value and the allowed paths are read from django.conf.settings while the request is handled. The tests run the same gate again with those three overridden and require the body, the header value and which paths pass through to follow the new values.
5. The error response
- An unhandled exception raised by a view answers 500 with content type application/json and a body carrying detail of Server error and request_id of that request's id: ``json {"detail": "Server error", "request_id": "8f14e45fceea167a5a36dedd4bea2543"} ``
- The id in the body, the id in the X-Request-Id header and the id in the log entry are all the same value.
- Django wraps every layer in convert_exception_to_response, so a layer's get_response call hands back a 500 response rather than raising, and a try/except around it never catches anything. The hook Django calls for what a view raised is process_exception, and it takes the first response that is not None.
- A view that raises Http404 keeps answering 404, without the server-error body: that exception reaches the same hook and already has the right answer, so it is declined rather than converted.
- A response the view returned keeps its status, its body, its content type and the headers it set, a 404 it returned itself included. X-Request-Id is the only thing the pipeline adds to it.
- Everything below your layers still handles the request: a probe at the bottom of the stack still stamps the response, and the view below it still runs.
6. The order in MIDDLEWARE
- The id layer and the log layer sit above the gate. That is what lets the gate's 503 carry an id and appear in the log at all, because a layer listed below something that answers without calling down never runs for that request.
- The gate sits below django.contrib.auth.middleware.AuthenticationMiddleware, which is what puts request.user there for the staff exemption to read.
- Both are asserted by running the same entries a second time in a different order and requiring that the pipeline then breaks: lifting your entries above AuthenticationMiddleware costs staff their exemption, and moving the entries that sit above the gate down below it costs the 503 its id and its log entry.
Notes
- Only app/middleware.py and the MIDDLEWARE list in project/settings.py change; leave the rest of the settings file alone.
- Do not edit the views, and do not make the exporter stop raising. The error is converted, not removed.
- A message, a retry value or a path prefix written into the middleware as a literal reports the shipped value after the setting has changed.
- request.user.is_staff is a plain boolean and is False for an anonymous visitor, so anonymity never needs a test of its own.
- JsonResponse serialises a dict and sets the JSON content type for you.
- No third-party packages: logging, time, uuid and django.http are all this needs.
