HTTP Shortcuts

Smarter’s html responses, which render an error or information page.

These are wrappers around the Django HttpResponse class, with a custom error_message attribute for the custom templates, and default error messages.

class smarter.lib.django.http.shortcuts.SmarterHttpErrorResponse(request, error_message=None, status_code=200, template_file='200.html', *args, **kwargs)[source]

Bases: SmarterHttpResponse

Base class of the Smarter html error responses, e.g. SmarterHttpResponseBadRequest.

It adds nothing to SmarterHttpResponse; it lets callers tell an error page from a normal one.

class smarter.lib.django.http.shortcuts.SmarterHttpResponse(request, error_message=None, status_code=200, template_file='200.html', *args, **kwargs)[source]

Bases: HttpResponse

A generic HTTP response class for Smarter applications, extending Django’s HttpResponse.

This class is designed to render a specified template with a customizable error message and HTTP status code. It is intended to standardize error handling and response rendering across Smarter Django views.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object associated with the response.

  • error_message (str | None) – An optional custom error message to display in the rendered template. If not provided, a default message is used.

  • status_code (int) – The HTTP status code for the response. Defaults to 200 (OK).

  • template_file (str) – The name of the Django template file to render. Defaults to "200.html".

  • args – Additional positional arguments passed to the parent HttpResponse.

  • kwargs – Additional keyword arguments passed to the parent HttpResponse. The content_type is set to "text/html" by default.

Context:

The template is rendered with a context dictionary containing a single key:

  • message: The error message to display.

Example Usage:

from smarter.lib.django.http.shortcuts import SmarterHttpResponse

def my_view(request):
    # Custom error message and template
    return SmarterHttpResponse(
        request,
        error_message="Custom error occurred.",
        status_code=400,
        template_file="400.html"
    )

Notes:

  • This class is intended for use in Django views where a standardized error or informational response is required.

  • The template_file should exist in your Django templates directory and be designed to display the message context variable.

Warning:

  • If the specified template file does not exist, Django will raise a TemplateDoesNotExist exception.

  • The default error message is generic; always provide a specific message for better user experience.

__init__(request, error_message=None, status_code=200, template_file='200.html', *args, **kwargs)[source]
context: dict[str, Any] = {}
class smarter.lib.django.http.shortcuts.SmarterHttpResponseBadRequest(request, error_message=None, *args, **kwargs)[source]

Bases: SmarterHttpErrorResponse

Specialized HTTP 400 (Bad Request) response for Smarter Django applications.

This class extends SmarterHttpErrorResponse to provide a standardized way to return a “Bad Request” response, rendering the 400.html template with a customizable error message.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object associated with the response.

  • error_message (str | None) – An optional custom error message to display in the rendered template. If not provided, a default message is used: “Dohhhh, that’s a bad request my friend.”

  • args – Additional positional arguments passed to the parent SmarterHttpErrorResponse.

  • kwargs – Additional keyword arguments passed to the parent SmarterHttpErrorResponse.

Context:

The template is rendered with a context dictionary containing:

  • message: The error message to display.

Example Usage:

from smarter.lib.django.http.shortcuts import SmarterHttpResponseBadRequest

def my_view(request):
    if not request.GET.get("important_param"):
        return SmarterHttpResponseBadRequest(
            request,
            error_message="Missing required parameter: important_param"
        )
    # ... rest of the view logic ...

Notes:

  • The 400.html template should exist in your Django templates directory and be designed to display the message context variable.

  • This class is intended for use in views where you want to provide a user-friendly error page for bad requests.

Warning:

  • If the specified template file does not exist, Django will raise a TemplateDoesNotExist exception.

  • Always provide a clear error message to help users understand what went wrong.

__init__(request, error_message=None, *args, **kwargs)[source]
class smarter.lib.django.http.shortcuts.SmarterHttpResponseForbidden(request, error_message=None, *args, **kwargs)[source]

Bases: SmarterHttpErrorResponse

Specialized HTTP 403 (Forbidden) response for Smarter Django applications.

This class extends SmarterHttpErrorResponse to provide a standardized way to return a “Forbidden” response, rendering the 403.html template with a customizable error message.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object associated with the response.

  • error_message (str | None) – An optional custom error message to display in the rendered template. If not provided, a default message is used: “Awe shucks, you’re not allowed to do that.”

  • args – Additional positional arguments passed to the parent SmarterHttpErrorResponse.

  • kwargs – Additional keyword arguments passed to the parent SmarterHttpErrorResponse.

Context:

The template is rendered with a context dictionary containing:

  • message: The error message to display.

Example Usage:

from smarter.lib.django.http.shortcuts import SmarterHttpResponseForbidden

def my_view(request):
    if not request.user.has_perm("myapp.can_access"):
        return SmarterHttpResponseForbidden(
            request,
            error_message="You do not have permission to access this resource."
        )
    # ... rest of the view logic ...

Notes:

  • The 403.html template should exist in your Django templates directory and be designed to display the message context variable.

  • This class is intended for use in views where you want to provide a user-friendly error page for forbidden actions.

Warning:

  • If the specified template file does not exist, Django will raise a TemplateDoesNotExist exception.

  • Always provide a clear error message to help users understand why access was denied.

__init__(request, error_message=None, *args, **kwargs)[source]
class smarter.lib.django.http.shortcuts.SmarterHttpResponseNotFound(request, error_message=None, *args, **kwargs)[source]

Bases: SmarterHttpErrorResponse

Specialized HTTP 404 (Not Found) response for Smarter Django applications.

This class extends SmarterHttpErrorResponse to provide a standardized way to return a “Not Found” response, rendering the 404.html template with a customizable error message.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object associated with the response.

  • error_message (str | None) – An optional custom error message to display in the rendered template. If not provided, a default message is used: “Oh no!!! We couldn’t find that page.”

  • args – Additional positional arguments passed to the parent SmarterHttpErrorResponse.

  • kwargs – Additional keyword arguments passed to the parent SmarterHttpErrorResponse.

Context:

The template is rendered with a context dictionary containing:

  • message: The error message to display.

Example Usage:

from smarter.lib.django.http.shortcuts import SmarterHttpResponseNotFound

def my_view(request):
    obj = get_object_or_404(MyModel, pk=some_id)
    if not obj:
        return SmarterHttpResponseNotFound(
            request,
            error_message="The requested object does not exist."
        )
    # ... rest of the view logic ...

Notes:

  • The 404.html template should exist in your Django templates directory and be designed to display the message context variable.

  • This class is intended for use in views where you want to provide a user-friendly error page for missing resources.

Warning:

  • If the specified template file does not exist, Django will raise a TemplateDoesNotExist exception.

  • Always provide a clear error message to help users understand what could not be found.

__init__(request, error_message=None, *args, **kwargs)[source]
class smarter.lib.django.http.shortcuts.SmarterHttpResponseServerError(request, error_message=None, *args, **kwargs)[source]

Bases: SmarterHttpErrorResponse

Specialized HTTP 500 (Internal Server Error) response for Smarter Django applications.

This class extends SmarterHttpErrorResponse to provide a standardized way to return an “Internal Server Error” response, rendering the 500.html template with a customizable error message.

Parameters:
  • request (HttpRequest) – The Django HttpRequest object associated with the response.

  • error_message (str | None) – An optional custom error message to display in the rendered template. If not provided, a default message is used: “Ugh!!! Something went wrong on our end.”

  • args – Additional positional arguments passed to the parent SmarterHttpErrorResponse.

  • kwargs – Additional keyword arguments passed to the parent SmarterHttpErrorResponse.

Context:

The template is rendered with a context dictionary containing:

  • message: The error message to display.

Example Usage:

from smarter.lib.django.http.shortcuts import SmarterHttpResponseServerError

def my_view(request):
    try:
        # ... some logic that may raise an exception ...
        pass
    except Exception:
        logger.exception("failed")
        return SmarterHttpResponseServerError(
            request,
            error_message="An unexpected error occurred."
        )

Notes:

  • The 500.html template should exist in your Django templates directory and be designed to display the message context variable.

  • This class is intended for use in views where you want to provide a user-friendly error page for server errors.

Warning:

  • If the specified template file does not exist, Django will raise a TemplateDoesNotExist exception.

  • Always provide a clear error message to help users understand that a server error has occurred.

__init__(request, error_message=None, *args, **kwargs)[source]

Error Pages

Every urlconf that a host routes to names these views as its handler400, handler403, handler404 and handler500. They are Django’s own error pages, which also close the database connections of the thread that rendered them.

The error pages of every Smarter urlconf: Django’s own views, which close their database connections.

Under ASGI, Django renders the response to an exception raised by a view or a middleware, e.g. Http404, PermissionDenied or SuspiciousOperation, with sync_to_async(response_for_exception, thread_sensitive=False), in a thread of the event loop’s default executor, outside the request cycle. With DEBUG off, the page renders a template whose context processors query the database, so it opens a connection in that thread, which nothing closes. Chat prompts run in the same executor (smarter.apps.prompt.progress.prompt_event_stream()), so the first prompt to land in the thread hours later reused the idle connection, which MariaDB had closed after its wait_timeout, and failed with (2006, "MySQL server has gone away"). Bots requesting /favicon.ico, /robots.txt or /.env left one such connection in every app process.

Each view here is Django’s default view, from django.views.defaults, followed by smarter.lib.django.connections.close_thread_connections(). Every urlconf that a host routes to (smarter.urls.console, smarter.urls.api and smarter.urls.llmclients) names them as its handler400, handler403, handler404 and handler500.

smarter.lib.django.http.error_handlers.bad_request(request, exception, template_name='400.html')[source]

handler400: Django’s 400 page, django.views.defaults.bad_request().

smarter.lib.django.http.error_handlers.closing_connections(view)[source]

Wrap an error view so that it closes its thread’s database connections when it returns.

The view’s response is rendered by the time it returns, so nothing it does needs the connection afterwards. functools.wraps() keeps the view’s signature, which Django’s system check of custom error handlers reads. The wrapper gets its own docstring, because Django’s error views use the :template: role of django.contrib.admindocs, which crashes Sphinx when autodoc renders it.

Parameters:

view (Callable[..., HttpResponse]) – An error view, e.g. django.views.defaults.page_not_found().

Return type:

Callable[..., HttpResponse]

Returns:

The view, closing the current thread’s connections after it runs.

smarter.lib.django.http.error_handlers.page_not_found(request, exception, template_name='404.html')[source]

handler404: Django’s 404 page, django.views.defaults.page_not_found().

smarter.lib.django.http.error_handlers.permission_denied(request, exception, template_name='403.html')[source]

handler403: Django’s 403 page, django.views.defaults.permission_denied().

smarter.lib.django.http.error_handlers.server_error(request, template_name='500.html')[source]

handler500: Django’s 500 page, django.views.defaults.server_error().