CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-django-stubs

Comprehensive type stubs for Django framework enabling static type checking with mypy

Pending
Overview
Eval results
Files

http.mddocs/

HTTP Handling

Django's HTTP handling system provides comprehensive support for processing HTTP requests and generating responses, including request objects, response classes, middleware, and cookie management.

Core Imports

# HTTP request and response classes
from django.http import (
    HttpRequest, HttpResponse, HttpResponseRedirect,
    HttpResponsePermanentRedirect, HttpResponseNotModified,
    HttpResponseBadRequest, HttpResponseNotFound,
    HttpResponseForbidden, HttpResponseNotAllowed,
    HttpResponseGone, HttpResponseServerError,
    JsonResponse, StreamHttpResponse, FileResponse
)

# Query handling
from django.http import QueryDict

# File uploads
from django.core.files.uploadedfile import UploadedFile, TemporaryUploadedFile, InMemoryUploadedFile

# HTTP exceptions
from django.http import Http404, HttpResponseBadRequest

# Cookie handling  
from django.http.cookie import SimpleCookie

# Utilities
from django.utils.datastructures import MultiValueDict

Capabilities

HTTP Request

Request object containing all information about the HTTP request from the client.

class HttpRequest:
    """
    HTTP request object containing client request data.
    
    Attributes:
        method (str): HTTP method (GET, POST, etc.)
        path (str): Request path
        path_info (str): Path info portion of URL
        GET (QueryDict): GET parameters
        POST (QueryDict): POST data
        COOKIES (dict): Request cookies
        FILES (MultiValueDict): Uploaded files
        META (dict): Request metadata and headers
        user: Authenticated user object
        session: Session data
    """
    method: str
    path: str
    path_info: str
    GET: QueryDict
    POST: QueryDict
    COOKIES: dict
    FILES: MultiValueDict
    META: dict
    user: Any
    session: Any
    
    def build_absolute_uri(self, location: str = None) -> str: ...
    def get_full_path(self, force_append_slash: bool = False) -> str: ...
    def get_full_path_info(self, force_append_slash: bool = False) -> str: ...
    def get_host(self) -> str: ...
    def get_port(self) -> str: ...
    def get_raw_uri(self) -> str: ...
    def get_signed_cookie(self, key: str, default=None, salt: str = '', max_age: int = None) -> str: ...
    def is_secure(self) -> bool: ...
    def is_ajax(self) -> bool: ...
    def read(self, size: int = None) -> bytes: ...
    def readline(self, size: int = None) -> bytes: ...
    def readlines(self) -> list: ...
    def xreadlines(self): ...
    def __iter__(self): ...

HTTP Response Classes

Response objects for returning data to the client with various content types and status codes.

class HttpResponseBase:
    """Base HTTP response class."""
    def __init__(self, content_type: str = None, status: int = None, reason: str = None, charset: str = None): ...
    
    def __setitem__(self, header: str, value: str) -> None: ...
    def __delitem__(self, header: str) -> None: ...
    def __getitem__(self, header: str) -> str: ...
    def has_header(self, header: str) -> bool: ...
    def setdefault(self, header: str, value: str) -> str: ...
    def set_cookie(self, key: str, value: str = '', max_age: int = None, expires=None, 
                   path: str = '/', domain: str = None, secure: bool = False, 
                   httponly: bool = False, samesite: str = None) -> None: ...
    def set_signed_cookie(self, key: str, value: str, salt: str = '', **kwargs) -> None: ...
    def delete_cookie(self, key: str, path: str = '/', domain: str = None, samesite: str = None) -> None: ...
    def write(self, content) -> None: ...
    def flush(self) -> None: ...
    def tell(self) -> int: ...
    def readable(self) -> bool: ...
    def seekable(self) -> bool: ...
    def writable(self) -> bool: ...
    def writelines(self, lines) -> None: ...
    
    status_code: int
    reason_phrase: str
    charset: str
    streaming: bool
    closed: bool

class HttpResponse(HttpResponseBase):
    """Standard HTTP response."""
    def __init__(self, content=b'', content_type: str = None, status: int = 200, reason: str = None, charset: str = None): ...
    
    content: bytes

class HttpResponseRedirect(HttpResponse):
    """HTTP redirect response (302)."""
    status_code: int = 302
    def __init__(self, redirect_to: str, *args, **kwargs): ...
    url: str

class HttpResponsePermanentRedirect(HttpResponse):
    """HTTP permanent redirect response (301)."""
    status_code: int = 301
    def __init__(self, redirect_to: str, *args, **kwargs): ...
    url: str

class HttpResponseNotModified(HttpResponse):
    """HTTP not modified response (304)."""
    status_code: int = 304
    def __init__(self, *args, **kwargs): ...

class HttpResponseBadRequest(HttpResponse):
    """HTTP bad request response (400)."""
    status_code: int = 400

class HttpResponseNotFound(HttpResponse):
    """HTTP not found response (404)."""
    status_code: int = 404

class HttpResponseForbidden(HttpResponse):
    """HTTP forbidden response (403)."""
    status_code: int = 403

class HttpResponseNotAllowed(HttpResponse):
    """HTTP method not allowed response (405)."""
    status_code: int = 405
    def __init__(self, permitted_methods: list, *args, **kwargs): ...

class HttpResponseGone(HttpResponse):
    """HTTP gone response (410)."""
    status_code: int = 410

class HttpResponseServerError(HttpResponse):
    """HTTP server error response (500)."""
    status_code: int = 500

Specialized Response Classes

Response classes for specific content types and use cases.

class StreamingHttpResponse(HttpResponseBase):
    """HTTP response for streaming content."""
    def __init__(self, streaming_content=(), content_type: str = 'text/html; charset=utf-8', 
                 status: int = 200, reason: str = None, charset: str = None): ...
    
    streaming_content: Any
    streaming: bool = True

class FileResponse(StreamingHttpResponse):
    """HTTP response for serving files."""
    def __init__(self, open_file, as_attachment: bool = False, filename: str = '', 
                 content_type: str = None, **kwargs): ...
    
    def set_headers(self, open_file) -> None: ...

class JsonResponse(HttpResponse):
    """HTTP response for JSON content."""
    def __init__(self, data, encoder=None, safe: bool = True, json_dumps_params: dict = None, **kwargs): ...

Query Parameters and Data

Classes for handling query parameters and form data.

class QueryDict(MultiValueDict):
    """
    Dictionary for handling query parameters and form data.
    
    Supports multiple values per key and URL encoding/decoding.
    """
    def __init__(self, query_string: str = None, mutable: bool = False, encoding: str = None): ...
    
    def urlencode(self, safe: str = None) -> str: ...
    def copy(self) -> QueryDict: ...
    def __deepcopy__(self, memo: dict): ...
    def __copy__(self): ...
    def pop(self, key: str, default=None): ...
    def popitem(self): ...
    def clear(self) -> None: ...
    def setdefault(self, key: str, default=None): ...
    def update(self, other_dict) -> None: ...

File Uploads

Classes for handling uploaded files and multipart form data.

class MultiValueDict(dict):
    """Dictionary that can store multiple values for each key."""
    def __init__(self, key_to_list_mapping=()): ...
    
    def __getitem__(self, key: str): ...
    def __setitem__(self, key: str, value) -> None: ...
    def __copy__(self): ...
    def __deepcopy__(self, memo: dict): ...
    def get(self, key: str, default=None): ...
    def getlist(self, key: str, default: list = None) -> list: ...
    def setlist(self, key: str, list_: list) -> None: ...
    def setlistdefault(self, key: str, default_list: list = None) -> list: ...
    def appendlist(self, key: str, value) -> None: ...
    def update(self, *args, **kwargs) -> None: ...
    def pop(self, key: str, default=None): ...
    def popitem(self): ...
    def dict(self) -> dict: ...
    def lists(self): ...
    def values(self): ...
    def items(self): ...

class UploadedFile:
    """Uploaded file wrapper."""
    def __init__(self, file=None, name: str = None, content_type: str = None, size: int = None, charset: str = None, content_type_extra: dict = None): ...
    
    def read(self, num_bytes: int = None) -> bytes: ...
    def readline(self, length: int = None) -> bytes: ...
    def readlines(self) -> list: ...
    def chunks(self, chunk_size: int = None): ...
    def multiple_chunks(self, chunk_size: int = None) -> bool: ...
    def __iter__(self): ...
    def open(self, mode: str = 'rb'): ...
    def close(self) -> None: ...
    
    name: str
    size: int
    content_type: str
    content_type_extra: dict
    charset: str

class InMemoryUploadedFile(UploadedFile):
    """Uploaded file stored in memory."""
    def __init__(self, file, field_name: str, name: str, content_type: str, size: int, charset: str, content_type_extra: dict = None): ...

class TemporaryUploadedFile(UploadedFile):
    """Uploaded file stored in temporary file."""
    def __init__(self, name: str, content_type: str, size: int, charset: str, content_type_extra: dict = None): ...
    def temporary_file_path(self) -> str: ...

HTTP Exceptions

Exception classes for HTTP error conditions.

class Http404(Exception):
    """HTTP 404 Not Found exception."""
    pass

class BadHeaderError(ValueError):
    """Invalid HTTP header error."""
    pass

class RawPostDataException(Exception):
    """Exception for accessing raw POST data incorrectly."""
    pass

class UnreadablePostError(OSError):
    """Exception for unreadable POST data."""
    pass

Cookie Handling

Utilities for HTTP cookie management and parsing.

class SimpleCookie(dict):
    """Simple cookie implementation."""
    def __init__(self, input: str = None): ...
    def load(self, rawdata: str) -> None: ...
    def output(self, attrs: list = None, header: str = "Set-Cookie:", sep: str = "\\r\\n") -> str: ...
    def js_output(self, attrs: list = None) -> str: ...
    def value_decode(self, val: str) -> tuple: ...
    def value_encode(self, val) -> tuple: ...

def parse_cookie(cookie: str) -> dict:
    """Parse cookie string into dictionary."""

HTTP Headers and Metadata

Utilities for handling HTTP headers and request metadata.

class HttpHeaders(dict):
    """Case-insensitive HTTP headers dictionary."""
    def __getitem__(self, key: str) -> str: ...
    def __setitem__(self, key: str, value: str) -> None: ...
    def __delitem__(self, key: str) -> None: ...
    def __contains__(self, key: str) -> bool: ...
    def get(self, key: str, default: str = None) -> str: ...
    def keys(self): ...
    def values(self): ...
    def items(self): ...

def parse_header_parameters(header: str) -> tuple:
    """Parse header parameters into main value and parameters dict."""

def quote_etag(etag: str, weak: bool = False) -> str:
    """Quote ETag for HTTP headers."""

def unquote_etag(etag: str) -> tuple:
    """Unquote ETag from HTTP headers."""

def parse_etags(etag_str: str) -> list:
    """Parse multiple ETags from header."""

def quote(s: str, safe: str = '/') -> str:
    """URL quote string."""

def unquote(s: str) -> str:
    """URL unquote string."""

def unquote_plus(s: str) -> str:
    """URL unquote string with plus signs."""

Content Types and Encoding

Utilities for handling content types and character encoding.

def parse_accept_lang_header(lang_string: str) -> list:
    """Parse Accept-Language header."""

def get_content_charset_from_headers(headers: dict) -> str:
    """Extract charset from Content-Type header."""

def is_same_domain(host: str, pattern: str) -> bool:
    """Check if host matches domain pattern."""

def escape_uri_path(path: str) -> str:
    """Escape URI path for safe HTTP transmission."""

def http_date(epoch_seconds: float = None) -> str:
    """Format timestamp as HTTP date string."""

def parse_http_date(date: str) -> float:
    """Parse HTTP date string to timestamp."""

def conditional_content_removal(request: HttpRequest, response: HttpResponse) -> HttpResponse:
    """Remove content for conditional requests."""

Request Processing

Utilities for processing and validating HTTP requests.

def get_token(request: HttpRequest) -> str:
    """Get CSRF token from request."""

def same_origin(url1: str, url2: str) -> bool:
    """Check if two URLs have the same origin."""

def is_safe_url(url: str, allowed_hosts: set = None, require_https: bool = False) -> bool:
    """Check if URL is safe for redirects."""

def urlencode(query: dict, doseq: bool = False, safe: str = '', encoding: str = None, errors: str = None, quote_via=None) -> str:
    """Encode dictionary as URL query string."""

def urlencode_bytes(query: dict, doseq: bool = False) -> bytes:
    """Encode dictionary as URL query bytes."""

Middleware Support

Base classes and utilities for HTTP middleware.

class MiddlewareMixin:
    """Base mixin for middleware classes."""
    def __init__(self, get_response=None): ...
    def __call__(self, request: HttpRequest) -> HttpResponse: ...
    
    def process_request(self, request: HttpRequest): ...
    def process_view(self, request: HttpRequest, view_func, view_args: tuple, view_kwargs: dict): ...
    def process_template_response(self, request: HttpRequest, response): ...
    def process_response(self, request: HttpRequest, response: HttpResponse) -> HttpResponse: ...
    def process_exception(self, request: HttpRequest, exception: Exception): ...

Install with Tessl CLI

npx tessl i tessl/pypi-django-stubs

docs

admin.md

auth.md

contrib.md

database-orm.md

forms.md

http.md

index.md

migrations.md

mypy-plugin.md

signals.md

templates.md

transactions.md

urls.md

views.md

tile.json