Skip to content

HTTP Utilities

These helpers simplify working with request metadata and standardized API responses.

Module drf_corekit.http.requests

Utilities for extracting information from incoming requests.

get_current_site_info(request)

Returns site metadata for the current request.

Returns

(site_name: str, site_domain: str, protocol: str)

Behavior

  • Protocol is:
  • http if DEBUG=True
  • https otherwise

Example

name, domain, protocol = get_current_site_info(request)

get_client_ip(request)

Returns the client IP address.

By default this is REMOTE_ADDR. Proxy headers such as X-Forwarded-For are ignored, because any caller can forge them. If your app sits behind a proxy you control, name the header it sets:

DRF_COREKIT = {
    "HTTP": {
        "CLIENT_IP_HEADER": "CF-Connecting-IP",
    }
}

If the header holds a comma separated list (e.g. X-Forwarded-For), the last valid entry is used: it is the one your proxy appended. A missing or invalid header falls back to REMOTE_ADDR.

Rate throttles and request logs use this function, so they follow the same setting.

Warning

Only set CLIENT_IP_HEADER when your proxy always overwrites that header. Otherwise a client can set it and pick its own IP.

Returns

str | None

Example

ip = get_client_ip(request)

get_request_txid(request)

Retrieves request transaction ID if available.

This assumes a middleware has attached request.transaction_id.

Returns

str | None

Example

txid = get_request_txid(request)

extract_sensitive_metadata(metadata=None)

Splits personal data out of a request metadata dict. Removes ip_address and user_agent from metadata in place and returns them as a new dict:

metadata = parse_request_metadata(request)   # ip_address, user_agent, txid
sensitive = extract_sensitive_metadata(metadata)

# metadata  -> {"txid": "tx-..."}
# sensitive -> {"ip_address": "203.0.113.7", "user_agent": "..."}
Event.objects.create(metadata=metadata, **sensitive)

With None, it returns both keys as None.

Module drf_corekit.http.limits

reject_large_body(request, limit=8192)

Refuses a request whose declared body is larger than limit bytes by raising PayloadTooLargeException (HTTP 413, code payload_too_large). Use it at the top of a public endpoint, before touching request.data.

from drf_corekit.http import reject_large_body

class AccessRequestView(APIView):
    permission_classes = [AllowAny]

    def post(self, request):
        reject_large_body(request)                  # 8 KB
        # reject_large_body(request, limit=512 * 1024)
        ...

Warning

Only the Content-Length header is checked. A request without one (for example chunked) is refused too, so do not use this on requests that have no body. Also set DATA_UPLOAD_MAX_MEMORY_SIZE and a proxy limit (client_max_body_size in nginx).

Responses

Standardized API response wrappers.

Module drf_corekit.http.responses

Ensures consistent response structure across all APIs.

wrap_success_response(data=None, status_code=200)

Wraps successful API responses in a consistent envelope.

Response format

{
  "data": "...",
  "errors": null
}

Parameters

  • data : Any serializable payload
  • status_code : HTTP status code (default: 200)

Returns

rest_framework.response.Response

Example

return wrap_success_response({"id": 1, "name": "Abu"})

FileHttpResponse

An HttpResponse subclass for returning file downloads, with the Content-Disposition header set automatically so the browser saves the file under a dated name: <file_name>_<YYYYMMDD>.<file_ext>.

Parameter Type Default Description
file any — File content, forwarded to HttpResponse as the body
file_name str — Base name used to build the Content-Disposition header
file_ext str "pdf" Extension appended to the generated file name
*args Forwarded to HttpResponse
**kwargs Forwarded to HttpResponse
def export_invoice(request, invoice_id):
    pdf_bytes = render_invoice_pdf(invoice_id)
    return FileHttpResponse(pdf_bytes, file_name="invoice", file_ext="pdf")

A request on, say, 3 March 2026 returns a response with:

Content-Disposition: attachment; filename="invoice_20260303.pdf"
Content-Transfer-Encoding: binary

Tip

The date suffix is today's date in the current time zone (timezone.localdate()) at response time, not a field on the file itself, so two downloads of the same file on different days get different filenames. USE_TZ must be on (the Django default).

Note

The name is passed through Django's get_valid_filename: spaces become _ and characters other than letters, digits, -, _ and . are dropped. Q3 report gives Q3_report_20260303.pdf, and a file_name with quotes, ; or line breaks cannot add header parameters or raise BadHeaderError.