Utils - URI
smarter.common.utils.uri
Helpers for building absolute URIs from Django or DRF request objects.
This module provides the smarter_build_absolute_uri function, which attempts to construct
an absolute URI from a given request object. It supports Django’s HttpRequest, Django REST Framework’s
Request, and mock objects for testing. The function is robust to missing or malformed request data and
returns a fallback test URL if the request cannot be resolved.
Example usage:
from smarter.common.utils import smarter_build_absolute_uri
from django.http import HttpRequest
request = HttpRequest()
request.META['HTTP_HOST'] = 'localhost:9357'
request.path = '/api/v1/resource/'
url = smarter_build_absolute_uri(request)
print(url) # Output: http://localhost:9357/api/v1/resource/
- smarter.common.utils.uri.smarter_build_absolute_uri(request)[source]
Attempts to construct the absolute URI for a given request object.
- Parameters:
request (
HttpRequest) – The request object, which may be an instance ofdjango.http.HttpRequest,rest_framework.request.Request,django.core.handlers.wsgi.ASGIRequest, or a mock object for testing.- Returns:
The absolute URI as a string, or a fallback test URL if the request is invalid or cannot be resolved.
- Return type:
Note
If the request is a Django REST Framework
Request, it is recast to a DjangoHttpRequest.If the request is a mock object (e.g., from unit tests), a synthetic test URL is returned.
The function first tries to use Django’s
build_absolute_urimethod. If unavailable, it attempts to build the URL from scheme, host, and path attributes.If all attempts fail, a generic fallback URL is returned.
Warning
If the request is
Noneor cannot be resolved, the function logs a warning and returns a fallback test URL. Always validate the returned URL before using it in production.Example usage:
from smarter.common.utils import smarter_build_absolute_uri from django.http import HttpRequest request = HttpRequest() request.META['HTTP_HOST'] = 'localhost:9357' request.path = '/api/v1/resource/' url = smarter_build_absolute_uri(request) print(url) # Output: http://localhost:9357/api/v1/resource/ # Example with DRF Request from rest_framework.request import Request drf_request = Request(...) url = smarter_build_absolute_uri(drf_request) print(url) # Example with None url = smarter_build_absolute_uri(None) print(url) # Output: http://testserver/unknown/