repo
stringlengths
7
90
file_url
stringlengths
81
315
file_path
stringlengths
4
228
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 14:38:15
2026-01-05 02:33:18
truncated
bool
2 classes
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/response.py
django/template/response.py
from django.http import HttpResponse from .loader import get_template, select_template class ContentNotRenderedError(Exception): pass class SimpleTemplateResponse(HttpResponse): rendering_attrs = ["template_name", "context_data", "_post_render_callbacks"] def __init__( self, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None, ): # It would seem obvious to call these next two members 'template' and # 'context', but those names are reserved as part of the test Client # API. To avoid the name collision, we use different names. self.template_name = template self.context_data = context self.using = using self._post_render_callbacks = [] # _request stores the current request object in subclasses that know # about requests, like TemplateResponse. It's defined in the base class # to minimize code duplication. # It's called self._request because self.request gets overwritten by # django.test.client.Client. Unlike template_name and context_data, # _request should not be considered part of the public API. self._request = None # content argument doesn't make sense here because it will be replaced # with rendered template so we always pass empty string in order to # prevent errors and provide shorter signature. super().__init__("", content_type, status, charset=charset, headers=headers) # _is_rendered tracks whether the template and context has been baked # into a final response. # Super __init__ doesn't know any better than to set self.content to # the empty string we just gave it, which wrongly sets _is_rendered # True, so we initialize it to False after the call to super __init__. self._is_rendered = False def __getstate__(self): """ Raise an exception if trying to pickle an unrendered response. Pickle only rendered data, not the data used to construct the response. """ obj_dict = self.__dict__.copy() if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be pickled." ) for attr in self.rendering_attrs: if attr in obj_dict: del obj_dict[attr] return obj_dict def resolve_template(self, template): """Accept a template object, path-to-template, or list of paths.""" if isinstance(template, (list, tuple)): return select_template(template, using=self.using) elif isinstance(template, str): return get_template(template, using=self.using) else: return template def resolve_context(self, context): return context @property def rendered_content(self): """Return the freshly rendered content for the template and context described by the TemplateResponse. This *does not* set the final content of the response. To set the response content, you must either call render(), or set the content explicitly using the value of this property. """ template = self.resolve_template(self.template_name) context = self.resolve_context(self.context_data) return template.render(context, self._request) def add_post_render_callback(self, callback): """Add a new post-rendering callback. If the response has already been rendered, invoke the callback immediately. """ if self._is_rendered: callback(self) else: self._post_render_callbacks.append(callback) def render(self): """Render (thereby finalizing) the content of the response. If the content has already been rendered, this is a no-op. Return the baked response instance. """ retval = self if not self._is_rendered: self.content = self.rendered_content for post_callback in self._post_render_callbacks: newretval = post_callback(retval) if newretval is not None: retval = newretval return retval @property def is_rendered(self): return self._is_rendered def __iter__(self): if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be iterated over." ) return super().__iter__() @property def content(self): if not self._is_rendered: raise ContentNotRenderedError( "The response content must be rendered before it can be accessed." ) return super().content @content.setter def content(self, value): """Set the content for the response.""" HttpResponse.content.fset(self, value) self._is_rendered = True class TemplateResponse(SimpleTemplateResponse): rendering_attrs = [*SimpleTemplateResponse.rendering_attrs, "_request"] def __init__( self, request, template, context=None, content_type=None, status=None, charset=None, using=None, headers=None, ): super().__init__( template, context, content_type, status, charset, using, headers=headers ) self._request = request
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/smartif.py
django/template/smartif.py
""" Parser and utilities for the smart 'if' tag """ # Using a simple top down parser, as described here: # https://11l-lang.org/archive/simple-top-down-parsing/ # 'led' = left denotation # 'nud' = null denotation # 'bp' = binding power (left = lbp, right = rbp) class TokenBase: """ Base class for operators and literals, mainly for debugging and for throwing syntax errors. """ id = None # node/token type name value = None # used by literals first = second = None # used by tree nodes def nud(self, parser): # Null denotation - called in prefix context raise parser.error_class( "Not expecting '%s' in this position in if tag." % self.id ) def led(self, left, parser): # Left denotation - called in infix context raise parser.error_class( "Not expecting '%s' as infix operator in if tag." % self.id ) def display(self): """ Return what to display in error messages for this node """ return self.id def __repr__(self): out = [str(x) for x in [self.id, self.first, self.second] if x is not None] return "(" + " ".join(out) + ")" def infix(bp, func): """ Create an infix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def led(self, left, parser): self.first = left self.second = parser.expression(bp) return self def eval(self, context): try: return func(context, self.first, self.second) except Exception: # Templates shouldn't throw exceptions when rendering. We are # most likely to get exceptions for things like: # {% if foo in bar %} # where 'bar' does not support 'in', so default to False. return False return Operator def prefix(bp, func): """ Create a prefix operator, given a binding power and a function that evaluates the node. """ class Operator(TokenBase): lbp = bp def nud(self, parser): self.first = parser.expression(bp) self.second = None return self def eval(self, context): try: return func(context, self.first) except Exception: return False return Operator # Operator precedence follows Python. # We defer variable evaluation to the lambda to ensure that terms are # lazily evaluated using Python's boolean parsing logic. OPERATORS = { "or": infix(6, lambda context, x, y: x.eval(context) or y.eval(context)), "and": infix(7, lambda context, x, y: x.eval(context) and y.eval(context)), "not": prefix(8, lambda context, x: not x.eval(context)), "in": infix(9, lambda context, x, y: x.eval(context) in y.eval(context)), "not in": infix(9, lambda context, x, y: x.eval(context) not in y.eval(context)), "is": infix(10, lambda context, x, y: x.eval(context) is y.eval(context)), "is not": infix(10, lambda context, x, y: x.eval(context) is not y.eval(context)), "==": infix(10, lambda context, x, y: x.eval(context) == y.eval(context)), "!=": infix(10, lambda context, x, y: x.eval(context) != y.eval(context)), ">": infix(10, lambda context, x, y: x.eval(context) > y.eval(context)), ">=": infix(10, lambda context, x, y: x.eval(context) >= y.eval(context)), "<": infix(10, lambda context, x, y: x.eval(context) < y.eval(context)), "<=": infix(10, lambda context, x, y: x.eval(context) <= y.eval(context)), } # Assign 'id' to each: for key, op in OPERATORS.items(): op.id = key class Literal(TokenBase): """ A basic self-resolvable object similar to a Django template variable. """ # IfParser uses Literal in create_var, but TemplateIfParser overrides # create_var so that a proper implementation that actually resolves # variables, filters etc. is used. id = "literal" lbp = 0 def __init__(self, value): self.value = value def display(self): return repr(self.value) def nud(self, parser): return self def eval(self, context): return self.value def __repr__(self): return "(%s %r)" % (self.id, self.value) class EndToken(TokenBase): lbp = 0 def nud(self, parser): raise parser.error_class("Unexpected end of expression in if tag.") EndToken = EndToken() class IfParser: error_class = ValueError def __init__(self, tokens): # Turn 'is','not' and 'not','in' into single tokens. num_tokens = len(tokens) mapped_tokens = [] i = 0 while i < num_tokens: token = tokens[i] if token == "is" and i + 1 < num_tokens and tokens[i + 1] == "not": token = "is not" i += 1 # skip 'not' elif token == "not" and i + 1 < num_tokens and tokens[i + 1] == "in": token = "not in" i += 1 # skip 'in' mapped_tokens.append(self.translate_token(token)) i += 1 self.tokens = mapped_tokens self.pos = 0 self.current_token = self.next_token() def translate_token(self, token): try: op = OPERATORS[token] except (KeyError, TypeError): return self.create_var(token) else: return op() def next_token(self): if self.pos >= len(self.tokens): return EndToken else: retval = self.tokens[self.pos] self.pos += 1 return retval def parse(self): retval = self.expression() # Check that we have exhausted all the tokens if self.current_token is not EndToken: raise self.error_class( "Unused '%s' at end of if expression." % self.current_token.display() ) return retval def expression(self, rbp=0): t = self.current_token self.current_token = self.next_token() left = t.nud(self) while rbp < self.current_token.lbp: t = self.current_token self.current_token = self.next_token() left = t.led(left, self) return left def create_var(self, value): return Literal(value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loader_tags.py
django/template/loader_tags.py
import posixpath from collections import defaultdict from django.utils.safestring import mark_safe from .base import Node, Template, TemplateSyntaxError, TextNode, Variable, token_kwargs from .library import Library register = Library() BLOCK_CONTEXT_KEY = "block_context" class BlockContext: def __init__(self): # Dictionary of FIFO queues. self.blocks = defaultdict(list) def __repr__(self): return f"<{self.__class__.__qualname__}: blocks={self.blocks!r}>" def add_blocks(self, blocks): for name, block in blocks.items(): self.blocks[name].insert(0, block) def pop(self, name): try: return self.blocks[name].pop() except IndexError: return None def push(self, name, block): self.blocks[name].append(block) def get_block(self, name): try: return self.blocks[name][-1] except IndexError: return None class BlockNode(Node): def __init__(self, name, nodelist, parent=None): self.name = name self.nodelist = nodelist self.parent = parent def __repr__(self): return "<Block Node: %s. Contents: %r>" % (self.name, self.nodelist) def render(self, context): block_context = context.render_context.get(BLOCK_CONTEXT_KEY) with context.push(): if block_context is None: context["block"] = self result = self.nodelist.render(context) else: push = block = block_context.pop(self.name) if block is None: block = self # Create new block so we can store context without # thread-safety issues. block = type(self)(block.name, block.nodelist) block.context = context context["block"] = block result = block.nodelist.render(context) if push is not None: block_context.push(self.name, push) return result def super(self): if not hasattr(self, "context"): raise TemplateSyntaxError( "'%s' object has no attribute 'context'. Did you use " "{{ block.super }} in a base template?" % self.__class__.__name__ ) render_context = self.context.render_context if ( BLOCK_CONTEXT_KEY in render_context and render_context[BLOCK_CONTEXT_KEY].get_block(self.name) is not None ): return mark_safe(self.render(self.context)) return "" class ExtendsNode(Node): must_be_first = True context_key = "extends_context" def __init__(self, nodelist, parent_name, template_dirs=None): self.nodelist = nodelist self.parent_name = parent_name self.template_dirs = template_dirs self.blocks = {n.name: n for n in nodelist.get_nodes_by_type(BlockNode)} def __repr__(self): return "<%s: extends %s>" % (self.__class__.__name__, self.parent_name.token) def find_template(self, template_name, context): """ This is a wrapper around engine.find_template(). A history is kept in the render_context attribute between successive extends calls and passed as the skip argument. This enables extends to work recursively without extending the same template twice. """ history = context.render_context.setdefault( self.context_key, [self.origin], ) template, origin = context.template.engine.find_template( template_name, skip=history, ) history.append(origin) return template def get_parent(self, context): parent = self.parent_name.resolve(context) if not parent: error_msg = "Invalid template name in 'extends' tag: %r." % parent if self.parent_name.filters or isinstance(self.parent_name.var, Variable): error_msg += ( " Got this from the '%s' variable." % self.parent_name.token ) raise TemplateSyntaxError(error_msg) if isinstance(parent, Template): # parent is a django.template.Template return parent if isinstance(getattr(parent, "template", None), Template): # parent is a django.template.backends.django.Template return parent.template return self.find_template(parent, context) def render(self, context): compiled_parent = self.get_parent(context) if BLOCK_CONTEXT_KEY not in context.render_context: context.render_context[BLOCK_CONTEXT_KEY] = BlockContext() block_context = context.render_context[BLOCK_CONTEXT_KEY] # Add the block nodes from this node to the block context block_context.add_blocks(self.blocks) # If this block's parent doesn't have an extends node it is the root, # and its block nodes also need to be added to the block context. for node in compiled_parent.nodelist: # The ExtendsNode has to be the first non-text node. if not isinstance(node, TextNode): if not isinstance(node, ExtendsNode): blocks = { n.name: n for n in compiled_parent.nodelist.get_nodes_by_type(BlockNode) } block_context.add_blocks(blocks) break # Call Template._render explicitly so the parser context stays # the same. with context.render_context.push_state(compiled_parent, isolated_context=False): return compiled_parent._render(context) class IncludeNode(Node): context_key = "__include_context" def __init__( self, template, *args, extra_context=None, isolated_context=False, **kwargs ): self.template = template self.extra_context = extra_context or {} self.isolated_context = isolated_context super().__init__(*args, **kwargs) def __repr__(self): return f"<{self.__class__.__qualname__}: template={self.template!r}>" def render(self, context): """ Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop. """ template = self.template.resolve(context) # Does this quack like a Template? if not callable(getattr(template, "render", None)): # If not, try the cache and select_template(). template_name = template or () if isinstance(template_name, str): template_name = ( construct_relative_path( self.origin.template_name, template_name, ), ) else: template_name = tuple(template_name) cache = context.render_context.dicts[0].setdefault(self, {}) template = cache.get(template_name) if template is None: template = context.template.engine.select_template(template_name) cache[template_name] = template # Use the base.Template of a backends.django.Template. elif hasattr(template, "template"): template = template.template values = { name: var.resolve(context) for name, var in self.extra_context.items() } if self.isolated_context: return template.render(context.new(values)) with context.push(**values): return template.render(context) @register.tag("block") def do_block(parser, token): """ Define a block that can be overridden by child templates. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. bits = token.contents.split() if len(bits) != 2: raise TemplateSyntaxError("'%s' tag takes only one argument" % bits[0]) block_name = bits[1] # Keep track of the names of BlockNodes found in this template, so we can # check for duplication. try: if block_name in parser.__loaded_blocks: raise TemplateSyntaxError( "'%s' tag with name '%s' appears more than once" % (bits[0], block_name) ) parser.__loaded_blocks.append(block_name) except AttributeError: # parser.__loaded_blocks isn't a list yet parser.__loaded_blocks = [block_name] nodelist = parser.parse(("endblock",)) # This check is kept for backwards-compatibility. See #3100. endblock = parser.next_token() acceptable_endblocks = ("endblock", "endblock %s" % block_name) if endblock.contents not in acceptable_endblocks: parser.invalid_block_tag(endblock, "endblock", acceptable_endblocks) return BlockNode(block_name, nodelist) def construct_relative_path( current_template_name, relative_name, allow_recursion=False, ): """ Convert a relative path (starting with './' or '../') to the full template name based on the current_template_name. """ new_name = relative_name.strip("'\"") if not new_name.startswith(("./", "../")): # relative_name is a variable or a literal that doesn't contain a # relative path. return relative_name if current_template_name is None: # Unknown origin (e.g. Template('...').render(Context({...})). raise TemplateSyntaxError( f"The relative path {relative_name} cannot be evaluated due to " "an unknown template origin." ) new_name = posixpath.normpath( posixpath.join( posixpath.dirname(current_template_name.lstrip("/")), new_name, ) ) if new_name.startswith("../"): raise TemplateSyntaxError( "The relative path '%s' points outside the file hierarchy that " "template '%s' is in." % (relative_name, current_template_name) ) if not allow_recursion and current_template_name.lstrip("/") == new_name: raise TemplateSyntaxError( "The relative path '%s' was translated to template name '%s', the " "same template in which the tag appears." % (relative_name, current_template_name) ) has_quotes = ( relative_name.startswith(('"', "'")) and relative_name[0] == relative_name[-1] ) return f'"{new_name}"' if has_quotes else new_name @register.tag("extends") def do_extends(parser, token): """ Signal that this template extends a parent template. This tag may be used in two ways: ``{% extends "base" %}`` (with quotes) uses the literal value "base" as the name of the parent template to extend, or ``{% extends variable %}`` uses the value of ``variable`` as either the name of the parent template to extend (if it evaluates to a string) or as the parent template itself (if it evaluates to a Template object). """ bits = token.split_contents() if len(bits) != 2: raise TemplateSyntaxError("'%s' takes one argument" % bits[0]) bits[1] = construct_relative_path(parser.origin.template_name, bits[1]) parent_name = parser.compile_filter(bits[1]) nodelist = parser.parse() if nodelist.get_nodes_by_type(ExtendsNode): raise TemplateSyntaxError( "'%s' cannot appear more than once in the same template" % bits[0] ) return ExtendsNode(nodelist, parent_name) @register.tag("include") def do_include(parser, token): """ Load a template and render it with the current context. You can pass additional context using keyword arguments. Example:: {% include "foo/some_include" %} {% include "foo/some_include" with bar="BAZZ!" baz="BING!" %} Use the ``only`` argument to exclude the current context when rendering the included template:: {% include "foo/some_include" only %} {% include "foo/some_include" with bar="1" only %} """ bits = token.split_contents() if len(bits) < 2: raise TemplateSyntaxError( "%r tag takes at least one argument: the name of the template to " "be included." % bits[0] ) options = {} remaining_bits = bits[2:] while remaining_bits: option = remaining_bits.pop(0) if option in options: raise TemplateSyntaxError( "The %r option was specified more than once." % option ) if option == "with": value = token_kwargs(remaining_bits, parser, support_legacy=False) if not value: raise TemplateSyntaxError( '"with" in %r tag needs at least one keyword argument.' % bits[0] ) elif option == "only": value = True else: raise TemplateSyntaxError( "Unknown argument for %r tag: %r." % (bits[0], option) ) options[option] = value isolated_context = options.get("only", False) namemap = options.get("with", {}) bits[1] = construct_relative_path( parser.origin.template_name, bits[1], allow_recursion=True, ) return IncludeNode( parser.compile_filter(bits[1]), extra_context=namemap, isolated_context=isolated_context, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/exceptions.py
django/template/exceptions.py
""" This module contains generic exceptions used by template backends. Although, due to historical reasons, the Django template language also internally uses these exceptions, other exceptions specific to the DTL should not be added here. """ class TemplateDoesNotExist(Exception): """ The exception used when a template does not exist. Optional arguments: backend The template backend class used when raising this exception. tried A list of sources that were tried when finding the template. This is formatted as a list of tuples containing (origin, status), where origin is an Origin object or duck type and status is a string with the reason the template wasn't found. chain A list of intermediate TemplateDoesNotExist exceptions. This is used to encapsulate multiple exceptions when loading templates from multiple engines. """ def __init__(self, msg, tried=None, backend=None, chain=None): self.backend = backend if tried is None: tried = [] self.tried = tried if chain is None: chain = [] self.chain = chain super().__init__(msg) class TemplateSyntaxError(Exception): """ The exception used for syntax errors during parsing or rendering. """ pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/context_processors.py
django/template/context_processors.py
""" A set of request processors that return dictionaries to be merged into a template context. Each function takes the request object as its only parameter and returns a dictionary to add to the context. These are referenced from the 'context_processors' option of the configuration of a DjangoTemplates backend and used by RequestContext. """ import itertools from django.conf import settings from django.middleware.csp import get_nonce from django.middleware.csrf import get_token from django.utils.functional import SimpleLazyObject, lazy def csrf(request): """ Context processor that provides a CSRF token, or the string 'NOTPROVIDED' if it has not been provided by either a view decorator or the middleware """ def _get_val(): token = get_token(request) if token is None: # In order to be able to provide debugging info in the # case of misconfiguration, we use a sentinel value # instead of returning an empty dict. return "NOTPROVIDED" else: return token return {"csrf_token": SimpleLazyObject(_get_val)} def debug(request): """ Return context variables helpful for debugging. """ context_extras = {} if settings.DEBUG and request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS: context_extras["debug"] = True from django.db import connections # Return a lazy reference that computes connection.queries on access, # to ensure it contains queries triggered after this function runs. context_extras["sql_queries"] = lazy( lambda: list( itertools.chain.from_iterable( connections[x].queries for x in connections ) ), list, ) return context_extras def i18n(request): from django.utils import translation return { "LANGUAGES": settings.LANGUAGES, "LANGUAGE_CODE": translation.get_language(), "LANGUAGE_BIDI": translation.get_language_bidi(), } def tz(request): from django.utils import timezone return {"TIME_ZONE": timezone.get_current_timezone_name()} def static(request): """ Add static-related context variables to the context. """ return {"STATIC_URL": settings.STATIC_URL} def media(request): """ Add media-related context variables to the context. """ return {"MEDIA_URL": settings.MEDIA_URL} def request(request): return {"request": request} def csp(request): """ Add the CSP nonce to the context. """ return {"csp_nonce": get_nonce(request)}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/autoreload.py
django/template/autoreload.py
from pathlib import Path from django.dispatch import receiver from django.template import engines from django.template.backends.django import DjangoTemplates from django.utils._os import to_path from django.utils.autoreload import autoreload_started, file_changed, is_django_path def get_template_directories(): # Iterate through each template backend and find # any template_loader that has a 'get_dirs' method. # Collect the directories, filtering out Django templates. cwd = Path.cwd() items = set() for backend in engines.all(): if not isinstance(backend, DjangoTemplates): continue items.update(cwd / to_path(dir) for dir in backend.engine.dirs if dir) for loader in backend.engine.template_loaders: if not hasattr(loader, "get_dirs"): continue items.update( cwd / to_path(directory) for directory in loader.get_dirs() if directory and not is_django_path(directory) ) return items def reset_loaders(): from django.forms.renderers import get_default_renderer for backend in engines.all(): if not isinstance(backend, DjangoTemplates): continue for loader in backend.engine.template_loaders: loader.reset() backend = getattr(get_default_renderer(), "engine", None) if isinstance(backend, DjangoTemplates): for loader in backend.engine.template_loaders: loader.reset() @receiver(autoreload_started, dispatch_uid="template_loaders_watch_changes") def watch_for_template_changes(sender, **kwargs): for directory in get_template_directories(): sender.watch_dir(directory, "**/*") @receiver(file_changed, dispatch_uid="template_loaders_file_changed") def template_changed(sender, file_path, **kwargs): if file_path.suffix == ".py": return for template_dir in get_template_directories(): if template_dir in file_path.parents: reset_loaders() return True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/utils.py
django/template/utils.py
import functools from collections import Counter from pathlib import Path from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.utils.functional import cached_property from django.utils.module_loading import import_string class InvalidTemplateEngineError(ImproperlyConfigured): pass class EngineHandler: def __init__(self, templates=None): """ templates is an optional list of template engine definitions (structured like settings.TEMPLATES). """ self._templates = templates self._engines = {} @cached_property def templates(self): if self._templates is None: self._templates = settings.TEMPLATES templates = {} backend_names = [] for tpl in self._templates: try: # This will raise an exception if 'BACKEND' doesn't exist or # isn't a string containing at least one dot. default_name = tpl["BACKEND"].rsplit(".", 2)[-2] except Exception: invalid_backend = tpl.get("BACKEND", "<not defined>") raise ImproperlyConfigured( "Invalid BACKEND for a template engine: {}. Check " "your TEMPLATES setting.".format(invalid_backend) ) tpl = { "NAME": default_name, "DIRS": [], "APP_DIRS": False, "OPTIONS": {}, **tpl, } templates[tpl["NAME"]] = tpl backend_names.append(tpl["NAME"]) counts = Counter(backend_names) duplicates = [alias for alias, count in counts.most_common() if count > 1] if duplicates: raise ImproperlyConfigured( "Template engine aliases aren't unique, duplicates: {}. " "Set a unique NAME for each engine in settings.TEMPLATES.".format( ", ".join(duplicates) ) ) return templates def __getitem__(self, alias): try: return self._engines[alias] except KeyError: try: params = self.templates[alias] except KeyError: raise InvalidTemplateEngineError( "Could not find config for '{}' " "in settings.TEMPLATES".format(alias) ) # If importing or initializing the backend raises an exception, # self._engines[alias] isn't set and this code may get executed # again, so we must preserve the original params. See #24265. params = params.copy() backend = params.pop("BACKEND") engine_cls = import_string(backend) engine = engine_cls(params) self._engines[alias] = engine return engine def __iter__(self): return iter(self.templates) def all(self): return [self[alias] for alias in self] @functools.lru_cache def get_app_template_dirs(dirname): """ Return an iterable of paths of directories to load app templates from. dirname is the name of the subdirectory containing templates inside installed applications. """ # Immutable return value because it will be cached and shared by callers. return tuple( path for app_config in apps.get_app_configs() if app_config.path and (path := Path(app_config.path) / dirname).is_dir() )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/__init__.py
django/template/__init__.py
""" Django's support for templates. The django.template namespace contains two independent subsystems: 1. Multiple Template Engines: support for pluggable template backends, built-in backends and backend-independent APIs 2. Django Template Language: Django's own template engine, including its built-in loaders, context processors, tags and filters. Ideally these subsystems would be implemented in distinct packages. However keeping them together made the implementation of Multiple Template Engines less disruptive . Here's a breakdown of which modules belong to which subsystem. Multiple Template Engines: - django.template.backends.* - django.template.loader - django.template.response Django Template Language: - django.template.base - django.template.context - django.template.context_processors - django.template.loaders.* - django.template.debug - django.template.defaultfilters - django.template.defaulttags - django.template.engine - django.template.loader_tags - django.template.smartif Shared: - django.template.utils """ # Multiple Template Engines from .engine import Engine from .utils import EngineHandler engines = EngineHandler() __all__ = ("Engine", "engines") # Django Template Language # Public exceptions from .base import VariableDoesNotExist # NOQA isort:skip from .context import Context, ContextPopException, RequestContext # NOQA isort:skip from .exceptions import TemplateDoesNotExist, TemplateSyntaxError # NOQA isort:skip # Template parts from .base import ( # NOQA isort:skip Node, NodeList, Origin, PartialTemplate, Template, Variable, ) # Library management from .library import Library # NOQA isort:skip # Import the .autoreload module to trigger the registrations of signals. from . import autoreload # NOQA isort:skip __all__ += ("Template", "Context", "RequestContext")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/context.py
django/template/context.py
from contextlib import contextmanager from copy import copy # Hard-coded processor for easier use of CSRF protection. _builtin_context_processors = ("django.template.context_processors.csrf",) class ContextPopException(Exception): "pop() has been called more times than push()" pass class ContextDict(dict): def __init__(self, context, *args, **kwargs): super().__init__(*args, **kwargs) context.dicts.append(self) self.context = context def __enter__(self): return self def __exit__(self, *args, **kwargs): self.context.pop() class BaseContext: def __init__(self, dict_=None): self._reset_dicts(dict_) def _reset_dicts(self, value=None): builtins = {"True": True, "False": False, "None": None} self.dicts = [builtins] if isinstance(value, BaseContext): self.dicts += value.dicts[1:] elif value is not None: self.dicts.append(value) def __copy__(self): duplicate = BaseContext() duplicate.__class__ = self.__class__ duplicate.__dict__ = copy(self.__dict__) duplicate.dicts = self.dicts[:] return duplicate def __repr__(self): return repr(self.dicts) def __iter__(self): return reversed(self.dicts) def push(self, *args, **kwargs): dicts = [] for d in args: if isinstance(d, BaseContext): dicts += d.dicts[1:] else: dicts.append(d) return ContextDict(self, *dicts, **kwargs) def pop(self): if len(self.dicts) == 1: raise ContextPopException return self.dicts.pop() def __setitem__(self, key, value): "Set a variable in the current context" self.dicts[-1][key] = value def set_upward(self, key, value): """ Set a variable in one of the higher contexts if it exists there, otherwise in the current context. """ context = self.dicts[-1] for d in reversed(self.dicts): if key in d: context = d break context[key] = value def __getitem__(self, key): """ Get a variable's value, starting at the current context and going upward """ for d in reversed(self.dicts): if key in d: return d[key] raise KeyError(key) def __delitem__(self, key): "Delete a variable from the current context" del self.dicts[-1][key] def __contains__(self, key): return any(key in d for d in self.dicts) def get(self, key, otherwise=None): for d in reversed(self.dicts): if key in d: return d[key] return otherwise def setdefault(self, key, default=None): try: return self[key] except KeyError: self[key] = default return default def new(self, values=None): """ Return a new context with the same properties, but with only the values given in 'values' stored. """ new_context = copy(self) new_context._reset_dicts(values) return new_context def flatten(self): """ Return self.dicts as one dictionary. """ flat = {} for d in self.dicts: flat.update(d) return flat def __eq__(self, other): """ Compare two contexts by comparing theirs 'dicts' attributes. """ if not isinstance(other, BaseContext): return NotImplemented # flatten dictionaries because they can be put in a different order. return self.flatten() == other.flatten() class Context(BaseContext): "A stack container for variable context" def __init__(self, dict_=None, autoescape=True, use_l10n=None, use_tz=None): self.autoescape = autoescape self.use_l10n = use_l10n self.use_tz = use_tz self.template_name = "unknown" self.render_context = RenderContext() # Set to the original template -- as opposed to extended or included # templates -- during rendering, see bind_template. self.template = None super().__init__(dict_) @contextmanager def bind_template(self, template): if self.template is not None: raise RuntimeError("Context is already bound to a template") self.template = template try: yield finally: self.template = None def __copy__(self): duplicate = super().__copy__() duplicate.render_context = copy(self.render_context) return duplicate def update(self, other_dict): "Push other_dict to the stack of dictionaries in the Context" if not hasattr(other_dict, "__getitem__"): raise TypeError("other_dict must be a mapping (dictionary-like) object.") if isinstance(other_dict, BaseContext): other_dict = other_dict.dicts[1:].pop() return ContextDict(self, other_dict) class RenderContext(BaseContext): """ A stack container for storing Template state. RenderContext simplifies the implementation of template Nodes by providing a safe place to store state between invocations of a node's `render` method. The RenderContext also provides scoping rules that are more sensible for 'template local' variables. The render context stack is pushed before each template is rendered, creating a fresh scope with nothing in it. Name resolution fails if a variable is not found at the top of the RequestContext stack. Thus, variables are local to a specific template and don't affect the rendering of other templates as they would if they were stored in the normal template context. """ template = None def __iter__(self): yield from self.dicts[-1] def __contains__(self, key): return key in self.dicts[-1] def get(self, key, otherwise=None): return self.dicts[-1].get(key, otherwise) def __getitem__(self, key): return self.dicts[-1][key] @contextmanager def push_state(self, template, isolated_context=True): initial = self.template self.template = template if isolated_context: self.push() try: yield finally: self.template = initial if isolated_context: self.pop() class RequestContext(Context): """ This subclass of template.Context automatically populates itself using the processors defined in the engine's configuration. Additional processors can be specified as a list of callables using the "processors" keyword argument. """ def __init__( self, request, dict_=None, processors=None, use_l10n=None, use_tz=None, autoescape=True, ): super().__init__(dict_, use_l10n=use_l10n, use_tz=use_tz, autoescape=autoescape) self.request = request self._processors = () if processors is None else tuple(processors) self._processors_index = len(self.dicts) # placeholder for context processors output self.update({}) # empty dict for any new modifications # (so that context processors don't overwrite them) self.update({}) @contextmanager def bind_template(self, template): if self.template is not None: raise RuntimeError("Context is already bound to a template") self.template = template # Set context processors according to the template engine's settings. processors = template.engine.template_context_processors + self._processors updates = {} for processor in processors: context = processor(self.request) try: updates.update(context) except TypeError as e: raise TypeError( f"Context processor {processor.__qualname__} didn't return a " "dictionary." ) from e self.dicts[self._processors_index] = updates try: yield finally: self.template = None # Unset context processors. self.dicts[self._processors_index] = {} def new(self, values=None): new_context = super().new(values) # This is for backwards-compatibility: RequestContexts created via # Context.new don't include values from context processors. if hasattr(new_context, "_processors_index"): del new_context._processors_index return new_context def make_context(context, request=None, **kwargs): """ Create a suitable Context from a plain dict and optionally an HttpRequest. """ if context is not None and not isinstance(context, dict): raise TypeError( "context must be a dict rather than %s." % context.__class__.__name__ ) if request is None: context = Context(context, **kwargs) else: # The following pattern is required to ensure values from # context override those from template context processors. original_context = context context = RequestContext(request, **kwargs) if original_context: context.push(original_context) return context
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/base.py
django/template/base.py
""" This is the Django template system. How it works: The Lexer.tokenize() method converts a template string (i.e., a string containing markup with custom template tags) to tokens, which can be either plain text (TokenType.TEXT), variables (TokenType.VAR), or block statements (TokenType.BLOCK). The Parser() class takes a list of tokens in its constructor, and its parse() method returns a compiled template -- which is, under the hood, a list of Node objects. Each Node is responsible for creating some sort of output -- e.g. simple text (TextNode), variable values in a given context (VariableNode), results of basic logic (IfNode), results of looping (ForNode), or anything else. The core Node types are TextNode, VariableNode, IfNode and ForNode, but plugin modules can define their own custom node types. Each Node has a render() method, which takes a Context and returns a string of the rendered node. For example, the render() method of a Variable Node returns the variable's value as a string. The render() method of a ForNode returns the rendered output of whatever was inside the loop, recursively. The Template class is a convenient wrapper that takes care of template compilation and rendering. Usage: The only thing you should ever use directly in this file is the Template class. Create a compiled template object with a template_string, then call render() with a context. In the compilation stage, the TemplateSyntaxError exception will be raised if the template doesn't have proper syntax. Sample code: >>> from django import template >>> s = '<html>{% if test %}<h1>{{ varvalue }}</h1>{% endif %}</html>' >>> t = template.Template(s) (t is now a compiled template, and its render() method can be called multiple times with multiple contexts) >>> c = template.Context({'test':True, 'varvalue': 'Hello'}) >>> t.render(c) '<html><h1>Hello</h1></html>' >>> c = template.Context({'test':False, 'varvalue': 'Hello'}) >>> t.render(c) '<html></html>' """ import inspect import logging import re import warnings from enum import Enum from django.template.context import BaseContext from django.utils.deprecation import django_file_prefixes from django.utils.formats import localize from django.utils.html import conditional_escape from django.utils.inspect import lazy_annotations from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import get_text_list, smart_split, unescape_string_literal from django.utils.timezone import template_localtime from django.utils.translation import gettext_lazy, pgettext_lazy from .exceptions import TemplateSyntaxError # template syntax constants FILTER_SEPARATOR = "|" FILTER_ARGUMENT_SEPARATOR = ":" VARIABLE_ATTRIBUTE_SEPARATOR = "." BLOCK_TAG_START = "{%" BLOCK_TAG_END = "%}" VARIABLE_TAG_START = "{{" VARIABLE_TAG_END = "}}" COMMENT_TAG_START = "{#" COMMENT_TAG_END = "#}" SINGLE_BRACE_START = "{" SINGLE_BRACE_END = "}" # what to report as the origin for templates that come from non-loader sources # (e.g. strings) UNKNOWN_SOURCE = "<unknown source>" # Match BLOCK_TAG_*, VARIABLE_TAG_*, and COMMENT_TAG_* tags and capture the # entire tag, including start/end delimiters. Using re.compile() is faster # than instantiating SimpleLazyObject with _lazy_re_compile(). tag_re = re.compile(r"({%.*?%}|{{.*?}}|{#.*?#})") logger = logging.getLogger("django.template") class TokenType(Enum): TEXT = 0 VAR = 1 BLOCK = 2 COMMENT = 3 class VariableDoesNotExist(Exception): def __init__(self, msg, params=()): self.msg = msg self.params = params def __str__(self): return self.msg % self.params class Origin: def __init__(self, name, template_name=None, loader=None): self.name = name self.template_name = template_name self.loader = loader def __str__(self): return self.name def __repr__(self): return "<%s name=%r>" % (self.__class__.__qualname__, self.name) def __eq__(self, other): return ( isinstance(other, Origin) and self.name == other.name and self.loader == other.loader ) @property def loader_name(self): if self.loader: return "%s.%s" % ( self.loader.__module__, self.loader.__class__.__name__, ) class Template: def __init__(self, template_string, origin=None, name=None, engine=None): # If Template is instantiated directly rather than from an Engine and # exactly one Django template engine is configured, use that engine. # This is required to preserve backwards-compatibility for direct use # e.g. Template('...').render(Context({...})) if engine is None: from .engine import Engine engine = Engine.get_default() if origin is None: origin = Origin(UNKNOWN_SOURCE) self.name = name self.origin = origin self.engine = engine self.source = str(template_string) # May be lazy. self.nodelist = self.compile_nodelist() def __repr__(self): return '<%s template_string="%s...">' % ( self.__class__.__qualname__, self.source[:20].replace("\n", ""), ) def _render(self, context): return self.nodelist.render(context) def render(self, context): "Display stage -- can be called many times" with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def compile_nodelist(self): """ Parse and compile the template source into a nodelist. If debug is True and an exception occurs during parsing, the exception is annotated with contextual line information where it occurred in the template source. """ if self.engine.debug: lexer = DebugLexer(self.source) else: lexer = Lexer(self.source) tokens = lexer.tokenize() parser = Parser( tokens, self.engine.template_libraries, self.engine.template_builtins, self.origin, ) try: nodelist = parser.parse() self.extra_data = parser.extra_data return nodelist except Exception as e: if self.engine.debug: e.template_debug = self.get_exception_info(e, e.token) if ( isinstance(e, TemplateSyntaxError) and self.origin.name != UNKNOWN_SOURCE and e.args ): raw_message = e.args[0] e.raw_error_message = raw_message e.args = (f"Template: {self.origin.name}, {raw_message}", *e.args[1:]) raise def get_exception_info(self, exception, token): """ Return a dictionary containing contextual line information of where the exception occurred in the template. The following information is provided: message The message of the exception raised. source_lines The lines before, after, and including the line the exception occurred on. line The line number the exception occurred on. before, during, after The line the exception occurred on split into three parts: 1. The content before the token that raised the error. 2. The token that raised the error. 3. The content after the token that raised the error. total The number of lines in source_lines. top The line number where source_lines starts. bottom The line number where source_lines ends. start The start position of the token in the template source. end The end position of the token in the template source. """ start, end = token.position context_lines = 10 line = 0 upto = 0 source_lines = [] before = during = after = "" for num, next in enumerate(linebreak_iter(self.source)): if start >= upto and end <= next: line = num before = self.source[upto:start] during = self.source[start:end] after = self.source[end:next] source_lines.append((num, self.source[upto:next])) upto = next total = len(source_lines) top = max(1, line - context_lines) bottom = min(total, line + 1 + context_lines) # In some rare cases exc_value.args can be empty or an invalid # string. try: message = str(exception.args[0]) except (IndexError, UnicodeDecodeError): message = "(Could not get exception message)" return { "message": message, "source_lines": source_lines[top:bottom], "before": before, "during": during, "after": after, "top": top, "bottom": bottom, "total": total, "line": line, "name": self.origin.name, "start": start, "end": end, } class PartialTemplate: """ A lightweight Template lookalike used for template partials. Wraps nodelist as a partial, in order to be able to bind context. """ def __init__(self, nodelist, origin, name, source_start=None, source_end=None): self.nodelist = nodelist self.origin = origin self.name = name # If available (debug mode), the absolute character offsets in the # template.source correspond to the full partial region. self._source_start = source_start self._source_end = source_end def get_exception_info(self, exception, token): template = self.origin.loader.get_template(self.origin.template_name) return template.get_exception_info(exception, token) def find_partial_source(self, full_source): if ( self._source_start is not None and self._source_end is not None and 0 <= self._source_start <= self._source_end <= len(full_source) ): return full_source[self._source_start : self._source_end] return "" @property def source(self): template = self.origin.loader.get_template(self.origin.template_name) if not template.engine.debug: warnings.warn( "PartialTemplate.source is only available when template " "debugging is enabled.", RuntimeWarning, skip_file_prefixes=django_file_prefixes(), ) return self.find_partial_source(template.source) def _render(self, context): return self.nodelist.render(context) def render(self, context): with context.render_context.push_state(self): if context.template is None: with context.bind_template(self): context.template_name = self.name return self._render(context) else: return self._render(context) def linebreak_iter(template_source): yield 0 p = template_source.find("\n") while p >= 0: yield p + 1 p = template_source.find("\n", p + 1) yield len(template_source) + 1 class Token: def __init__(self, token_type, contents, position=None, lineno=None): """ A token representing a string from the template. token_type A TokenType, either .TEXT, .VAR, .BLOCK, or .COMMENT. contents The token source string. position An optional tuple containing the start and end index of the token in the template source. This is used for traceback information when debug is on. lineno The line number the token appears on in the template source. This is used for traceback information and gettext files. """ self.token_type = token_type self.contents = contents self.lineno = lineno self.position = position def __repr__(self): token_name = self.token_type.name.capitalize() return '<%s token: "%s...">' % ( token_name, self.contents[:20].replace("\n", ""), ) def split_contents(self): split = [] bits = smart_split(self.contents) for bit in bits: # Handle translation-marked template pieces if bit.startswith(('_("', "_('")): sentinel = bit[2] + ")" trans_bit = [bit] while not bit.endswith(sentinel): bit = next(bits) trans_bit.append(bit) bit = " ".join(trans_bit) split.append(bit) return split class Lexer: def __init__(self, template_string): self.template_string = template_string self.verbatim = False def __repr__(self): return '<%s template_string="%s...", verbatim=%s>' % ( self.__class__.__qualname__, self.template_string[:20].replace("\n", ""), self.verbatim, ) def tokenize(self): """ Return a list of tokens from a given template_string. """ in_tag = False lineno = 1 result = [] for token_string in tag_re.split(self.template_string): if token_string: result.append(self.create_token(token_string, None, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result def create_token(self, token_string, position, lineno, in_tag): """ Convert the given token string into a new Token object and return it. If in_tag is True, we are processing something that matched a tag, otherwise it should be treated as a literal string. """ if in_tag: # The [0:2] and [2:-2] ranges below strip off *_TAG_START and # *_TAG_END. The 2's are hard-coded for performance. Using # len(BLOCK_TAG_START) would permit BLOCK_TAG_START to be # different, but it's not likely that the TAG_START values will # change anytime soon. token_start = token_string[0:2] if token_start == BLOCK_TAG_START: content = token_string[2:-2].strip() if self.verbatim: # Then a verbatim block is being processed. if content != self.verbatim: return Token(TokenType.TEXT, token_string, position, lineno) # Otherwise, the current verbatim block is ending. self.verbatim = False elif content[:9] in ("verbatim", "verbatim "): # Then a verbatim block is starting. self.verbatim = "end%s" % content return Token(TokenType.BLOCK, content, position, lineno) if not self.verbatim: content = token_string[2:-2].strip() if token_start == VARIABLE_TAG_START: return Token(TokenType.VAR, content, position, lineno) # BLOCK_TAG_START was handled above. assert token_start == COMMENT_TAG_START return Token(TokenType.COMMENT, content, position, lineno) return Token(TokenType.TEXT, token_string, position, lineno) class DebugLexer(Lexer): def _tag_re_split_positions(self): last = 0 for match in tag_re.finditer(self.template_string): start, end = match.span() yield last, start yield start, end last = end yield last, len(self.template_string) # This parallels the use of tag_re.split() in Lexer.tokenize(). def _tag_re_split(self): for position in self._tag_re_split_positions(): yield self.template_string[slice(*position)], position def tokenize(self): """ Split a template string into tokens and annotates each token with its start and end position in the source. This is slower than the default lexer so only use it when debug is True. """ # For maintainability, it is helpful if the implementation below can # continue to closely parallel Lexer.tokenize()'s implementation. in_tag = False lineno = 1 result = [] for token_string, position in self._tag_re_split(): if token_string: result.append(self.create_token(token_string, position, lineno, in_tag)) lineno += token_string.count("\n") in_tag = not in_tag return result class Parser: def __init__(self, tokens, libraries=None, builtins=None, origin=None): # Reverse the tokens so delete_first_token(), prepend_token(), and # next_token() can operate at the end of the list in constant time. self.tokens = list(reversed(tokens)) self.tags = {} self.filters = {} self.command_stack = [] # Custom template tags may store additional data on the parser that # will be made available on the template instance. Library authors # should use a key to namespace any added data. The 'django' namespace # is reserved for internal use. self.extra_data = {} if libraries is None: libraries = {} if builtins is None: builtins = [] self.libraries = libraries for builtin in builtins: self.add_library(builtin) self.origin = origin def __repr__(self): return "<%s tokens=%r>" % (self.__class__.__qualname__, self.tokens) def parse(self, parse_until=None): """ Iterate through the parser tokens and compiles each one into a node. If parse_until is provided, parsing will stop once one of the specified tokens has been reached. This is formatted as a list of tokens, e.g. ['elif', 'else', 'endif']. If no matching token is reached, raise an exception with the unclosed block tag details. """ if parse_until is None: parse_until = [] nodelist = NodeList() while self.tokens: token = self.next_token() # Use the raw values here for TokenType.* for a tiny performance # boost. token_type = token.token_type.value if token_type == 0: # TokenType.TEXT self.extend_nodelist(nodelist, TextNode(token.contents), token) elif token_type == 1: # TokenType.VAR if not token.contents: raise self.error( token, "Empty variable tag on line %d" % token.lineno ) try: filter_expression = self.compile_filter(token.contents) except TemplateSyntaxError as e: raise self.error(token, e) var_node = VariableNode(filter_expression) self.extend_nodelist(nodelist, var_node, token) elif token_type == 2: # TokenType.BLOCK try: command = token.contents.split()[0] except IndexError: raise self.error(token, "Empty block tag on line %d" % token.lineno) if command in parse_until: # A matching token has been reached. Return control to # the caller. Put the token back on the token list so the # caller knows where it terminated. self.prepend_token(token) return nodelist # Add the token to the command stack. This is used for error # messages if further parsing fails due to an unclosed block # tag. self.command_stack.append((command, token)) # Get the tag callback function from the ones registered with # the parser. try: compile_func = self.tags[command] except KeyError: self.invalid_block_tag(token, command, parse_until) # Compile the callback into a node object and add it to # the node list. try: compiled_result = compile_func(self, token) except Exception as e: raise self.error(token, e) self.extend_nodelist(nodelist, compiled_result, token) # Compile success. Remove the token from the command stack. self.command_stack.pop() if parse_until: self.unclosed_block_tag(parse_until) return nodelist def skip_past(self, endtag): while self.tokens: token = self.next_token() if token.token_type == TokenType.BLOCK and token.contents == endtag: return self.unclosed_block_tag([endtag]) def extend_nodelist(self, nodelist, node, token): # Check that non-text nodes don't appear before an extends tag. if node.must_be_first and nodelist.contains_nontext: if self.origin.template_name: origin = repr(self.origin.template_name) else: origin = "the template" raise self.error( token, "{%% %s %%} must be the first tag in %s." % (token.contents, origin), ) if not isinstance(node, TextNode): nodelist.contains_nontext = True # Set origin and token here since we can't modify the node __init__() # method. node.token = token node.origin = self.origin nodelist.append(node) def error(self, token, e): """ Return an exception annotated with the originating token. Since the parser can be called recursively, check if a token is already set. This ensures the innermost token is highlighted if an exception occurs, e.g. a compile error within the body of an if statement. """ if not isinstance(e, Exception): e = TemplateSyntaxError(e) if not hasattr(e, "token"): e.token = token return e def invalid_block_tag(self, token, command, parse_until=None): if parse_until: raise self.error( token, "Invalid block tag on line %d: '%s', expected %s. Did you " "forget to register or load this tag?" % ( token.lineno, command, get_text_list(["'%s'" % p for p in parse_until], "or"), ), ) raise self.error( token, "Invalid block tag on line %d: '%s'. Did you forget to register " "or load this tag?" % (token.lineno, command), ) def unclosed_block_tag(self, parse_until): command, token = self.command_stack.pop() msg = "Unclosed tag on line %d: '%s'. Looking for one of: %s." % ( token.lineno, command, ", ".join(parse_until), ) raise self.error(token, msg) def next_token(self): return self.tokens.pop() def prepend_token(self, token): self.tokens.append(token) def delete_first_token(self): del self.tokens[-1] def add_library(self, lib): self.tags.update(lib.tags) self.filters.update(lib.filters) def compile_filter(self, token): """ Convenient wrapper for FilterExpression """ return FilterExpression(token, self) def find_filter(self, filter_name): if filter_name in self.filters: return self.filters[filter_name] else: raise TemplateSyntaxError("Invalid filter: '%s'" % filter_name) # This only matches constant *strings* (things in quotes or marked for # translation). Numbers are treated as variables for implementation reasons # (so that they retain their type when passed to filters). constant_string = r""" (?:%(i18n_open)s%(strdq)s%(i18n_close)s| %(i18n_open)s%(strsq)s%(i18n_close)s| %(strdq)s| %(strsq)s) """ % { "strdq": r'"[^"\\]*(?:\\.[^"\\]*)*"', # double-quoted string "strsq": r"'[^'\\]*(?:\\.[^'\\]*)*'", # single-quoted string "i18n_open": re.escape("_("), "i18n_close": re.escape(")"), } constant_string = constant_string.replace("\n", "") filter_raw_string = r""" ^(?P<constant>%(constant)s)| ^(?P<var>[%(var_chars)s]+)| (?:\s*%(filter_sep)s\s* (?P<filter_name>\w+) (?:%(arg_sep)s (?: (?P<constant_arg>%(constant)s)| (?P<var_arg>[%(var_chars)s]+) ) )? )""" % { "constant": constant_string, "var_chars": r"\w\.\+-", "filter_sep": re.escape(FILTER_SEPARATOR), "arg_sep": re.escape(FILTER_ARGUMENT_SEPARATOR), } filter_re = _lazy_re_compile(filter_raw_string, re.VERBOSE) class FilterExpression: """ Parse a variable token and its optional filters (all as a single string), and return a list of tuples of the filter name and arguments. Sample:: >>> token = 'variable|default:"Default value"|date:"Y-m-d"' >>> p = Parser('') >>> fe = FilterExpression(token, p) >>> len(fe.filters) 2 >>> fe.var <Variable: 'variable'> """ __slots__ = ("token", "filters", "var", "is_var") def __init__(self, token, parser): self.token = token matches = filter_re.finditer(token) var_obj = None filters = [] upto = 0 for match in matches: start = match.start() if upto != start: raise TemplateSyntaxError( "Could not parse some characters: " "%s|%s|%s" % (token[:upto], token[upto:start], token[start:]) ) if var_obj is None: if constant := match["constant"]: try: var_obj = Variable(constant).resolve({}) except VariableDoesNotExist: var_obj = None elif (var := match["var"]) is None: raise TemplateSyntaxError( "Could not find variable at start of %s." % token ) else: var_obj = Variable(var) else: filter_name = match["filter_name"] args = [] if constant_arg := match["constant_arg"]: args.append((False, Variable(constant_arg).resolve({}))) elif var_arg := match["var_arg"]: args.append((True, Variable(var_arg))) filter_func = parser.find_filter(filter_name) self.args_check(filter_name, filter_func, args) filters.append((filter_func, args)) upto = match.end() if upto != len(token): raise TemplateSyntaxError( "Could not parse the remainder: '%s' " "from '%s'" % (token[upto:], token) ) self.filters = filters self.var = var_obj self.is_var = isinstance(var_obj, Variable) def resolve(self, context, ignore_failures=False): if self.is_var: try: obj = self.var.resolve(context) except VariableDoesNotExist: if ignore_failures: obj = None else: string_if_invalid = context.template.engine.string_if_invalid if string_if_invalid: if "%s" in string_if_invalid: return string_if_invalid % self.var else: return string_if_invalid else: obj = string_if_invalid else: obj = self.var for func, args in self.filters: arg_vals = [] for lookup, arg in args: if not lookup: arg_vals.append(mark_safe(arg)) else: arg_vals.append(arg.resolve(context)) if getattr(func, "expects_localtime", False): obj = template_localtime(obj, context.use_tz) if getattr(func, "needs_autoescape", False): new_obj = func(obj, autoescape=context.autoescape, *arg_vals) else: new_obj = func(obj, *arg_vals) if getattr(func, "is_safe", False) and isinstance(obj, SafeData): obj = mark_safe(new_obj) else: obj = new_obj return obj def args_check(name, func, provided): provided = list(provided) # First argument, filter input, is implied. plen = len(provided) + 1 # Check to see if a decorator is providing the real function. func = inspect.unwrap(func) with lazy_annotations(): args, _, _, defaults, _, _, _ = inspect.getfullargspec(func) alen = len(args) dlen = len(defaults or []) # Not enough OR Too many if plen < (alen - dlen) or plen > alen: raise TemplateSyntaxError( "%s requires %d arguments, %d provided" % (name, alen - dlen, plen) ) return True args_check = staticmethod(args_check) def __str__(self): return self.token def __repr__(self): return "<%s %r>" % (self.__class__.__qualname__, self.token) class Variable: """ A template variable, resolvable against a given context. The variable may be a hard-coded string (if it begins and ends with single or double quote marks):: >>> c = {'article': {'section':'News'}} >>> Variable('article.section').resolve(c) 'News' >>> Variable('article').resolve(c) {'section': 'News'} >>> class AClass: pass >>> c = AClass() >>> c.article = AClass() >>> c.article.section = 'News' (The example assumes VARIABLE_ATTRIBUTE_SEPARATOR is '.') """ __slots__ = ("var", "literal", "lookups", "translate", "message_context") def __init__(self, var): self.var = var self.literal = None self.lookups = None self.translate = False self.message_context = None if not isinstance(var, str): raise TypeError("Variable must be a string or number, got %s" % type(var)) try: # First try to treat this variable as a number. # # Note that this could cause an OverflowError here that we're not # catching. Since this should only happen at compile time, that's # probably OK. # Try to interpret values containing a period or an 'e'/'E' # (possibly scientific notation) as a float; otherwise, try int. if "." in var or "e" in var.lower(): self.literal = float(var) # "2." is invalid if var[-1] == ".": raise ValueError else: self.literal = int(var) except ValueError: # A ValueError means that the variable isn't a number. if var[0:2] == "_(" and var[-1] == ")": # The result of the lookup should be translated at rendering # time. self.translate = True var = var[2:-1] # If it's wrapped with quotes (single or double), then # we're also dealing with a literal. try: self.literal = mark_safe(unescape_string_literal(var)) except ValueError: # Otherwise we'll set self.lookups so that resolve() knows # we're dealing with a bonafide variable if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in var or var[0] == "_": raise TemplateSyntaxError( "Variables and attributes may "
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/engine.py
django/template/engine.py
import functools from django.core.exceptions import ImproperlyConfigured from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import Template from .context import Context, _builtin_context_processors from .exceptions import TemplateDoesNotExist from .library import import_library class Engine: default_builtins = [ "django.template.defaulttags", "django.template.defaultfilters", "django.template.loader_tags", ] def __init__( self, dirs=None, app_dirs=False, context_processors=None, debug=False, loaders=None, string_if_invalid="", file_charset="utf-8", libraries=None, builtins=None, autoescape=True, ): if dirs is None: dirs = [] if context_processors is None: context_processors = [] if loaders is None: loaders = ["django.template.loaders.filesystem.Loader"] if app_dirs: loaders += ["django.template.loaders.app_directories.Loader"] loaders = [("django.template.loaders.cached.Loader", loaders)] else: if app_dirs: raise ImproperlyConfigured( "app_dirs must not be set when loaders is defined." ) if libraries is None: libraries = {} if builtins is None: builtins = [] self.dirs = dirs self.app_dirs = app_dirs self.autoescape = autoescape self.context_processors = context_processors self.debug = debug self.loaders = loaders self.string_if_invalid = string_if_invalid self.file_charset = file_charset self.libraries = libraries self.template_libraries = self.get_template_libraries(libraries) self.builtins = self.default_builtins + builtins self.template_builtins = self.get_template_builtins(self.builtins) def __repr__(self): return ( "<%s:%s app_dirs=%s%s debug=%s loaders=%s string_if_invalid=%s " "file_charset=%s%s%s autoescape=%s>" ) % ( self.__class__.__qualname__, "" if not self.dirs else " dirs=%s" % repr(self.dirs), self.app_dirs, ( "" if not self.context_processors else " context_processors=%s" % repr(self.context_processors) ), self.debug, repr(self.loaders), repr(self.string_if_invalid), repr(self.file_charset), "" if not self.libraries else " libraries=%s" % repr(self.libraries), "" if not self.builtins else " builtins=%s" % repr(self.builtins), repr(self.autoescape), ) @staticmethod @functools.lru_cache def get_default(): """ Return the first DjangoTemplates backend that's configured, or raise ImproperlyConfigured if none are configured. This is required for preserving historical APIs that rely on a globally available, implicitly configured engine such as: >>> from django.template import Context, Template >>> template = Template("Hello {{ name }}!") >>> context = Context({'name': "world"}) >>> template.render(context) 'Hello world!' """ # Since Engine is imported in django.template and since # DjangoTemplates is a wrapper around this Engine class, # local imports are required to avoid import loops. from django.template import engines from django.template.backends.django import DjangoTemplates for engine in engines.all(): if isinstance(engine, DjangoTemplates): return engine.engine raise ImproperlyConfigured("No DjangoTemplates backend is configured.") @cached_property def template_context_processors(self): context_processors = _builtin_context_processors context_processors += tuple(self.context_processors) return tuple(import_string(path) for path in context_processors) def get_template_builtins(self, builtins): return [import_library(x) for x in builtins] def get_template_libraries(self, libraries): loaded = {} for name, path in libraries.items(): loaded[name] = import_library(path) return loaded @cached_property def template_loaders(self): return self.get_template_loaders(self.loaders) def get_template_loaders(self, template_loaders): loaders = [] for template_loader in template_loaders: loader = self.find_template_loader(template_loader) if loader is not None: loaders.append(loader) return loaders def find_template_loader(self, loader): if isinstance(loader, (tuple, list)): loader, *args = loader else: args = [] if isinstance(loader, str): loader_class = import_string(loader) return loader_class(self, *args) else: raise ImproperlyConfigured( "Invalid value in template loaders configuration: %r" % loader ) def find_template(self, name, dirs=None, skip=None): tried = [] for loader in self.template_loaders: try: template = loader.get_template(name, skip=skip) return template, template.origin except TemplateDoesNotExist as e: tried.extend(e.tried) raise TemplateDoesNotExist(name, tried=tried) def from_string(self, template_code): """ Return a compiled Template object for the given template code, handling template inheritance recursively. """ return Template(template_code, engine=self) def get_template(self, template_name): """ Return a compiled Template object for the given template name, handling template inheritance recursively. """ original_name = template_name try: template_name, _, partial_name = template_name.partition("#") except AttributeError: raise TemplateDoesNotExist(original_name) if not template_name: raise TemplateDoesNotExist(original_name) template, origin = self.find_template(template_name) if not hasattr(template, "render"): # template needs to be compiled template = Template(template, origin, template_name, engine=self) if not partial_name: return template extra_data = getattr(template, "extra_data", {}) try: partial = extra_data["partials"][partial_name] except (KeyError, TypeError): raise TemplateDoesNotExist(partial_name, tried=[template_name]) partial.engine = self return partial def render_to_string(self, template_name, context=None): """ Render the template specified by template_name with the given context. For use in Django's test suite. """ if isinstance(template_name, (list, tuple)): t = self.select_template(template_name) else: t = self.get_template(template_name) # Django < 1.8 accepted a Context in `context` even though that's # unintended. Preserve this ability but don't rewrap `context`. if isinstance(context, Context): return t.render(context) else: return t.render(Context(context, autoescape=self.autoescape)) def select_template(self, template_name_list): """ Given a list of template names, return the first that can be loaded. """ if not template_name_list: raise TemplateDoesNotExist("No template names provided") not_found = [] for template_name in template_name_list: try: return self.get_template(template_name) except TemplateDoesNotExist as exc: if exc.args[0] not in not_found: not_found.append(exc.args[0]) continue # If we get here, none of the templates could be loaded raise TemplateDoesNotExist(", ".join(not_found))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/library.py
django/template/library.py
from collections.abc import Iterable from functools import wraps from importlib import import_module from inspect import getfullargspec, unwrap from django.utils.html import conditional_escape from django.utils.inspect import lazy_annotations from .base import Node, Template, token_kwargs from .exceptions import TemplateSyntaxError class InvalidTemplateLibrary(Exception): pass class Library: """ A class for registering template tags and filters. Compiled filter and template tag functions are stored in the filters and tags attributes. The filter, simple_tag, and inclusion_tag methods provide a convenient way to register callables as tags. """ def __init__(self): self.filters = {} self.tags = {} def tag(self, name=None, compile_function=None): if name is None and compile_function is None: # @register.tag() return self.tag_function elif name is not None and compile_function is None: if callable(name): # @register.tag return self.tag_function(name) else: # @register.tag('somename') or @register.tag(name='somename') def dec(func): return self.tag(name, func) return dec elif name is not None and compile_function is not None: # register.tag('somename', somefunc) self.tags[name] = compile_function return compile_function else: raise ValueError( "Unsupported arguments to Library.tag: (%r, %r)" % (name, compile_function), ) def tag_function(self, func): self.tags[func.__name__] = func return func def filter(self, name=None, filter_func=None, **flags): """ Register a callable as a template filter. Example: @register.filter def lower(value): return value.lower() """ if name is None and filter_func is None: # @register.filter() def dec(func): return self.filter_function(func, **flags) return dec elif name is not None and filter_func is None: if callable(name): # @register.filter return self.filter_function(name, **flags) else: # @register.filter('somename') or # @register.filter(name='somename') def dec(func): return self.filter(name, func, **flags) return dec elif name is not None and filter_func is not None: # register.filter('somename', somefunc) self.filters[name] = filter_func for attr in ("expects_localtime", "is_safe", "needs_autoescape"): if attr in flags: value = flags[attr] # set the flag on the filter for FilterExpression.resolve setattr(filter_func, attr, value) # set the flag on the innermost decorated function # for decorators that need it, e.g. stringfilter setattr(unwrap(filter_func), attr, value) filter_func._filter_name = name return filter_func else: raise ValueError( "Unsupported arguments to Library.filter: (%r, %r)" % (name, filter_func), ) def filter_function(self, func, **flags): return self.filter(func.__name__, func, **flags) def simple_tag(self, func=None, takes_context=None, name=None): """ Register a callable as a compiled template tag. Example: @register.simple_tag def hello(*args, **kwargs): return 'world' """ def dec(func): with lazy_annotations(): ( params, varargs, varkw, defaults, kwonly, kwonly_defaults, _, ) = getfullargspec(unwrap(func)) function_name = name or func.__name__ if takes_context: if params and params[0] == "context": del params[0] else: raise TemplateSyntaxError( f"{function_name!r} is decorated with takes_context=True so it " "must have a first argument of 'context'" ) @wraps(func) def compile_func(parser, token): bits = token.split_contents()[1:] target_var = None if len(bits) >= 2 and bits[-2] == "as": target_var = bits[-1] bits = bits[:-2] args, kwargs = parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, function_name, ) return SimpleNode(func, takes_context, args, kwargs, target_var) self.tag(function_name, compile_func) return func if func is None: # @register.simple_tag(...) return dec elif callable(func): # @register.simple_tag return dec(func) else: raise ValueError("Invalid arguments provided to simple_tag") def simple_block_tag(self, func=None, takes_context=None, name=None, end_name=None): """ Register a callable as a compiled block template tag. Example: @register.simple_block_tag def hello(content): return 'world' """ def dec(func): nonlocal end_name with lazy_annotations(): ( params, varargs, varkw, defaults, kwonly, kwonly_defaults, _, ) = getfullargspec(unwrap(func)) function_name = name or func.__name__ if end_name is None: end_name = f"end{function_name}" if takes_context: if len(params) >= 2 and params[1] == "content": del params[1] else: raise TemplateSyntaxError( f"{function_name!r} is decorated with takes_context=True so" " it must have a first argument of 'context' and a second " "argument of 'content'" ) if params and params[0] == "context": del params[0] else: raise TemplateSyntaxError( f"{function_name!r} is decorated with takes_context=True so it " "must have a first argument of 'context'" ) elif params and params[0] == "content": del params[0] else: raise TemplateSyntaxError( f"{function_name!r} must have a first argument of 'content'" ) @wraps(func) def compile_func(parser, token): bits = token.split_contents()[1:] target_var = None if len(bits) >= 2 and bits[-2] == "as": target_var = bits[-1] bits = bits[:-2] nodelist = parser.parse((end_name,)) parser.delete_first_token() args, kwargs = parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, function_name, ) return SimpleBlockNode( nodelist, func, takes_context, args, kwargs, target_var ) self.tag(function_name, compile_func) return func if func is None: # @register.simple_block_tag(...) return dec elif callable(func): # @register.simple_block_tag return dec(func) else: raise ValueError("Invalid arguments provided to simple_block_tag") def inclusion_tag(self, filename, func=None, takes_context=None, name=None): """ Register a callable as an inclusion tag: @register.inclusion_tag('results.html') def show_results(poll): choices = poll.choice_set.all() return {'choices': choices} """ def dec(func): with lazy_annotations(): ( params, varargs, varkw, defaults, kwonly, kwonly_defaults, _, ) = getfullargspec(unwrap(func)) function_name = name or func.__name__ if takes_context: if params and params[0] == "context": params = params[1:] else: raise TemplateSyntaxError( f"{function_name!r} is decorated with takes_context=True so it " "must have a first argument of 'context'" ) @wraps(func) def compile_func(parser, token): bits = token.split_contents()[1:] args, kwargs = parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, function_name, ) return InclusionNode( func, takes_context, args, kwargs, filename, ) self.tag(function_name, compile_func) return func return dec class TagHelperNode(Node): """ Base class for tag helper nodes such as SimpleNode and InclusionNode. Manages the positional and keyword arguments to be passed to the decorated function. """ def __init__(self, func, takes_context, args, kwargs): self.func = func self.takes_context = takes_context self.args = args self.kwargs = kwargs def get_resolved_arguments(self, context): resolved_args = [var.resolve(context) for var in self.args] if self.takes_context: resolved_args = [context, *resolved_args] resolved_kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} return resolved_args, resolved_kwargs class SimpleNode(TagHelperNode): child_nodelists = () def __init__(self, func, takes_context, args, kwargs, target_var): super().__init__(func, takes_context, args, kwargs) self.target_var = target_var def render(self, context): resolved_args, resolved_kwargs = self.get_resolved_arguments(context) output = self.func(*resolved_args, **resolved_kwargs) if self.target_var is not None: context[self.target_var] = output return "" if context.autoescape: output = conditional_escape(output) return output class SimpleBlockNode(SimpleNode): def __init__(self, nodelist, *args, **kwargs): super().__init__(*args, **kwargs) self.nodelist = nodelist def get_resolved_arguments(self, context): resolved_args, resolved_kwargs = super().get_resolved_arguments(context) # Restore the "content" argument. # It will move depending on whether takes_context was passed. resolved_args.insert( 1 if self.takes_context else 0, self.nodelist.render(context) ) return resolved_args, resolved_kwargs class InclusionNode(TagHelperNode): def __init__(self, func, takes_context, args, kwargs, filename): super().__init__(func, takes_context, args, kwargs) self.filename = filename def render(self, context): """ Render the specified template and context. Cache the template object in render_context to avoid reparsing and loading when used in a for loop. """ resolved_args, resolved_kwargs = self.get_resolved_arguments(context) _dict = self.func(*resolved_args, **resolved_kwargs) t = context.render_context.get(self) if t is None: if isinstance(self.filename, Template): t = self.filename elif isinstance(getattr(self.filename, "template", None), Template): t = self.filename.template elif not isinstance(self.filename, str) and isinstance( self.filename, Iterable ): t = context.template.engine.select_template(self.filename) else: t = context.template.engine.get_template(self.filename) context.render_context[self] = t new_context = context.new(_dict) # Copy across the CSRF token, if present, because inclusion tags are # often used for forms, and we need instructions for using CSRF # protection to be as simple as possible. csrf_token = context.get("csrf_token") if csrf_token is not None: new_context["csrf_token"] = csrf_token return t.render(new_context) def parse_bits( parser, bits, params, varargs, varkw, defaults, kwonly, kwonly_defaults, name, ): """ Parse bits for template tag helpers simple_tag and inclusion_tag, in particular by detecting syntax errors and by extracting positional and keyword arguments. """ args = [] kwargs = {} unhandled_params = list(params) unhandled_kwargs = [ kwarg for kwarg in kwonly if not kwonly_defaults or kwarg not in kwonly_defaults ] for bit in bits: # First we try to extract a potential kwarg from the bit kwarg = token_kwargs([bit], parser) if kwarg: # The kwarg was successfully extracted param, value = kwarg.popitem() if param not in params and param not in kwonly and varkw is None: # An unexpected keyword argument was supplied raise TemplateSyntaxError( "'%s' received unexpected keyword argument '%s'" % (name, param) ) elif param in kwargs: # The keyword argument has already been supplied once raise TemplateSyntaxError( "'%s' received multiple values for keyword argument '%s'" % (name, param) ) else: # All good, record the keyword argument kwargs[str(param)] = value if param in unhandled_params: # If using the keyword syntax for a positional arg, then # consume it. unhandled_params.remove(param) elif param in unhandled_kwargs: # Same for keyword-only arguments unhandled_kwargs.remove(param) else: if kwargs: raise TemplateSyntaxError( "'%s' received some positional argument(s) after some " "keyword argument(s)" % name ) else: # Record the positional argument args.append(parser.compile_filter(bit)) try: # Consume from the list of expected positional arguments unhandled_params.pop(0) except IndexError: if varargs is None: raise TemplateSyntaxError( "'%s' received too many positional arguments" % name ) if defaults is not None: # Consider the last n params handled, where n is the # number of defaults. unhandled_params = unhandled_params[: -len(defaults)] if unhandled_params or unhandled_kwargs: # Some positional arguments were not supplied raise TemplateSyntaxError( "'%s' did not receive value(s) for the argument(s): %s" % (name, ", ".join("'%s'" % p for p in unhandled_params + unhandled_kwargs)) ) return args, kwargs def import_library(name): """ Load a Library object from a template tag module. """ try: module = import_module(name) except ImportError as e: raise InvalidTemplateLibrary( "Invalid template library specified. ImportError raised when " "trying to load '%s': %s" % (name, e) ) try: return module.register except AttributeError: raise InvalidTemplateLibrary( "Module %s does not have a variable named 'register'" % name, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/defaulttags.py
django/template/defaulttags.py
"""Default tags used by the template system, available to all templates.""" import re import sys import warnings from collections import namedtuple from collections.abc import Iterable, Mapping from datetime import datetime from itertools import cycle as itertools_cycle from itertools import groupby from django.conf import settings from django.http import QueryDict from django.utils import timezone from django.utils.datastructures import DeferredSubDict from django.utils.html import conditional_escape, escape, format_html from django.utils.lorem_ipsum import paragraphs, words from django.utils.safestring import mark_safe from .base import ( BLOCK_TAG_END, BLOCK_TAG_START, COMMENT_TAG_END, COMMENT_TAG_START, FILTER_SEPARATOR, SINGLE_BRACE_END, SINGLE_BRACE_START, VARIABLE_ATTRIBUTE_SEPARATOR, VARIABLE_TAG_END, VARIABLE_TAG_START, Node, NodeList, PartialTemplate, TemplateSyntaxError, VariableDoesNotExist, kwarg_re, render_value_in_context, token_kwargs, ) from .context import Context from .defaultfilters import date from .library import Library from .smartif import IfParser, Literal register = Library() class AutoEscapeControlNode(Node): """Implement the actions of the autoescape tag.""" def __init__(self, setting, nodelist): self.setting = setting self.nodelist = nodelist def render(self, context): old_setting = context.autoescape context.autoescape = self.setting output = self.nodelist.render(context) context.autoescape = old_setting if self.setting: return mark_safe(output) else: return output class CommentNode(Node): child_nodelists = () def render(self, context): return "" class CsrfTokenNode(Node): child_nodelists = () def render(self, context): csrf_token = context.get("csrf_token") if csrf_token: if csrf_token == "NOTPROVIDED": return format_html("") else: return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}">', csrf_token, ) else: # It's very probable that the token is missing because of # misconfiguration, so we raise a warning if settings.DEBUG: warnings.warn( "A {% csrf_token %} was used in a template, but the context " "did not provide the value. This is usually caused by not " "using RequestContext." ) return "" class CycleNode(Node): def __init__(self, cyclevars, variable_name=None, silent=False): self.cyclevars = cyclevars self.variable_name = variable_name self.silent = silent def render(self, context): if self not in context.render_context: # First time the node is rendered in template context.render_context[self] = itertools_cycle(self.cyclevars) cycle_iter = context.render_context[self] value = next(cycle_iter).resolve(context) if self.variable_name: context.set_upward(self.variable_name, value) if self.silent: return "" return render_value_in_context(value, context) def reset(self, context): """ Reset the cycle iteration back to the beginning. """ context.render_context[self] = itertools_cycle(self.cyclevars) class DebugNode(Node): def render(self, context): if not settings.DEBUG: return "" from pprint import pformat output = [escape(pformat(val)) for val in context] output.append("\n\n") output.append(escape(pformat(sys.modules))) return "".join(output) class FilterNode(Node): def __init__(self, filter_expr, nodelist): self.filter_expr = filter_expr self.nodelist = nodelist def render(self, context): output = self.nodelist.render(context) # Apply filters. with context.push(var=output): return self.filter_expr.resolve(context) class FirstOfNode(Node): def __init__(self, variables, asvar=None): self.vars = variables self.asvar = asvar def render(self, context): first = "" for var in self.vars: value = var.resolve(context, ignore_failures=True) if value: first = render_value_in_context(value, context) break if self.asvar: context[self.asvar] = first return "" return first class ForNode(Node): child_nodelists = ("nodelist_loop", "nodelist_empty") def __init__( self, loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty=None ): self.loopvars = loopvars self.sequence = sequence self.is_reversed = is_reversed self.nodelist_loop = nodelist_loop if nodelist_empty is None: self.nodelist_empty = NodeList() else: self.nodelist_empty = nodelist_empty def __repr__(self): reversed_text = " reversed" if self.is_reversed else "" return "<%s: for %s in %s, tail_len: %d%s>" % ( self.__class__.__name__, ", ".join(self.loopvars), self.sequence, len(self.nodelist_loop), reversed_text, ) def render(self, context): if "forloop" in context: parentloop = context["forloop"] else: parentloop = {} with context.push(): values = self.sequence.resolve(context, ignore_failures=True) if values is None: values = [] if not hasattr(values, "__len__"): values = list(values) len_values = len(values) if len_values < 1: return self.nodelist_empty.render(context) nodelist = [] if self.is_reversed: values = reversed(values) num_loopvars = len(self.loopvars) unpack = num_loopvars > 1 # Create a forloop value in the context. We'll update counters on # each iteration just below. loop_dict = context["forloop"] = { "parentloop": parentloop, "length": len_values, } for i, item in enumerate(values): # Shortcuts for current loop iteration number. loop_dict["counter0"] = i loop_dict["counter"] = i + 1 # Reverse counter iteration numbers. loop_dict["revcounter"] = len_values - i loop_dict["revcounter0"] = len_values - i - 1 # Boolean values designating first and last times through loop. loop_dict["first"] = i == 0 loop_dict["last"] = i == len_values - 1 pop_context = False if unpack: # If there are multiple loop variables, unpack the item # into them. try: len_item = len(item) except TypeError: # not an iterable len_item = 1 # Check loop variable count before unpacking if num_loopvars != len_item: raise ValueError( "Need {} values to unpack in for loop; got {}. ".format( num_loopvars, len_item ), ) unpacked_vars = dict(zip(self.loopvars, item)) pop_context = True context.update(unpacked_vars) else: context[self.loopvars[0]] = item for node in self.nodelist_loop: nodelist.append(node.render_annotated(context)) if pop_context: # Pop the loop variables pushed on to the context to avoid # the context ending up in an inconsistent state when other # tags (e.g., include and with) push data to context. context.pop() return mark_safe("".join(nodelist)) class IfChangedNode(Node): child_nodelists = ("nodelist_true", "nodelist_false") def __init__(self, nodelist_true, nodelist_false, *varlist): self.nodelist_true = nodelist_true self.nodelist_false = nodelist_false self._varlist = varlist def render(self, context): # Init state storage state_frame = self._get_context_stack_frame(context) state_frame.setdefault(self) nodelist_true_output = None if self._varlist: # Consider multiple parameters. This behaves like an OR evaluation # of the multiple variables. compare_to = [ var.resolve(context, ignore_failures=True) for var in self._varlist ] else: # The "{% ifchanged %}" syntax (without any variables) compares # the rendered output. compare_to = nodelist_true_output = self.nodelist_true.render(context) if compare_to != state_frame[self]: state_frame[self] = compare_to # render true block if not already rendered return nodelist_true_output or self.nodelist_true.render(context) elif self.nodelist_false: return self.nodelist_false.render(context) return "" def _get_context_stack_frame(self, context): # The Context object behaves like a stack where each template tag can # create a new scope. Find the place where to store the state to detect # changes. if "forloop" in context: # Ifchanged is bound to the local for loop. # When there is a loop-in-loop, the state is bound to the inner # loop, so it resets when the outer loop continues. return context["forloop"] else: # Using ifchanged outside loops. Effectively this is a no-op # because the state is associated with 'self'. return context.render_context class IfNode(Node): def __init__(self, conditions_nodelists): self.conditions_nodelists = conditions_nodelists def __repr__(self): return "<%s>" % self.__class__.__name__ def __iter__(self): for _, nodelist in self.conditions_nodelists: yield from nodelist @property def nodelist(self): return NodeList(self) def render(self, context): for condition, nodelist in self.conditions_nodelists: if condition is not None: # if / elif clause try: match = condition.eval(context) except VariableDoesNotExist: match = None else: # else clause match = True if match: return nodelist.render(context) return "" class LoremNode(Node): def __init__(self, count, method, common): self.count = count self.method = method self.common = common def render(self, context): try: count = int(self.count.resolve(context)) except (ValueError, TypeError): count = 1 if self.method == "w": return words(count, common=self.common) else: paras = paragraphs(count, common=self.common) if self.method == "p": paras = ["<p>%s</p>" % p for p in paras] return "\n\n".join(paras) GroupedResult = namedtuple("GroupedResult", ["grouper", "list"]) class RegroupNode(Node): def __init__(self, target, expression, var_name): self.target = target self.expression = expression self.var_name = var_name def resolve_expression(self, obj, context): # This method is called for each object in self.target. See regroup() # for the reason why we temporarily put the object in the context. context[self.var_name] = obj return self.expression.resolve(context, ignore_failures=True) def render(self, context): obj_list = self.target.resolve(context, ignore_failures=True) if obj_list is None: # target variable wasn't found in context; fail silently. context[self.var_name] = [] return "" # List of dictionaries in the format: # {'grouper': 'key', 'list': [list of contents]}. context[self.var_name] = [ GroupedResult(grouper=key, list=list(val)) for key, val in groupby( obj_list, lambda obj: self.resolve_expression(obj, context) ) ] return "" class LoadNode(Node): child_nodelists = () def render(self, context): return "" class NowNode(Node): def __init__(self, format_string, asvar=None): self.format_string = format_string self.asvar = asvar def render(self, context): tzinfo = timezone.get_current_timezone() if settings.USE_TZ else None formatted = date(datetime.now(tz=tzinfo), self.format_string) if self.asvar: context[self.asvar] = formatted return "" else: return formatted class PartialDefNode(Node): def __init__(self, partial_name, inline, nodelist): self.partial_name = partial_name self.inline = inline self.nodelist = nodelist def render(self, context): return self.nodelist.render(context) if self.inline else "" class PartialNode(Node): def __init__(self, partial_name, partial_mapping): # Defer lookup in `partial_mapping` and nodelist to runtime. self.partial_name = partial_name self.partial_mapping = partial_mapping def render(self, context): try: return self.partial_mapping[self.partial_name].render(context) except KeyError: raise TemplateSyntaxError( f"Partial '{self.partial_name}' is not defined in the current template." ) class ResetCycleNode(Node): def __init__(self, node): self.node = node def render(self, context): self.node.reset(context) return "" class SpacelessNode(Node): def __init__(self, nodelist): self.nodelist = nodelist def render(self, context): from django.utils.html import strip_spaces_between_tags return strip_spaces_between_tags(self.nodelist.render(context).strip()) class TemplateTagNode(Node): mapping = { "openblock": BLOCK_TAG_START, "closeblock": BLOCK_TAG_END, "openvariable": VARIABLE_TAG_START, "closevariable": VARIABLE_TAG_END, "openbrace": SINGLE_BRACE_START, "closebrace": SINGLE_BRACE_END, "opencomment": COMMENT_TAG_START, "closecomment": COMMENT_TAG_END, } def __init__(self, tagtype): self.tagtype = tagtype def render(self, context): return self.mapping.get(self.tagtype, "") class URLNode(Node): child_nodelists = () def __init__(self, view_name, args, kwargs, asvar): self.view_name = view_name self.args = args self.kwargs = kwargs self.asvar = asvar def __repr__(self): return "<%s view_name='%s' args=%s kwargs=%s as=%s>" % ( self.__class__.__qualname__, self.view_name, repr(self.args), repr(self.kwargs), repr(self.asvar), ) def render(self, context): from django.urls import NoReverseMatch, reverse args = [arg.resolve(context) for arg in self.args] kwargs = {k: v.resolve(context) for k, v in self.kwargs.items()} view_name = self.view_name.resolve(context) try: current_app = context.request.current_app except AttributeError: try: current_app = context.request.resolver_match.namespace except AttributeError: current_app = None # Try to look up the URL. If it fails, raise NoReverseMatch unless the # {% url ... as var %} construct is used, in which case return nothing. url = "" try: url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app) except NoReverseMatch: if self.asvar is None: raise if self.asvar: context[self.asvar] = url return "" else: if context.autoescape: url = conditional_escape(url) return url class VerbatimNode(Node): def __init__(self, content): self.content = content def render(self, context): return self.content class WidthRatioNode(Node): def __init__(self, val_expr, max_expr, max_width, asvar=None): self.val_expr = val_expr self.max_expr = max_expr self.max_width = max_width self.asvar = asvar def render(self, context): try: value = self.val_expr.resolve(context) max_value = self.max_expr.resolve(context) max_width = int(self.max_width.resolve(context)) except VariableDoesNotExist: return "" except (ValueError, TypeError): raise TemplateSyntaxError("widthratio final argument must be a number") try: value = float(value) max_value = float(max_value) ratio = (value / max_value) * max_width result = str(round(ratio)) except ZeroDivisionError: result = "0" except (ValueError, TypeError, OverflowError): result = "" if self.asvar: context[self.asvar] = result return "" else: return result class WithNode(Node): def __init__(self, var, name, nodelist, extra_context=None): self.nodelist = nodelist # var and name are legacy attributes, being left in case they are used # by third-party subclasses of this Node. self.extra_context = extra_context or {} if name: self.extra_context[name] = var def __repr__(self): return "<%s>" % self.__class__.__name__ def render(self, context): values = {key: val.resolve(context) for key, val in self.extra_context.items()} with context.push(**values): return self.nodelist.render(context) @register.tag def autoescape(parser, token): """ Force autoescape behavior for this block. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. args = token.contents.split() if len(args) != 2: raise TemplateSyntaxError("'autoescape' tag requires exactly one argument.") arg = args[1] if arg not in ("on", "off"): raise TemplateSyntaxError("'autoescape' argument should be 'on' or 'off'") nodelist = parser.parse(("endautoescape",)) parser.delete_first_token() return AutoEscapeControlNode((arg == "on"), nodelist) @register.tag def comment(parser, token): """ Ignore everything between ``{% comment %}`` and ``{% endcomment %}``. """ parser.skip_past("endcomment") return CommentNode() @register.tag def cycle(parser, token): """ Cycle among the given strings each time this tag is encountered. Within a loop, cycles among the given strings each time through the loop:: {% for o in some_list %} <tr class="{% cycle 'row1' 'row2' %}"> ... </tr> {% endfor %} Outside of a loop, give the values a unique name the first time you call it, then use that name each successive time through:: <tr class="{% cycle 'row1' 'row2' 'row3' as rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> <tr class="{% cycle rowcolors %}">...</tr> You can use any number of values, separated by spaces. Commas can also be used to separate values; if a comma is used, the cycle values are interpreted as literal strings. The optional flag "silent" can be used to prevent the cycle declaration from returning any value:: {% for o in some_list %} {% cycle 'row1' 'row2' as rowcolors silent %} <tr class="{{ rowcolors }}">{% include "subtemplate.html " %}</tr> {% endfor %} """ # Note: This returns the exact same node on each {% cycle name %} call; # that is, the node object returned from {% cycle a b c as name %} and the # one returned from {% cycle name %} are the exact same object. This # shouldn't cause problems (heh), but if it does, now you know. # # Ugly hack warning: This stuffs the named template dict into parser so # that names are only unique within each template (as opposed to using # a global variable, which would make cycle names have to be unique across # *all* templates. # # It keeps the last node in the parser to be able to reset it with # {% resetcycle %}. args = token.split_contents() if len(args) < 2: raise TemplateSyntaxError("'cycle' tag requires at least two arguments") if len(args) == 2: # {% cycle foo %} case. name = args[1] if not hasattr(parser, "_named_cycle_nodes"): raise TemplateSyntaxError( "No named cycles in template. '%s' is not defined" % name ) if name not in parser._named_cycle_nodes: raise TemplateSyntaxError("Named cycle '%s' does not exist" % name) return parser._named_cycle_nodes[name] as_form = False if len(args) > 4: # {% cycle ... as foo [silent] %} case. if args[-3] == "as": if args[-1] != "silent": raise TemplateSyntaxError( "Only 'silent' flag is allowed after cycle's name, not '%s'." % args[-1] ) as_form = True silent = True args = args[:-1] elif args[-2] == "as": as_form = True silent = False if as_form: name = args[-1] values = [parser.compile_filter(arg) for arg in args[1:-2]] node = CycleNode(values, name, silent=silent) if not hasattr(parser, "_named_cycle_nodes"): parser._named_cycle_nodes = {} parser._named_cycle_nodes[name] = node else: values = [parser.compile_filter(arg) for arg in args[1:]] node = CycleNode(values) parser._last_cycle_node = node return node @register.tag def csrf_token(parser, token): return CsrfTokenNode() @register.tag def debug(parser, token): """ Output a whole load of debugging information, including the current context and imported modules. Sample usage:: <pre> {% debug %} </pre> """ return DebugNode() @register.tag("filter") def do_filter(parser, token): """ Filter the contents of the block through variable filters. Filters can also be piped through each other, and they can have arguments -- just like in variable syntax. Sample usage:: {% filter force_escape|lower %} This text will be HTML-escaped, and will appear in lowercase. {% endfilter %} Note that the ``escape`` and ``safe`` filters are not acceptable arguments. Instead, use the ``autoescape`` tag to manage autoescaping for blocks of template code. """ # token.split_contents() isn't useful here because this tag doesn't accept # variable as arguments. _, rest = token.contents.split(None, 1) filter_expr = parser.compile_filter("var|%s" % (rest)) for func, unused in filter_expr.filters: filter_name = getattr(func, "_filter_name", None) if filter_name in ("escape", "safe"): raise TemplateSyntaxError( '"filter %s" is not permitted. Use the "autoescape" tag instead.' % filter_name ) nodelist = parser.parse(("endfilter",)) parser.delete_first_token() return FilterNode(filter_expr, nodelist) @register.tag def firstof(parser, token): """ Output the first variable passed that is not False. Output nothing if all the passed variables are False. Sample usage:: {% firstof var1 var2 var3 as myvar %} This is equivalent to:: {% if var1 %} {{ var1 }} {% elif var2 %} {{ var2 }} {% elif var3 %} {{ var3 }} {% endif %} but much cleaner! You can also use a literal string as a fallback value in case all passed variables are False:: {% firstof var1 var2 var3 "fallback value" %} If you want to disable auto-escaping of variables you can use:: {% autoescape off %} {% firstof var1 var2 var3 "<strong>fallback value</strong>" %} {% autoescape %} Or if only some variables should be escaped, you can use:: {% firstof var1 var2|safe var3 "<strong>fallback</strong>"|safe %} """ bits = token.split_contents()[1:] asvar = None if not bits: raise TemplateSyntaxError("'firstof' statement requires at least one argument") if len(bits) >= 2 and bits[-2] == "as": asvar = bits[-1] bits = bits[:-2] return FirstOfNode([parser.compile_filter(bit) for bit in bits], asvar) @register.tag("for") def do_for(parser, token): """ Loop over each item in an array. For example, to display a list of athletes given ``athlete_list``:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} </ul> You can loop over a list in reverse by using ``{% for obj in list reversed %}``. You can also unpack multiple values from a two-dimensional array:: {% for key,value in dict.items %} {{ key }}: {{ value }} {% endfor %} The ``for`` tag can take an optional ``{% empty %}`` clause that will be displayed if the given array is empty or could not be found:: <ul> {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% empty %} <li>Sorry, no athletes in this list.</li> {% endfor %} <ul> The above is equivalent to -- but shorter, cleaner, and possibly faster than -- the following:: <ul> {% if athlete_list %} {% for athlete in athlete_list %} <li>{{ athlete.name }}</li> {% endfor %} {% else %} <li>Sorry, no athletes in this list.</li> {% endif %} </ul> The for loop sets a number of variables available within the loop: ======================= ============================================== Variable Description ======================= ============================================== ``forloop.counter`` The current iteration of the loop (1-indexed) ``forloop.counter0`` The current iteration of the loop (0-indexed) ``forloop.revcounter`` The number of iterations from the end of the loop (1-indexed) ``forloop.revcounter0`` The number of iterations from the end of the loop (0-indexed) ``forloop.first`` True if this is the first time through the loop ``forloop.last`` True if this is the last time through the loop ``forloop.parentloop`` For nested loops, this is the loop "above" the current one ======================= ============================================== """ bits = token.split_contents() if len(bits) < 4: raise TemplateSyntaxError( "'for' statements should have at least four words: %s" % token.contents ) is_reversed = bits[-1] == "reversed" in_index = -3 if is_reversed else -2 if bits[in_index] != "in": raise TemplateSyntaxError( "'for' statements should use the format" " 'for x in y': %s" % token.contents ) invalid_chars = frozenset((" ", '"', "'", FILTER_SEPARATOR)) loopvars = re.split(r" *, *", " ".join(bits[1:in_index])) for var in loopvars: if not var or not invalid_chars.isdisjoint(var): raise TemplateSyntaxError( "'for' tag received an invalid argument: %s" % token.contents ) sequence = parser.compile_filter(bits[in_index + 1]) nodelist_loop = parser.parse( ( "empty", "endfor", ) ) token = parser.next_token() if token.contents == "empty": nodelist_empty = parser.parse(("endfor",)) parser.delete_first_token() else: nodelist_empty = None return ForNode(loopvars, sequence, is_reversed, nodelist_loop, nodelist_empty) class TemplateLiteral(Literal): def __init__(self, value, text): self.value = value self.text = text # for better error messages def display(self): return self.text def eval(self, context): return self.value.resolve(context, ignore_failures=True) class TemplateIfParser(IfParser): error_class = TemplateSyntaxError def __init__(self, parser, *args, **kwargs): self.template_parser = parser super().__init__(*args, **kwargs) def create_var(self, value): return TemplateLiteral(self.template_parser.compile_filter(value), value) @register.tag("if") def do_if(parser, token): """ Evaluate a variable, and if that variable is "true" (i.e., exists, is not empty, and is not a false boolean value), output the contents of the block: :: {% if athlete_list %} Number of athletes: {{ athlete_list|count }} {% elif athlete_in_locker_room_list %} Athletes should be out of the locker room soon! {% else %} No athletes. {% endif %} In the above, if ``athlete_list`` is not empty, the number of athletes will be displayed by the ``{{ athlete_list|count }}`` variable. The ``if`` tag may take one or several `` {% elif %}`` clauses, as well as an ``{% else %}`` clause that will be displayed if all previous conditions fail. These clauses are optional. ``if`` tags may use ``or``, ``and`` or ``not`` to test a number of variables or to negate a given variable:: {% if not athlete_list %} There are no athletes. {% endif %} {% if athlete_list or coach_list %} There are some athletes or some coaches. {% endif %} {% if athlete_list and coach_list %} Both athletes and coaches are available. {% endif %} {% if not athlete_list or coach_list %} There are no athletes, or there are some coaches. {% endif %} {% if athlete_list and not coach_list %} There are some athletes and absolutely no coaches. {% endif %} Comparison operators are also available, and the use of filters is also allowed, for example:: {% if articles|length >= 5 %}...{% endif %} Arguments and operators _must_ have a space between them, so ``{% if 1>2 %}`` is not a valid if tag. All supported operators are: ``or``, ``and``, ``in``, ``not in`` ``==``, ``!=``, ``>``, ``>=``, ``<`` and ``<=``. Operator precedence follows Python. """ # {% if ... %} bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(("elif", "else", "endif")) conditions_nodelists = [(condition, nodelist)] token = parser.next_token() # {% elif ... %} (repeatable) while token.contents.startswith("elif"): bits = token.split_contents()[1:] condition = TemplateIfParser(parser, bits).parse() nodelist = parser.parse(("elif", "else", "endif")) conditions_nodelists.append((condition, nodelist)) token = parser.next_token() # {% else %} (optional) if token.contents == "else": nodelist = parser.parse(("endif",)) conditions_nodelists.append((None, nodelist)) token = parser.next_token() # {% endif %}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/dummy.py
django/template/backends/dummy.py
import string from django.core.exceptions import ImproperlyConfigured from django.template import Origin, TemplateDoesNotExist from django.utils.html import conditional_escape from .base import BaseEngine from .utils import csrf_input_lazy, csrf_token_lazy class TemplateStrings(BaseEngine): app_dirname = "template_strings" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() if options: raise ImproperlyConfigured("Unknown options: {}".format(", ".join(options))) super().__init__(params) def from_string(self, template_code): return Template(template_code) def get_template(self, template_name): tried = [] for template_file in self.iter_template_filenames(template_name): try: with open(template_file, encoding="utf-8") as fp: template_code = fp.read() except FileNotFoundError: tried.append( ( Origin(template_file, template_name, self), "Source does not exist", ) ) else: return Template(template_code) raise TemplateDoesNotExist(template_name, tried=tried, backend=self) class Template(string.Template): def render(self, context=None, request=None): if context is None: context = {} else: context = {k: conditional_escape(v) for k, v in context.items()} if request is not None: context["csrf_input"] = csrf_input_lazy(request) context["csrf_token"] = csrf_token_lazy(request) return self.safe_substitute(context)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/utils.py
django/template/backends/utils.py
from django.middleware.csrf import get_token from django.utils.functional import lazy from django.utils.html import format_html from django.utils.safestring import SafeString def csrf_input(request): return format_html( '<input type="hidden" name="csrfmiddlewaretoken" value="{}">', get_token(request), ) csrf_input_lazy = lazy(csrf_input, SafeString, str) csrf_token_lazy = lazy(get_token, str)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/django.py
django/template/backends/django.py
from collections import defaultdict from importlib import import_module from pkgutil import walk_packages from django.apps import apps from django.conf import settings from django.core.checks import Error, Warning from django.template import TemplateDoesNotExist from django.template.context import make_context from django.template.engine import Engine from django.template.library import InvalidTemplateLibrary from .base import BaseEngine class DjangoTemplates(BaseEngine): app_dirname = "templates" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() options.setdefault("autoescape", True) options.setdefault("debug", settings.DEBUG) options.setdefault("file_charset", "utf-8") libraries = options.get("libraries", {}) options["libraries"] = self.get_templatetag_libraries(libraries) super().__init__(params) self.engine = Engine(self.dirs, self.app_dirs, **options) def check(self, **kwargs): return [ *self._check_string_if_invalid_is_string(), *self._check_for_template_tags_with_the_same_name(), ] def _check_string_if_invalid_is_string(self): value = self.engine.string_if_invalid if not isinstance(value, str): return [ Error( "'string_if_invalid' in TEMPLATES OPTIONS must be a string but " "got: %r (%s)." % (value, type(value)), obj=self, id="templates.E002", ) ] return [] def _check_for_template_tags_with_the_same_name(self): libraries = defaultdict(set) for module_name, module_path in get_template_tag_modules(): libraries[module_name].add(module_path) for module_name, module_path in self.engine.libraries.items(): libraries[module_name].add(module_path) errors = [] for library_name, items in libraries.items(): if len(items) > 1: items = ", ".join(repr(item) for item in sorted(items)) errors.append( Warning( f"{library_name!r} is used for multiple template tag modules: " f"{items}", obj=self, id="templates.W003", ) ) return errors def from_string(self, template_code): return Template(self.engine.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.engine.get_template(template_name), self) except TemplateDoesNotExist as exc: reraise(exc, self) def get_templatetag_libraries(self, custom_libraries): """ Return a collation of template tag libraries from installed applications and the supplied custom_libraries argument. """ libraries = get_installed_libraries() libraries.update(custom_libraries) return libraries class Template: def __init__(self, template, backend): self.template = template self.backend = backend @property def origin(self): return self.template.origin def render(self, context=None, request=None): context = make_context( context, request, autoescape=self.backend.engine.autoescape ) try: return self.template.render(context) except TemplateDoesNotExist as exc: reraise(exc, self.backend) def copy_exception(exc, backend=None): """ Create a new TemplateDoesNotExist. Preserve its declared attributes and template debug data but discard __traceback__, __context__, and __cause__ to make this object suitable for keeping around (in a cache, for example). """ backend = backend or exc.backend new = exc.__class__(*exc.args, tried=exc.tried, backend=backend, chain=exc.chain) if hasattr(exc, "template_debug"): new.template_debug = exc.template_debug return new def reraise(exc, backend): """ Reraise TemplateDoesNotExist while maintaining template debug information. """ new = copy_exception(exc, backend) raise new from exc def get_template_tag_modules(): """ Yield (module_name, module_path) pairs for all installed template tag libraries. """ candidates = ["django.templatetags"] candidates.extend( f"{app_config.name}.templatetags" for app_config in apps.get_app_configs() ) for candidate in candidates: try: pkg = import_module(candidate) except ImportError: # No templatetags package defined. This is safe to ignore. continue if hasattr(pkg, "__path__"): for name in get_package_libraries(pkg): yield name.removeprefix(candidate).lstrip("."), name def get_installed_libraries(): """ Return the built-in template tag libraries and those from installed applications. Libraries are stored in a dictionary where keys are the individual module names, not the full module paths. Example: django.templatetags.i18n is stored as i18n. """ return { module_name: full_name for module_name, full_name in get_template_tag_modules() } def get_package_libraries(pkg): """ Recursively yield template tag libraries defined in submodules of a package. """ for entry in walk_packages(pkg.__path__, pkg.__name__ + "."): try: module = import_module(entry[1]) except ImportError as e: raise InvalidTemplateLibrary( "Invalid template library specified. ImportError raised when " "trying to load '%s': %s" % (entry[1], e) ) from e if hasattr(module, "register"): yield entry[1]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/__init__.py
django/template/backends/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/base.py
django/template/backends/base.py
from django.core.exceptions import ImproperlyConfigured, SuspiciousFileOperation from django.template.utils import get_app_template_dirs from django.utils._os import safe_join from django.utils.functional import cached_property class BaseEngine: # Core methods: engines have to provide their own implementation # (except for from_string which is optional). def __init__(self, params): """ Initialize the template engine. `params` is a dict of configuration settings. """ params = params.copy() self.name = params.pop("NAME") self.dirs = list(params.pop("DIRS")) self.app_dirs = params.pop("APP_DIRS") if params: raise ImproperlyConfigured( "Unknown parameters: {}".format(", ".join(params)) ) def check(self, **kwargs): return [] @property def app_dirname(self): raise ImproperlyConfigured( "{} doesn't support loading templates from installed " "applications.".format(self.__class__.__name__) ) def from_string(self, template_code): """ Create and return a template for the given source code. This method is optional. """ raise NotImplementedError( "subclasses of BaseEngine should provide a from_string() method" ) def get_template(self, template_name): """ Load and return a template for the given name. Raise TemplateDoesNotExist if no such template exists. """ raise NotImplementedError( "subclasses of BaseEngine must provide a get_template() method" ) # Utility methods: they are provided to minimize code duplication and # security issues in third-party backends. @cached_property def template_dirs(self): """ Return a list of directories to search for templates. """ # Immutable return value because it's cached and shared by callers. template_dirs = tuple(self.dirs) if self.app_dirs: template_dirs += get_app_template_dirs(self.app_dirname) return template_dirs def iter_template_filenames(self, template_name): """ Iterate over candidate files for template_name. Ignore files that don't lie inside configured template dirs to avoid directory traversal attacks. """ for template_dir in self.template_dirs: try: yield safe_join(template_dir, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/backends/jinja2.py
django/template/backends/jinja2.py
from pathlib import Path import jinja2 from django.conf import settings from django.template import TemplateDoesNotExist, TemplateSyntaxError from django.utils.functional import cached_property from django.utils.module_loading import import_string from .base import BaseEngine from .utils import csrf_input_lazy, csrf_token_lazy class Jinja2(BaseEngine): app_dirname = "jinja2" def __init__(self, params): params = params.copy() options = params.pop("OPTIONS").copy() super().__init__(params) self.context_processors = options.pop("context_processors", []) environment = options.pop("environment", "jinja2.Environment") environment_cls = import_string(environment) if "loader" not in options: options["loader"] = jinja2.FileSystemLoader(self.template_dirs) options.setdefault("autoescape", True) options.setdefault("auto_reload", settings.DEBUG) options.setdefault( "undefined", jinja2.DebugUndefined if settings.DEBUG else jinja2.Undefined ) self.env = environment_cls(**options) def from_string(self, template_code): return Template(self.env.from_string(template_code), self) def get_template(self, template_name): try: return Template(self.env.get_template(template_name), self) except jinja2.TemplateNotFound as exc: raise TemplateDoesNotExist(exc.name, backend=self) from exc except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc @cached_property def template_context_processors(self): return [import_string(path) for path in self.context_processors] class Template: def __init__(self, template, backend): self.template = template self.backend = backend self.origin = Origin( name=template.filename, template_name=template.name, ) def render(self, context=None, request=None): if context is None: context = {} if request is not None: context["request"] = request context["csrf_input"] = csrf_input_lazy(request) context["csrf_token"] = csrf_token_lazy(request) for context_processor in self.backend.template_context_processors: context.update(context_processor(request)) try: return self.template.render(context) except jinja2.TemplateSyntaxError as exc: new = TemplateSyntaxError(exc.args) new.template_debug = get_exception_info(exc) raise new from exc class Origin: """ A container to hold debug information as described in the template API documentation. """ def __init__(self, name, template_name): self.name = name self.template_name = template_name def get_exception_info(exception): """ Format exception information for display on the debug page using the structure described in the template API documentation. """ context_lines = 10 lineno = exception.lineno source = exception.source if source is None: exception_file = Path(exception.filename) if exception_file.exists(): source = exception_file.read_text() if source is not None: lines = list(enumerate(source.strip().split("\n"), start=1)) during = lines[lineno - 1][1] total = len(lines) top = max(0, lineno - context_lines - 1) bottom = min(total, lineno + context_lines) else: during = "" lines = [] total = top = bottom = 0 return { "name": exception.filename, "message": exception.message, "source_lines": lines[top:bottom], "line": lineno, "before": "", "during": during, "after": "", "total": total, "top": top, "bottom": bottom, }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/filesystem.py
django/template/loaders/filesystem.py
""" Wrapper for loading templates from the filesystem. """ from django.core.exceptions import SuspiciousFileOperation from django.template import Origin, TemplateDoesNotExist from django.utils._os import safe_join from .base import Loader as BaseLoader class Loader(BaseLoader): def __init__(self, engine, dirs=None): super().__init__(engine) self.dirs = dirs def get_dirs(self): return self.dirs if self.dirs is not None else self.engine.dirs def get_contents(self, origin): try: with open(origin.name, encoding=self.engine.file_charset) as fp: return fp.read() except FileNotFoundError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name): """ Return an Origin object pointing to an absolute path in each directory in template_dirs. For security reasons, if a path doesn't lie inside one of the template_dirs it is excluded from the result set. """ for template_dir in self.get_dirs(): try: name = safe_join(template_dir, template_name) except SuspiciousFileOperation: # The joined path was located outside of this template_dir # (it might be inside another one, so this isn't fatal). continue yield Origin( name=name, template_name=template_name, loader=self, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/app_directories.py
django/template/loaders/app_directories.py
""" Wrapper for loading templates from "templates" directories in INSTALLED_APPS packages. """ from django.template.utils import get_app_template_dirs from .filesystem import Loader as FilesystemLoader class Loader(FilesystemLoader): def get_dirs(self): return get_app_template_dirs("templates")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/locmem.py
django/template/loaders/locmem.py
""" Wrapper for loading templates from a plain Python dict. """ from django.template import Origin, TemplateDoesNotExist from .base import Loader as BaseLoader class Loader(BaseLoader): def __init__(self, engine, templates_dict): self.templates_dict = templates_dict super().__init__(engine) def get_contents(self, origin): try: return self.templates_dict[origin.name] except KeyError: raise TemplateDoesNotExist(origin) def get_template_sources(self, template_name): yield Origin( name=template_name, template_name=template_name, loader=self, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/__init__.py
django/template/loaders/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/cached.py
django/template/loaders/cached.py
""" Wrapper class that takes a list of template loaders as an argument and attempts to load templates from them in order, caching the result. """ import hashlib from django.template import TemplateDoesNotExist from django.template.backends.django import copy_exception from .base import Loader as BaseLoader class Loader(BaseLoader): def __init__(self, engine, loaders): self.get_template_cache = {} self.loaders = engine.get_template_loaders(loaders) super().__init__(engine) def get_dirs(self): for loader in self.loaders: if hasattr(loader, "get_dirs"): yield from loader.get_dirs() def get_contents(self, origin): return origin.loader.get_contents(origin) def get_template(self, template_name, skip=None): """ Perform the caching that gives this loader its name. Often many of the templates attempted will be missing, so memory use is of concern here. To keep it in check, caching behavior is a little complicated when a template is not found. See ticket #26306 for more details. With template debugging disabled, cache the TemplateDoesNotExist class for every missing template and raise a new instance of it after fetching it from the cache. With template debugging enabled, a unique TemplateDoesNotExist object is cached for each missing template to preserve debug data. When raising an exception, Python sets __traceback__, __context__, and __cause__ attributes on it. Those attributes can contain references to all sorts of objects up the call chain and caching them creates a memory leak. Thus, unraised copies of the exceptions are cached and copies of those copies are raised after they're fetched from the cache. """ key = self.cache_key(template_name, skip) cached = self.get_template_cache.get(key) if cached: if isinstance(cached, type) and issubclass(cached, TemplateDoesNotExist): raise cached(template_name) elif isinstance(cached, TemplateDoesNotExist): raise copy_exception(cached) return cached try: template = super().get_template(template_name, skip) except TemplateDoesNotExist as e: self.get_template_cache[key] = ( copy_exception(e) if self.engine.debug else TemplateDoesNotExist ) raise else: self.get_template_cache[key] = template return template def get_template_sources(self, template_name): for loader in self.loaders: yield from loader.get_template_sources(template_name) def cache_key(self, template_name, skip=None): """ Generate a cache key for the template name and skip. If skip is provided, only origins that match template_name are included in the cache key. This ensures each template is only parsed and cached once if contained in different extend chains like: x -> a -> a y -> a -> a z -> a -> a """ skip_prefix = "" if skip: matching = [ origin.name for origin in skip if origin.template_name == template_name ] if matching: skip_prefix = self.generate_hash(matching) return "-".join(s for s in (str(template_name), skip_prefix) if s) def generate_hash(self, values): return hashlib.sha1("|".join(values).encode()).hexdigest() def reset(self): "Empty the template cache." self.get_template_cache.clear()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loaders/base.py
django/template/loaders/base.py
from django.template import Template, TemplateDoesNotExist class Loader: def __init__(self, engine): self.engine = engine def get_template(self, template_name, skip=None): """ Call self.get_template_sources() and return a Template object for the first template matching template_name. If skip is provided, ignore template origins in skip. This is used to avoid recursion during template extending. """ tried = [] for origin in self.get_template_sources(template_name): if skip is not None and origin in skip: tried.append((origin, "Skipped to avoid recursion")) continue try: contents = self.get_contents(origin) except TemplateDoesNotExist: tried.append((origin, "Source does not exist")) continue else: return Template( contents, origin, origin.template_name, self.engine, ) raise TemplateDoesNotExist(template_name, tried=tried) def get_template_sources(self, template_name): """ An iterator that yields possible matching template paths for a template name. """ raise NotImplementedError( "subclasses of Loader must provide a get_template_sources() method" ) def reset(self): """ Reset any state maintained by the loader instance (e.g. cached templates or cached loader modules). """ pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/paginator.py
django/core/paginator.py
import collections.abc import inspect import warnings from math import ceil from asgiref.sync import iscoroutinefunction, sync_to_async from django.utils.deprecation import RemovedInDjango70Warning from django.utils.functional import cached_property from django.utils.inspect import method_has_no_args from django.utils.translation import gettext_lazy as _ class UnorderedObjectListWarning(RuntimeWarning): pass class InvalidPage(Exception): pass class PageNotAnInteger(InvalidPage): pass class EmptyPage(InvalidPage): pass class BasePaginator: # Translators: String used to replace omitted page numbers in elided page # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10]. ELLIPSIS = _("…") default_error_messages = { "invalid_page": _("That page number is not an integer"), "min_page": _("That page number is less than 1"), "no_results": _("That page contains no results"), } def __init__( self, object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None, ): self.object_list = object_list self._check_object_list_is_ordered() self.per_page = int(per_page) self.orphans = int(orphans) self.allow_empty_first_page = allow_empty_first_page self.error_messages = ( self.default_error_messages if error_messages is None else self.default_error_messages | error_messages ) if self.per_page <= self.orphans: # RemovedInDjango70Warning: When the deprecation ends, replace # with: # raise ValueError( # "The orphans argument cannot be larger than or equal to the " # "per_page argument." # ) msg = ( "Support for the orphans argument being larger than or equal to the " "per_page argument is deprecated. This will raise a ValueError in " "Django 7.0." ) warnings.warn(msg, category=RemovedInDjango70Warning, stacklevel=2) def _check_object_list_is_ordered(self): """ Warn if self.object_list is unordered (typically a QuerySet). """ ordered = getattr(self.object_list, "ordered", None) if ordered is not None and not ordered: obj_list_repr = ( "{} {}".format( self.object_list.model, self.object_list.__class__.__name__ ) if hasattr(self.object_list, "model") else "{!r}".format(self.object_list) ) warnings.warn( "Pagination may yield inconsistent results with an unordered " "object_list: {}.".format(obj_list_repr), UnorderedObjectListWarning, stacklevel=3, ) def _get_elided_page_range( self, number, num_pages, page_range, on_each_side=3, on_ends=2 ): """ Return a 1-based range of pages with some values elided. If the page range is larger than a given size, the whole range is not provided and a compact form is returned instead, e.g. for a paginator with 50 pages, if page 43 were the current page, the output, with the default arguments, would be: 1, 2, …, 40, 41, 42, 43, 44, 45, 46, …, 49, 50. """ if num_pages <= (on_each_side + on_ends) * 2: for page in page_range: yield page return if number > (1 + on_each_side + on_ends) + 1: for page in range(1, on_ends + 1): yield page yield self.ELLIPSIS for page in range(number - on_each_side, number + 1): yield page else: for page in range(1, number + 1): yield page if number < (num_pages - on_each_side - on_ends) - 1: for page in range(number + 1, number + on_each_side + 1): yield page yield self.ELLIPSIS for page in range(num_pages - on_ends + 1, num_pages + 1): yield page else: for page in range(number + 1, num_pages + 1): yield page def _get_page(self, *args, **kwargs): """ Return an instance of a single page. This hook can be used by subclasses to use an alternative to the standard :cls:`Page` object. """ return Page(*args, **kwargs) def _validate_number(self, number, num_pages): """Validate the given 1-based page number.""" try: if isinstance(number, float) and not number.is_integer(): raise ValueError number = int(number) except (TypeError, ValueError): raise PageNotAnInteger(self.error_messages["invalid_page"]) if number < 1: raise EmptyPage(self.error_messages["min_page"]) if number > num_pages: raise EmptyPage(self.error_messages["no_results"]) return number class Paginator(BasePaginator): def __iter__(self): for page_number in self.page_range: yield self.page(page_number) def validate_number(self, number): return self._validate_number(number, self.num_pages) def get_page(self, number): """ Return a valid page, even if the page argument isn't a number or isn't in range. """ try: number = self.validate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = self.num_pages return self.page(number) def page(self, number): """Return a Page object for the given 1-based page number.""" number = self.validate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page if top + self.orphans >= self.count: top = self.count return self._get_page(self.object_list[bottom:top], number, self) @cached_property def count(self): """Return the total number of objects, across all pages.""" c = getattr(self.object_list, "count", None) if callable(c) and not inspect.isbuiltin(c) and method_has_no_args(c): return c() return len(self.object_list) @cached_property def num_pages(self): """Return the total number of pages.""" if self.count == 0 and not self.allow_empty_first_page: return 0 hits = max(1, self.count - self.orphans) return ceil(hits / self.per_page) @property def page_range(self): """ Return a 1-based range of pages for iterating through within a template for loop. """ return range(1, self.num_pages + 1) def get_elided_page_range(self, number=1, *, on_each_side=3, on_ends=2): number = self.validate_number(number) yield from self._get_elided_page_range( number, self.num_pages, self.page_range, on_each_side, on_ends ) class AsyncPaginator(BasePaginator): def __init__( self, object_list, per_page, orphans=0, allow_empty_first_page=True, error_messages=None, ): super().__init__( object_list, per_page, orphans, allow_empty_first_page, error_messages ) self._cache_acount = None self._cache_anum_pages = None async def __aiter__(self): page_range = await self.apage_range() for page_number in page_range: yield await self.apage(page_number) async def avalidate_number(self, number): num_pages = await self.anum_pages() return self._validate_number(number, num_pages) async def aget_page(self, number): """See Paginator.get_page().""" try: number = await self.avalidate_number(number) except PageNotAnInteger: number = 1 except EmptyPage: number = await self.anum_pages() return await self.apage(number) async def apage(self, number): """See Paginator.page().""" number = await self.avalidate_number(number) bottom = (number - 1) * self.per_page top = bottom + self.per_page count = await self.acount() if top + self.orphans >= count: top = count return self._get_page(self.object_list[bottom:top], number, self) def _get_page(self, *args, **kwargs): return AsyncPage(*args, **kwargs) async def acount(self): """See Paginator.count().""" if self._cache_acount is not None: return self._cache_acount c = getattr(self.object_list, "acount", None) if ( iscoroutinefunction(c) and not inspect.isbuiltin(c) and method_has_no_args(c) ): count = await c() else: count = len(self.object_list) self._cache_acount = count return count async def anum_pages(self): """See Paginator.num_pages().""" if self._cache_anum_pages is not None: return self._cache_anum_pages count = await self.acount() if count == 0 and not self.allow_empty_first_page: self._cache_anum_pages = 0 return self._cache_anum_pages hits = max(1, count - self.orphans) num_pages = ceil(hits / self.per_page) self._cache_anum_pages = num_pages return num_pages async def apage_range(self): """See Paginator.page_range()""" num_pages = await self.anum_pages() return range(1, num_pages + 1) async def aget_elided_page_range(self, number=1, *, on_each_side=3, on_ends=2): number = await self.avalidate_number(number) num_pages = await self.anum_pages() page_range = await self.apage_range() for page in self._get_elided_page_range( number, num_pages, page_range, on_each_side, on_ends ): yield page class Page(collections.abc.Sequence): def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return "<Page %s of %s>" % (self.number, self.paginator.num_pages) def __len__(self): return len(self.object_list) def __getitem__(self, index): if not isinstance(index, (int, slice)): raise TypeError( "Page indices must be integers or slices, not %s." % type(index).__name__ ) # The object_list is converted to a list so that if it was a QuerySet # it won't be a database hit per __getitem__. if not isinstance(self.object_list, list): self.object_list = list(self.object_list) return self.object_list[index] def has_next(self): return self.number < self.paginator.num_pages def has_previous(self): return self.number > 1 def has_other_pages(self): return self.has_previous() or self.has_next() def next_page_number(self): return self.paginator.validate_number(self.number + 1) def previous_page_number(self): return self.paginator.validate_number(self.number - 1) def start_index(self): """ Return the 1-based index of the first object on this page, relative to total objects in the paginator. """ # Special case, return zero if no items. if self.paginator.count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 def end_index(self): """ Return the 1-based index of the last object on this page, relative to total objects found (hits). """ # Special case for the last page because there can be orphans. if self.number == self.paginator.num_pages: return self.paginator.count return self.number * self.paginator.per_page class AsyncPage: def __init__(self, object_list, number, paginator): self.object_list = object_list self.number = number self.paginator = paginator def __repr__(self): return "<Async Page %s>" % self.number async def __aiter__(self): if hasattr(self.object_list, "__aiter__"): async for obj in self.object_list: yield obj else: for obj in self.object_list: yield obj def __len__(self): if not isinstance(self.object_list, list): raise TypeError( "AsyncPage.aget_object_list() must be awaited before calling len()." ) return len(self.object_list) def __reversed__(self): if not isinstance(self.object_list, list): raise TypeError( "AsyncPage.aget_object_list() " "must be awaited before calling reversed()." ) return reversed(self.object_list) def __getitem__(self, index): if not isinstance(index, (int, slice)): raise TypeError( "AsyncPage indices must be integers or slices, not %s." % type(index).__name__ ) if not isinstance(self.object_list, list): raise TypeError( "AsyncPage.aget_object_list() must be awaited before using indexing." ) return self.object_list[index] async def aget_object_list(self): """ Returns self.object_list as a list. This method must be awaited before AsyncPage can be treated as a sequence of self.object_list. """ if not isinstance(self.object_list, list): if hasattr(self.object_list, "__aiter__"): self.object_list = [obj async for obj in self.object_list] else: self.object_list = await sync_to_async(list)(self.object_list) return self.object_list async def ahas_next(self): num_pages = await self.paginator.anum_pages() return self.number < num_pages async def ahas_previous(self): return self.number > 1 async def ahas_other_pages(self): has_previous = await self.ahas_previous() has_next = await self.ahas_next() return has_previous or has_next async def anext_page_number(self): return await self.paginator.avalidate_number(self.number + 1) async def aprevious_page_number(self): return await self.paginator.avalidate_number(self.number - 1) async def astart_index(self): """See Page.start_index().""" count = await self.paginator.acount() if count == 0: return 0 return (self.paginator.per_page * (self.number - 1)) + 1 async def aend_index(self): """See Page.end_index().""" num_pages = await self.paginator.anum_pages() if self.number == num_pages: return await self.paginator.acount() return self.number * self.paginator.per_page
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/signals.py
django/core/signals.py
from django.dispatch import Signal request_started = Signal() request_finished = Signal() got_request_exception = Signal() setting_changed = Signal()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/signing.py
django/core/signing.py
""" Functions for creating and restoring url-safe signed JSON objects. The format used looks like this: >>> signing.dumps("hello") 'ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk' There are two components here, separated by a ':'. The first component is a URLsafe base64 encoded JSON of the object passed to dumps(). The second component is a base64 encoded hmac/SHA-256 hash of "$first_component:$secret" signing.loads(s) checks the signature and returns the deserialized object. If the signature fails, a BadSignature exception is raised. >>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk") 'hello' >>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified") ... BadSignature: Signature "ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified" does not match You can optionally compress the JSON prior to base64 encoding it to save space, using the compress=True argument. This checks if compression actually helps and only applies compression if the result is a shorter string: >>> signing.dumps(list(range(1, 20)), compress=True) '.eJwFwcERACAIwLCF-rCiILN47r-GyZVJsNgkxaFxoDgxcOHGxMKD_T7vhAml:1QaUaL:BA0thEZrp4FQVXIXuOvYJtLJSrQ' The fact that the string is compressed is signalled by the prefixed '.' at the start of the base64 JSON. There are 65 url-safe characters: the 64 used by url-safe base64 and the ':'. These functions make use of all of them. """ import base64 import datetime import json import time import zlib from django.conf import settings from django.utils.crypto import constant_time_compare, salted_hmac from django.utils.encoding import force_bytes from django.utils.module_loading import import_string from django.utils.regex_helper import _lazy_re_compile _SEP_UNSAFE = _lazy_re_compile(r"^[A-z0-9-_=]*$") BASE62_ALPHABET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" class BadSignature(Exception): """Signature does not match.""" pass class SignatureExpired(BadSignature): """Signature timestamp is older than required max_age.""" pass def b62_encode(s): if s == 0: return "0" sign = "-" if s < 0 else "" s = abs(s) encoded = "" while s > 0: s, remainder = divmod(s, 62) encoded = BASE62_ALPHABET[remainder] + encoded return sign + encoded def b62_decode(s): if s == "0": return 0 sign = 1 if s[0] == "-": s = s[1:] sign = -1 decoded = 0 for digit in s: decoded = decoded * 62 + BASE62_ALPHABET.index(digit) return sign * decoded def b64_encode(s): return base64.urlsafe_b64encode(s).strip(b"=") def b64_decode(s): pad = b"=" * (-len(s) % 4) return base64.urlsafe_b64decode(s + pad) def base64_hmac(salt, value, key, algorithm="sha1"): return b64_encode( salted_hmac(salt, value, key, algorithm=algorithm).digest() ).decode() def _cookie_signer_key(key): # SECRET_KEYS items may be str or bytes. return b"django.http.cookies" + force_bytes(key) def get_cookie_signer(salt="django.core.signing.get_cookie_signer"): Signer = import_string(settings.SIGNING_BACKEND) return Signer( key=_cookie_signer_key(settings.SECRET_KEY), fallback_keys=map(_cookie_signer_key, settings.SECRET_KEY_FALLBACKS), salt=salt, ) class JSONSerializer: """ Simple wrapper around json to be used in signing.dumps and signing.loads. """ def dumps(self, obj): return json.dumps(obj, separators=(",", ":")).encode("latin-1") def loads(self, data): return json.loads(data.decode("latin-1")) def dumps( obj, key=None, salt="django.core.signing", serializer=JSONSerializer, compress=False ): """ Return URL-safe, hmac signed base64 compressed JSON string. If key is None, use settings.SECRET_KEY instead. The hmac algorithm is the default Signer algorithm. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. Salt can be used to namespace the hash, so that a signed string is only valid for a given namespace. Leaving this at the default value or re-using a salt value across different parts of your application without good cause is a security risk. The serializer is expected to return a bytestring. """ return TimestampSigner(key=key, salt=salt).sign_object( obj, serializer=serializer, compress=compress ) def loads( s, key=None, salt="django.core.signing", serializer=JSONSerializer, max_age=None, fallback_keys=None, ): """ Reverse of dumps(), raise BadSignature if signature fails. The serializer is expected to accept a bytestring. """ return TimestampSigner( key=key, salt=salt, fallback_keys=fallback_keys ).unsign_object( s, serializer=serializer, max_age=max_age, ) class Signer: def __init__( self, *, key=None, sep=":", salt=None, algorithm=None, fallback_keys=None ): self.key = key or settings.SECRET_KEY self.fallback_keys = ( fallback_keys if fallback_keys is not None else settings.SECRET_KEY_FALLBACKS ) self.sep = sep self.salt = salt or "%s.%s" % ( self.__class__.__module__, self.__class__.__name__, ) self.algorithm = algorithm or "sha256" if _SEP_UNSAFE.match(self.sep): raise ValueError( "Unsafe Signer separator: %r (cannot be empty or consist of " "only A-z0-9-_=)" % sep, ) def signature(self, value, key=None): key = key or self.key return base64_hmac(self.salt + "signer", value, key, algorithm=self.algorithm) def sign(self, value): return "%s%s%s" % (value, self.sep, self.signature(value)) def unsign(self, signed_value): if self.sep not in signed_value: raise BadSignature('No "%s" found in value' % self.sep) value, sig = signed_value.rsplit(self.sep, 1) for key in [self.key, *self.fallback_keys]: if constant_time_compare(sig, self.signature(value, key)): return value raise BadSignature('Signature "%s" does not match' % sig) def sign_object(self, obj, serializer=JSONSerializer, compress=False): """ Return URL-safe, hmac signed base64 compressed JSON string. If compress is True (not the default), check if compressing using zlib can save some space. Prepend a '.' to signify compression. This is included in the signature, to protect against zip bombs. The serializer is expected to return a bytestring. """ data = serializer().dumps(obj) # Flag for if it's been compressed or not. is_compressed = False if compress: # Avoid zlib dependency unless compress is being used. compressed = zlib.compress(data) if len(compressed) < (len(data) - 1): data = compressed is_compressed = True base64d = b64_encode(data).decode() if is_compressed: base64d = "." + base64d return self.sign(base64d) def unsign_object(self, signed_obj, serializer=JSONSerializer, **kwargs): # Signer.unsign() returns str but base64 and zlib compression operate # on bytes. base64d = self.unsign(signed_obj, **kwargs).encode() decompress = base64d[:1] == b"." if decompress: # It's compressed; uncompress it first. base64d = base64d[1:] data = b64_decode(base64d) if decompress: data = zlib.decompress(data) return serializer().loads(data) class TimestampSigner(Signer): def timestamp(self): return b62_encode(int(time.time())) def sign(self, value): value = "%s%s%s" % (value, self.sep, self.timestamp()) return super().sign(value) def unsign(self, value, max_age=None): """ Retrieve original value and check it wasn't signed more than max_age seconds ago. """ result = super().unsign(value) value, timestamp = result.rsplit(self.sep, 1) timestamp = b62_decode(timestamp) if max_age is not None: if isinstance(max_age, datetime.timedelta): max_age = max_age.total_seconds() # Check timestamp is not older than max_age age = time.time() - timestamp if age > max_age: raise SignatureExpired("Signature age %s > %s seconds" % (age, max_age)) return value
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/exceptions.py
django/core/exceptions.py
""" Global Django exception classes. """ import operator from django.utils.hashable import make_hashable class FieldDoesNotExist(Exception): """The requested model field does not exist""" pass class AppRegistryNotReady(Exception): """The django.apps registry is not populated yet""" pass class ObjectDoesNotExist(Exception): """The requested object does not exist""" silent_variable_failure = True class ObjectNotUpdated(Exception): """The updated object no longer exists.""" class MultipleObjectsReturned(Exception): """The query returned multiple objects when only one was expected.""" pass class SuspiciousOperation(Exception): """The user did something suspicious""" class SuspiciousMultipartForm(SuspiciousOperation): """Suspect MIME request in multipart form data""" pass class SuspiciousFileOperation(SuspiciousOperation): """A Suspicious filesystem operation was attempted""" pass class DisallowedHost(SuspiciousOperation): """HTTP_HOST header contains invalid value""" pass class DisallowedRedirect(SuspiciousOperation): """Redirect was too long or scheme was not in allowed list.""" pass class TooManyFieldsSent(SuspiciousOperation): """ The number of fields in a GET or POST request exceeded settings.DATA_UPLOAD_MAX_NUMBER_FIELDS. """ pass class TooManyFilesSent(SuspiciousOperation): """ The number of fields in a GET or POST request exceeded settings.DATA_UPLOAD_MAX_NUMBER_FILES. """ pass class RequestDataTooBig(SuspiciousOperation): """ The size of the request (excluding any file uploads) exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE. """ pass class RequestAborted(Exception): """The request was closed before it was completed, or timed out.""" pass class BadRequest(Exception): """The request is malformed and cannot be processed.""" pass class PermissionDenied(Exception): """The user did not have permission to do that""" pass class ViewDoesNotExist(Exception): """The requested view does not exist""" pass class MiddlewareNotUsed(Exception): """This middleware is not used in this server configuration""" pass class ImproperlyConfigured(Exception): """Django is somehow improperly configured""" pass class FieldError(Exception): """Some kind of problem with a model field.""" pass class FieldFetchBlocked(FieldError): """On-demand fetching of a model field blocked.""" pass NON_FIELD_ERRORS = "__all__" class ValidationError(Exception): """An error while validating data.""" def __init__(self, message, code=None, params=None): """ The `message` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. What we define as an "error" can be either a simple string or an instance of ValidationError with its message attribute set, and what we define as list or dictionary can be an actual `list` or `dict` or an instance of ValidationError with its `error_list` or `error_dict` attribute set. """ super().__init__(message, code, params) if isinstance(message, ValidationError): if hasattr(message, "error_dict"): message = message.error_dict elif not hasattr(message, "message"): message = message.error_list else: message, code, params = message.message, message.code, message.params if isinstance(message, dict): self.error_dict = {} for field, messages in message.items(): if not isinstance(messages, ValidationError): messages = ValidationError(messages) self.error_dict[field] = messages.error_list elif isinstance(message, list): self.error_list = [] for message in message: # Normalize plain strings to instances of ValidationError. if not isinstance(message, ValidationError): message = ValidationError(message) if hasattr(message, "error_dict"): self.error_list.extend(sum(message.error_dict.values(), [])) else: self.error_list.extend(message.error_list) else: self.message = message self.code = code self.params = params self.error_list = [self] @property def message_dict(self): # Trigger an AttributeError if this ValidationError # doesn't have an error_dict. getattr(self, "error_dict") return dict(self) @property def messages(self): if hasattr(self, "error_dict"): return sum(dict(self).values(), []) return list(self) def update_error_dict(self, error_dict): if hasattr(self, "error_dict"): for field, error_list in self.error_dict.items(): error_dict.setdefault(field, []).extend(error_list) else: error_dict.setdefault(NON_FIELD_ERRORS, []).extend(self.error_list) return error_dict def __iter__(self): if hasattr(self, "error_dict"): for field, errors in self.error_dict.items(): yield field, list(ValidationError(errors)) else: for error in self.error_list: message = error.message if error.params: message %= error.params yield str(message) def __str__(self): if hasattr(self, "error_dict"): return repr(dict(self)) return repr(list(self)) def __repr__(self): return "ValidationError(%s)" % self def __eq__(self, other): if not isinstance(other, ValidationError): return NotImplemented return hash(self) == hash(other) def __hash__(self): if hasattr(self, "message"): return hash( ( self.message, self.code, make_hashable(self.params), ) ) if hasattr(self, "error_dict"): return hash(make_hashable(self.error_dict)) return hash(tuple(sorted(self.error_list, key=operator.attrgetter("message")))) class EmptyResultSet(Exception): """A database query predicate is impossible.""" pass class FullResultSet(Exception): """A database query predicate is matches everything.""" pass class SynchronousOnlyOperation(Exception): """The user tried to call a sync-only function from an async context.""" pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/validators.py
django/core/validators.py
import ipaddress import math import re from pathlib import Path from urllib.parse import urlsplit from django.core.exceptions import ValidationError from django.utils.deconstruct import deconstructible from django.utils.http import MAX_URL_LENGTH from django.utils.ipv6 import is_valid_ipv6_address from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy # These values, if given to validate(), will trigger the self.required check. EMPTY_VALUES = (None, "", [], (), {}) @deconstructible class RegexValidator: regex = "" message = _("Enter a valid value.") code = "invalid" inverse_match = False flags = 0 def __init__( self, regex=None, message=None, code=None, inverse_match=None, flags=None ): if regex is not None: self.regex = regex if message is not None: self.message = message if code is not None: self.code = code if inverse_match is not None: self.inverse_match = inverse_match if flags is not None: self.flags = flags if self.flags and not isinstance(self.regex, str): raise TypeError( "If the flags are set, regex must be a regular expression string." ) self.regex = _lazy_re_compile(self.regex, self.flags) def __call__(self, value): """ Validate that the input contains (or does *not* contain, if inverse_match is True) a match for the regular expression. """ regex_matches = self.regex.search(str(value)) invalid_input = regex_matches if self.inverse_match else not regex_matches if invalid_input: raise ValidationError(self.message, code=self.code, params={"value": value}) def __eq__(self, other): return ( isinstance(other, RegexValidator) and self.regex.pattern == other.regex.pattern and self.regex.flags == other.regex.flags and (self.message == other.message) and (self.code == other.code) and (self.inverse_match == other.inverse_match) ) @deconstructible class DomainNameValidator(RegexValidator): message = _("Enter a valid domain name.") ul = "\u00a1-\uffff" # Unicode letters range (must not be a raw string). # Host patterns. hostname_re = ( r"[a-z" + ul + r"0-9](?:[a-z" + ul + r"0-9-]{0,61}[a-z" + ul + r"0-9])?" ) # Max length for domain name labels is 63 characters per RFC 1034 sec. 3.1. domain_re = r"(?:\.(?!-)[a-z" + ul + r"0-9-]{1,63}(?<!-))*" # Top-level domain. tld_no_fqdn_re = ( r"\." # dot r"(?!-)" # can't start with a dash r"(?:[a-z" + ul + "-]{2,63}" # domain label r"|xn--[a-z0-9]{1,59})" # or punycode label r"(?<!-)" # can't end with a dash ) tld_re = tld_no_fqdn_re + r"\.?" ascii_only_hostname_re = r"[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?" ascii_only_domain_re = r"(?:\.(?!-)[a-zA-Z0-9-]{1,63}(?<!-))*" ascii_only_tld_re = ( r"\." # dot r"(?!-)" # can't start with a dash r"(?:[a-zA-Z0-9-]{2,63})" # domain label r"(?<!-)" # can't end with a dash r"\.?" # may have a trailing dot ) max_length = 255 def __init__(self, **kwargs): self.accept_idna = kwargs.pop("accept_idna", True) if self.accept_idna: self.regex = _lazy_re_compile( r"^" + self.hostname_re + self.domain_re + self.tld_re + r"$", re.IGNORECASE, ) else: self.regex = _lazy_re_compile( r"^" + self.ascii_only_hostname_re + self.ascii_only_domain_re + self.ascii_only_tld_re + r"$", re.IGNORECASE, ) super().__init__(**kwargs) def __call__(self, value): if not isinstance(value, str) or len(value) > self.max_length: raise ValidationError(self.message, code=self.code, params={"value": value}) if not self.accept_idna and not value.isascii(): raise ValidationError(self.message, code=self.code, params={"value": value}) super().__call__(value) validate_domain_name = DomainNameValidator() @deconstructible class URLValidator(RegexValidator): # IP patterns ipv4_re = ( r"(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)" r"(?:\.(?:0|25[0-5]|2[0-4][0-9]|1[0-9]?[0-9]?|[1-9][0-9]?)){3}" ) ipv6_re = r"\[[0-9a-f:.]+\]" # (simple regex, validated later) hostname_re = DomainNameValidator.hostname_re domain_re = DomainNameValidator.domain_re tld_re = DomainNameValidator.tld_re host_re = "(" + hostname_re + domain_re + tld_re + "|localhost)" regex = _lazy_re_compile( r"^(?:[a-z0-9.+-]*)://" # scheme is validated separately r"(?:[^\s:@/]+(?::[^\s:@/]*)?@)?" # user:pass authentication r"(?:" + ipv4_re + "|" + ipv6_re + "|" + host_re + ")" r"(?::[0-9]{1,5})?" # port r"(?:[/?#][^\s]*)?" # resource path r"\Z", re.IGNORECASE, ) message = _("Enter a valid URL.") schemes = ["http", "https", "ftp", "ftps"] unsafe_chars = frozenset("\t\r\n") max_length = MAX_URL_LENGTH def __init__(self, schemes=None, **kwargs): super().__init__(**kwargs) if schemes is not None: self.schemes = schemes def __call__(self, value): if not isinstance(value, str) or len(value) > self.max_length: raise ValidationError(self.message, code=self.code, params={"value": value}) if self.unsafe_chars.intersection(value): raise ValidationError(self.message, code=self.code, params={"value": value}) # Check if the scheme is valid. scheme = value.split("://")[0].lower() if scheme not in self.schemes: raise ValidationError(self.message, code=self.code, params={"value": value}) # Then check full URL try: splitted_url = urlsplit(value) except ValueError: raise ValidationError(self.message, code=self.code, params={"value": value}) super().__call__(value) # Now verify IPv6 in the netloc part host_match = re.search(r"^\[(.+)\](?::[0-9]{1,5})?$", splitted_url.netloc) if host_match: potential_ip = host_match[1] try: validate_ipv6_address(potential_ip) except ValidationError: raise ValidationError( self.message, code=self.code, params={"value": value} ) # The maximum length of a full host name is 253 characters per RFC 1034 # section 3.1. It's defined to be 255 bytes or less, but this includes # one byte for the length of the name and one byte for the trailing dot # that's used to indicate absolute names in DNS. if splitted_url.hostname is None or len(splitted_url.hostname) > 253: raise ValidationError(self.message, code=self.code, params={"value": value}) integer_validator = RegexValidator( _lazy_re_compile(r"^-?\d+\Z"), message=_("Enter a valid integer."), code="invalid", ) def validate_integer(value): return integer_validator(value) @deconstructible class EmailValidator: message = _("Enter a valid email address.") code = "invalid" hostname_re = DomainNameValidator.hostname_re domain_re = DomainNameValidator.domain_re tld_no_fqdn_re = DomainNameValidator.tld_no_fqdn_re user_regex = _lazy_re_compile( # dot-atom r"(^[-!#$%&'*+/=?^_`{}|~0-9A-Z]+(\.[-!#$%&'*+/=?^_`{}|~0-9A-Z]+)*\Z" # quoted-string r'|^"([\001-\010\013\014\016-\037!#-\[\]-\177]|\\[\001-\011\013\014\016-\177])' r'*"\Z)', re.IGNORECASE, ) domain_regex = _lazy_re_compile( r"^" + hostname_re + domain_re + tld_no_fqdn_re + r"\Z", re.IGNORECASE, ) literal_regex = _lazy_re_compile( # literal form, ipv4 or ipv6 address (SMTP 4.1.3) r"\[([A-F0-9:.]+)\]\Z", re.IGNORECASE, ) domain_allowlist = ["localhost"] def __init__(self, message=None, code=None, allowlist=None): if message is not None: self.message = message if code is not None: self.code = code if allowlist is not None: self.domain_allowlist = allowlist def __call__(self, value): # The maximum length of an email is 320 characters per RFC 3696 # section 3. if not value or "@" not in value or len(value) > 320: raise ValidationError(self.message, code=self.code, params={"value": value}) user_part, domain_part = value.rsplit("@", 1) if not self.user_regex.match(user_part): raise ValidationError(self.message, code=self.code, params={"value": value}) if domain_part not in self.domain_allowlist and not self.validate_domain_part( domain_part ): raise ValidationError(self.message, code=self.code, params={"value": value}) def validate_domain_part(self, domain_part): if self.domain_regex.match(domain_part): return True literal_match = self.literal_regex.match(domain_part) if literal_match: ip_address = literal_match[1] try: validate_ipv46_address(ip_address) return True except ValidationError: pass return False def __eq__(self, other): return ( isinstance(other, EmailValidator) and (set(self.domain_allowlist) == set(other.domain_allowlist)) and (self.message == other.message) and (self.code == other.code) ) validate_email = EmailValidator() slug_re = _lazy_re_compile(r"^[-a-zA-Z0-9_]+\Z") validate_slug = RegexValidator( slug_re, # Translators: "letters" means latin letters: a-z and A-Z. _("Enter a valid “slug” consisting of letters, numbers, underscores or hyphens."), "invalid", ) slug_unicode_re = _lazy_re_compile(r"^[-\w]+\Z") validate_unicode_slug = RegexValidator( slug_unicode_re, _( "Enter a valid “slug” consisting of Unicode letters, numbers, underscores, or " "hyphens." ), "invalid", ) def validate_ipv4_address(value): try: ipaddress.IPv4Address(value) except ValueError: raise ValidationError( _("Enter a valid %(protocol)s address."), code="invalid", params={"protocol": _("IPv4"), "value": value}, ) def validate_ipv6_address(value): if not is_valid_ipv6_address(value): raise ValidationError( _("Enter a valid %(protocol)s address."), code="invalid", params={"protocol": _("IPv6"), "value": value}, ) def validate_ipv46_address(value): try: validate_ipv4_address(value) except ValidationError: try: validate_ipv6_address(value) except ValidationError: raise ValidationError( _("Enter a valid %(protocol)s address."), code="invalid", params={"protocol": _("IPv4 or IPv6"), "value": value}, ) ip_address_validator_map = { "both": [validate_ipv46_address], "ipv4": [validate_ipv4_address], "ipv6": [validate_ipv6_address], } def ip_address_validators(protocol, unpack_ipv4): """ Depending on the given parameters, return the appropriate validators for the GenericIPAddressField. """ if protocol != "both" and unpack_ipv4: raise ValueError( "You can only use `unpack_ipv4` if `protocol` is set to 'both'" ) try: return ip_address_validator_map[protocol.lower()] except KeyError: raise ValueError( "The protocol '%s' is unknown. Supported: %s" % (protocol, list(ip_address_validator_map)) ) def int_list_validator(sep=",", message=None, code="invalid", allow_negative=False): regexp = _lazy_re_compile( r"^%(neg)s\d+(?:%(sep)s%(neg)s\d+)*\Z" % { "neg": "(-)?" if allow_negative else "", "sep": re.escape(sep), } ) return RegexValidator(regexp, message=message, code=code) validate_comma_separated_integer_list = int_list_validator( message=_("Enter only digits separated by commas."), ) @deconstructible class BaseValidator: message = _("Ensure this value is %(limit_value)s (it is %(show_value)s).") code = "limit_value" def __init__(self, limit_value, message=None): self.limit_value = limit_value if message: self.message = message def __call__(self, value): cleaned = self.clean(value) limit_value = ( self.limit_value() if callable(self.limit_value) else self.limit_value ) params = {"limit_value": limit_value, "show_value": cleaned, "value": value} if self.compare(cleaned, limit_value): raise ValidationError(self.message, code=self.code, params=params) def __eq__(self, other): if not isinstance(other, self.__class__): return NotImplemented return ( self.limit_value == other.limit_value and self.message == other.message and self.code == other.code ) def compare(self, a, b): return a is not b def clean(self, x): return x @deconstructible class MaxValueValidator(BaseValidator): message = _("Ensure this value is less than or equal to %(limit_value)s.") code = "max_value" def compare(self, a, b): return a > b @deconstructible class MinValueValidator(BaseValidator): message = _("Ensure this value is greater than or equal to %(limit_value)s.") code = "min_value" def compare(self, a, b): return a < b @deconstructible class StepValueValidator(BaseValidator): message = _("Ensure this value is a multiple of step size %(limit_value)s.") code = "step_size" def __init__(self, limit_value, message=None, offset=None): super().__init__(limit_value, message) if offset is not None: self.message = _( "Ensure this value is a multiple of step size %(limit_value)s, " "starting from %(offset)s, e.g. %(offset)s, %(valid_value1)s, " "%(valid_value2)s, and so on." ) self.offset = offset def __call__(self, value): if self.offset is None: super().__call__(value) else: cleaned = self.clean(value) limit_value = ( self.limit_value() if callable(self.limit_value) else self.limit_value ) if self.compare(cleaned, limit_value): offset = cleaned.__class__(self.offset) params = { "limit_value": limit_value, "offset": offset, "valid_value1": offset + limit_value, "valid_value2": offset + 2 * limit_value, } raise ValidationError(self.message, code=self.code, params=params) def compare(self, a, b): offset = 0 if self.offset is None else self.offset return not math.isclose(math.remainder(a - offset, b), 0, abs_tol=1e-9) @deconstructible class MinLengthValidator(BaseValidator): message = ngettext_lazy( "Ensure this value has at least %(limit_value)d character (it has " "%(show_value)d).", "Ensure this value has at least %(limit_value)d characters (it has " "%(show_value)d).", "limit_value", ) code = "min_length" def compare(self, a, b): return a < b def clean(self, x): return len(x) @deconstructible class MaxLengthValidator(BaseValidator): message = ngettext_lazy( "Ensure this value has at most %(limit_value)d character (it has " "%(show_value)d).", "Ensure this value has at most %(limit_value)d characters (it has " "%(show_value)d).", "limit_value", ) code = "max_length" def compare(self, a, b): return a > b def clean(self, x): return len(x) @deconstructible class DecimalValidator: """ Validate that the input does not exceed the maximum number of digits expected, otherwise raise ValidationError. """ messages = { "invalid": _("Enter a number."), "max_digits": ngettext_lazy( "Ensure that there are no more than %(max)s digit in total.", "Ensure that there are no more than %(max)s digits in total.", "max", ), "max_decimal_places": ngettext_lazy( "Ensure that there are no more than %(max)s decimal place.", "Ensure that there are no more than %(max)s decimal places.", "max", ), "max_whole_digits": ngettext_lazy( "Ensure that there are no more than %(max)s digit before the decimal " "point.", "Ensure that there are no more than %(max)s digits before the decimal " "point.", "max", ), } def __init__(self, max_digits, decimal_places): self.max_digits = max_digits self.decimal_places = decimal_places def __call__(self, value): digit_tuple, exponent = value.as_tuple()[1:] if exponent in {"F", "n", "N"}: raise ValidationError( self.messages["invalid"], code="invalid", params={"value": value} ) if exponent >= 0: digits = len(digit_tuple) if digit_tuple != (0,): # A positive exponent adds that many trailing zeros. digits += exponent decimals = 0 else: # If the absolute value of the negative exponent is larger than the # number of digits, then it's the same as the number of digits, # because it'll consume all of the digits in digit_tuple and then # add abs(exponent) - len(digit_tuple) leading zeros after the # decimal point. if abs(exponent) > len(digit_tuple): digits = decimals = abs(exponent) else: digits = len(digit_tuple) decimals = abs(exponent) whole_digits = digits - decimals if self.max_digits is not None and digits > self.max_digits: raise ValidationError( self.messages["max_digits"], code="max_digits", params={"max": self.max_digits, "value": value}, ) if self.decimal_places is not None and decimals > self.decimal_places: raise ValidationError( self.messages["max_decimal_places"], code="max_decimal_places", params={"max": self.decimal_places, "value": value}, ) if ( self.max_digits is not None and self.decimal_places is not None and whole_digits > (self.max_digits - self.decimal_places) ): raise ValidationError( self.messages["max_whole_digits"], code="max_whole_digits", params={"max": (self.max_digits - self.decimal_places), "value": value}, ) def __eq__(self, other): return ( isinstance(other, self.__class__) and self.max_digits == other.max_digits and self.decimal_places == other.decimal_places ) @deconstructible class FileExtensionValidator: message = _( "File extension “%(extension)s” is not allowed. " "Allowed extensions are: %(allowed_extensions)s." ) code = "invalid_extension" def __init__(self, allowed_extensions=None, message=None, code=None): if allowed_extensions is not None: allowed_extensions = [ allowed_extension.lower() for allowed_extension in allowed_extensions ] self.allowed_extensions = allowed_extensions if message is not None: self.message = message if code is not None: self.code = code def __call__(self, value): extension = Path(value.name).suffix[1:].lower() if ( self.allowed_extensions is not None and extension not in self.allowed_extensions ): raise ValidationError( self.message, code=self.code, params={ "extension": extension, "allowed_extensions": ", ".join(self.allowed_extensions), "value": value, }, ) def __eq__(self, other): return ( isinstance(other, self.__class__) and set(self.allowed_extensions or []) == set(other.allowed_extensions or []) and self.message == other.message and self.code == other.code ) def get_available_image_extensions(): try: from PIL import Image except ImportError: return [] else: Image.init() return [ext.lower()[1:] for ext in Image.EXTENSION] def validate_image_file_extension(value): return FileExtensionValidator(allowed_extensions=get_available_image_extensions())( value ) @deconstructible class ProhibitNullCharactersValidator: """Validate that the string doesn't contain the null character.""" message = _("Null characters are not allowed.") code = "null_characters_not_allowed" def __init__(self, message=None, code=None): if message is not None: self.message = message if code is not None: self.code = code def __call__(self, value): if "\x00" in str(value): raise ValidationError(self.message, code=self.code, params={"value": value}) def __eq__(self, other): return ( isinstance(other, self.__class__) and self.message == other.message and self.code == other.code )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/asgi.py
django/core/asgi.py
import django from django.core.handlers.asgi import ASGIHandler def get_asgi_application(): """ The public interface to Django's ASGI support. Return an ASGI 3 callable. Avoids making django.core.handlers.ASGIHandler a public API, in case the internal implementation changes or moves in the future. """ django.setup(set_prefix=False) return ASGIHandler()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/__init__.py
django/core/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/wsgi.py
django/core/wsgi.py
import django from django.core.handlers.wsgi import WSGIHandler def get_wsgi_application(): """ The public interface to Django's WSGI support. Return a WSGI callable. Avoids making django.core.handlers.WSGIHandler a public API, in case the internal WSGI implementation changes or moves in the future. """ django.setup(set_prefix=False) return WSGIHandler()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/sql.py
django/core/management/sql.py
import sys from django.apps import apps from django.db import models def sql_flush(style, connection, reset_sequences=True, allow_cascade=False): """ Return a list of the SQL statements used to flush the database. """ tables = connection.introspection.django_table_names( only_existing=True, include_views=False ) return connection.ops.sql_flush( style, tables, reset_sequences=reset_sequences, allow_cascade=allow_cascade, ) def emit_pre_migrate_signal(verbosity, interactive, db, **kwargs): # Emit the pre_migrate signal for every application. for app_config in apps.get_app_configs(): if app_config.models_module is None: continue if verbosity >= 2: stdout = kwargs.get("stdout", sys.stdout) stdout.write( "Running pre-migrate handlers for application %s" % app_config.label ) models.signals.pre_migrate.send( sender=app_config, app_config=app_config, verbosity=verbosity, interactive=interactive, using=db, **kwargs, ) def emit_post_migrate_signal(verbosity, interactive, db, **kwargs): # Emit the post_migrate signal for every application. for app_config in apps.get_app_configs(): if app_config.models_module is None: continue if verbosity >= 2: stdout = kwargs.get("stdout", sys.stdout) stdout.write( "Running post-migrate handlers for application %s" % app_config.label ) models.signals.post_migrate.send( sender=app_config, app_config=app_config, verbosity=verbosity, interactive=interactive, using=db, **kwargs, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/templates.py
django/core/management/templates.py
import argparse import mimetypes import os import posixpath import shutil import stat import tempfile from importlib.util import find_spec from urllib.request import build_opener import django from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import ( find_formatters, handle_extensions, run_formatters, ) from django.template import Context, Engine from django.utils import archive from django.utils.http import parse_header_parameters from django.utils.version import get_docs_version class TemplateCommand(BaseCommand): """ Copy either a Django application layout template or a Django project layout template into the specified directory. :param style: A color style object (see django.core.management.color). :param app_or_project: The string 'app' or 'project'. :param name: The name of the application or project. :param directory: The directory to which the template should be copied. :param options: The additional variables passed to project or app templates """ requires_system_checks = [] # The supported URL schemes url_schemes = ["http", "https", "ftp"] # Rewrite the following suffixes when determining the target filename. rewrite_template_suffixes = ( # Allow shipping invalid .py files without byte-compilation. (".py-tpl", ".py"), ) def add_arguments(self, parser): parser.add_argument("name", help="Name of the application or project.") parser.add_argument( "directory", nargs="?", help="Optional destination directory, this will be created if needed.", ) parser.add_argument( "--template", help="The path or URL to load the template from." ) parser.add_argument( "--extension", "-e", dest="extensions", action="append", default=["py"], help='The file extension(s) to render (default: "py"). ' "Separate multiple extensions with commas, or use " "-e multiple times.", ) parser.add_argument( "--name", "-n", dest="files", action="append", default=[], help="The file name(s) to render. Separate multiple file names " "with commas, or use -n multiple times.", ) parser.add_argument( "--exclude", "-x", action="append", default=argparse.SUPPRESS, nargs="?", const="", help=( "The directory name(s) to exclude, in addition to .git and " "__pycache__. Can be used multiple times." ), ) def handle(self, app_or_project, name, target=None, **options): self.app_or_project = app_or_project self.a_or_an = "an" if app_or_project == "app" else "a" self.paths_to_remove = [] self.verbosity = options["verbosity"] self.validate_name(name) # if some directory is given, make sure it's nicely expanded if target is None: top_dir = os.path.join(os.getcwd(), name) try: os.makedirs(top_dir) except FileExistsError: raise CommandError("'%s' already exists" % top_dir) except OSError as e: raise CommandError(e) else: top_dir = os.path.abspath(os.path.expanduser(target)) if app_or_project == "app": self.validate_name(os.path.basename(top_dir), "directory") if not os.path.exists(top_dir): try: os.makedirs(top_dir) except OSError as e: raise CommandError(e) # Find formatters, which are external executables, before input # from the templates can sneak into the path. formatter_paths = find_formatters() extensions = tuple(handle_extensions(options["extensions"])) extra_files = [] excluded_directories = [".git", "__pycache__"] for file in options["files"]: extra_files.extend(map(lambda x: x.strip(), file.split(","))) if exclude := options.get("exclude"): for directory in exclude: excluded_directories.append(directory.strip()) if self.verbosity >= 2: self.stdout.write( "Rendering %s template files with extensions: %s" % (app_or_project, ", ".join(extensions)) ) self.stdout.write( "Rendering %s template files with filenames: %s" % (app_or_project, ", ".join(extra_files)) ) base_name = "%s_name" % app_or_project base_subdir = "%s_template" % app_or_project base_directory = "%s_directory" % app_or_project camel_case_name = "camel_case_%s_name" % app_or_project camel_case_value = "".join(x for x in name.title() if x != "_") context = Context( { **options, base_name: name, base_directory: top_dir, camel_case_name: camel_case_value, "docs_version": get_docs_version(), "django_version": django.__version__, }, autoescape=False, ) # Setup a stub settings environment for template rendering if not settings.configured: settings.configure() django.setup() template_dir = self.handle_template(options["template"], base_subdir) prefix_length = len(template_dir) + 1 for root, dirs, files in os.walk(template_dir): path_rest = root[prefix_length:] relative_dir = path_rest.replace(base_name, name) if relative_dir: target_dir = os.path.join(top_dir, relative_dir) os.makedirs(target_dir, exist_ok=True) for dirname in dirs[:]: if "exclude" not in options: if dirname.startswith(".") or dirname == "__pycache__": dirs.remove(dirname) elif dirname in excluded_directories: dirs.remove(dirname) for filename in files: if filename.endswith((".pyo", ".pyc", ".py.class")): # Ignore some files as they cause various breakages. continue old_path = os.path.join(root, filename) new_path = os.path.join( top_dir, relative_dir, filename.replace(base_name, name) ) for old_suffix, new_suffix in self.rewrite_template_suffixes: if new_path.endswith(old_suffix): new_path = new_path.removesuffix(old_suffix) + new_suffix break # Only rewrite once if os.path.exists(new_path): raise CommandError( "%s already exists. Overlaying %s %s into an existing " "directory won't replace conflicting files." % ( new_path, self.a_or_an, app_or_project, ) ) # Only render the Python files, as we don't want to # accidentally render Django templates files if new_path.endswith(extensions) or filename in extra_files: with open(old_path, encoding="utf-8") as template_file: content = template_file.read() template = Engine().from_string(content) content = template.render(context) with open(new_path, "w", encoding="utf-8") as new_file: new_file.write(content) else: shutil.copyfile(old_path, new_path) if self.verbosity >= 2: self.stdout.write("Creating %s" % new_path) try: self.apply_umask(old_path, new_path) self.make_writeable(new_path) except OSError: self.stderr.write( "Notice: Couldn't set permission bits on %s. You're " "probably using an uncommon filesystem setup. No " "problem." % new_path, self.style.NOTICE, ) if self.paths_to_remove: if self.verbosity >= 2: self.stdout.write("Cleaning up temporary files.") for path_to_remove in self.paths_to_remove: if os.path.isfile(path_to_remove): os.remove(path_to_remove) else: shutil.rmtree(path_to_remove) run_formatters([top_dir], **formatter_paths, stderr=self.stderr) def handle_template(self, template, subdir): """ Determine where the app or project templates are. Use django.__path__[0] as the default because the Django install directory isn't known. """ if template is None: return os.path.join(django.__path__[0], "conf", subdir) else: template = template.removeprefix("file://") expanded_template = os.path.expanduser(template) expanded_template = os.path.normpath(expanded_template) if os.path.isdir(expanded_template): return expanded_template if self.is_url(template): # downloads the file and returns the path absolute_path = self.download(template) else: absolute_path = os.path.abspath(expanded_template) if os.path.exists(absolute_path): return self.extract(absolute_path) raise CommandError( "couldn't handle %s template %s." % (self.app_or_project, template) ) def validate_name(self, name, name_or_dir="name"): if name is None: raise CommandError( "you must provide {an} {app} name".format( an=self.a_or_an, app=self.app_or_project, ) ) # Check it's a valid directory name. if not name.isidentifier(): raise CommandError( "'{name}' is not a valid {app} {type}. Please make sure the " "{type} is a valid identifier.".format( name=name, app=self.app_or_project, type=name_or_dir, ) ) # Check that __spec__ doesn't exist. if find_spec(name) is not None: raise CommandError( "'{name}' conflicts with the name of an existing Python " "module and cannot be used as {an} {app} {type}. Please try " "another {type}.".format( name=name, an=self.a_or_an, app=self.app_or_project, type=name_or_dir, ) ) def download(self, url): """ Download the given URL and return the file name. """ def cleanup_url(url): tmp = url.rstrip("/") filename = tmp.split("/")[-1] if url.endswith("/"): display_url = tmp + "/" else: display_url = url return filename, display_url prefix = "django_%s_template_" % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_download") self.paths_to_remove.append(tempdir) filename, display_url = cleanup_url(url) if self.verbosity >= 2: self.stdout.write("Downloading %s" % display_url) the_path = os.path.join(tempdir, filename) opener = build_opener() opener.addheaders = [("User-Agent", f"Django/{django.__version__}")] try: with opener.open(url) as source, open(the_path, "wb") as target: headers = source.info() target.write(source.read()) except OSError as e: raise CommandError( "couldn't download URL %s to %s: %s" % (url, filename, e) ) used_name = the_path.split("/")[-1] # Trying to get better name from response headers content_disposition = headers["content-disposition"] if content_disposition: _, params = parse_header_parameters(content_disposition) guessed_filename = params.get("filename") or used_name else: guessed_filename = used_name # Falling back to content type guessing ext = self.splitext(guessed_filename)[1] content_type = headers["content-type"] if not ext and content_type: ext = mimetypes.guess_extension(content_type) if ext: guessed_filename += ext # Move the temporary file to a filename that has better # chances of being recognized by the archive utils if used_name != guessed_filename: guessed_path = os.path.join(tempdir, guessed_filename) shutil.move(the_path, guessed_path) return guessed_path # Giving up return the_path def splitext(self, the_path): """ Like os.path.splitext, but takes off .tar, too """ base, ext = posixpath.splitext(the_path) if base.lower().endswith(".tar"): ext = base[-4:] + ext base = base[:-4] return base, ext def extract(self, filename): """ Extract the given file to a temporary directory and return the path of the directory with the extracted content. """ prefix = "django_%s_template_" % self.app_or_project tempdir = tempfile.mkdtemp(prefix=prefix, suffix="_extract") self.paths_to_remove.append(tempdir) if self.verbosity >= 2: self.stdout.write("Extracting %s" % filename) try: archive.extract(filename, tempdir) return tempdir except (archive.ArchiveException, OSError) as e: raise CommandError( "couldn't extract file %s to %s: %s" % (filename, tempdir, e) ) def is_url(self, template): """Return True if the name looks like a URL.""" if ":" not in template: return False scheme = template.split(":", 1)[0].lower() return scheme in self.url_schemes def apply_umask(self, old_path, new_path): current_umask = os.umask(0) os.umask(current_umask) current_mode = stat.S_IMODE(os.stat(old_path).st_mode) os.chmod(new_path, current_mode & ~current_umask) def make_writeable(self, filename): """ Make sure that the file is writeable. Useful if our source is read-only. """ if not os.access(filename, os.W_OK): st = os.stat(filename) new_permissions = stat.S_IMODE(st.st_mode) | stat.S_IWUSR os.chmod(filename, new_permissions)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/utils.py
django/core/management/utils.py
import fnmatch import os import shutil import subprocess import sys import traceback from pathlib import Path from subprocess import run from django.apps import apps as installed_apps from django.utils.crypto import get_random_string from django.utils.encoding import DEFAULT_LOCALE_ENCODING from .base import CommandError, CommandParser def popen_wrapper(args, stdout_encoding="utf-8"): """ Friendly wrapper around Popen. Return stdout output, stderr output, and OS status code. """ try: p = run(args, capture_output=True, close_fds=os.name != "nt") except OSError as err: raise CommandError("Error executing %s" % args[0]) from err return ( p.stdout.decode(stdout_encoding), p.stderr.decode(DEFAULT_LOCALE_ENCODING, errors="replace"), p.returncode, ) def handle_extensions(extensions): """ Organize multiple extensions that are separated with commas or passed by using --extension/-e multiple times. For example: running 'django-admin makemessages -e js,txt -e xhtml -a' would result in an extension list: ['.js', '.txt', '.xhtml'] >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.py']) {'.html', '.js', '.py'} >>> handle_extensions(['.html, txt,.tpl']) {'.html', '.tpl', '.txt'} """ ext_list = [] for ext in extensions: ext_list.extend(ext.replace(" ", "").split(",")) for i, ext in enumerate(ext_list): if not ext.startswith("."): ext_list[i] = ".%s" % ext_list[i] return set(ext_list) def find_command(cmd, path=None, pathext=None): if path is None: path = os.environ.get("PATH", "").split(os.pathsep) if isinstance(path, str): path = [path] # check if there are funny path extensions for executables, e.g. Windows if pathext is None: pathext = os.environ.get("PATHEXT", ".COM;.EXE;.BAT;.CMD").split(os.pathsep) # don't use extensions if the command ends with one of them for ext in pathext: if cmd.endswith(ext): pathext = [""] break # check if we find the command on PATH for p in path: f = os.path.join(p, cmd) if os.path.isfile(f): return f for ext in pathext: fext = f + ext if os.path.isfile(fext): return fext return None def get_random_secret_key(): """ Return a 50 character random string usable as a SECRET_KEY setting value. """ chars = "abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)" return get_random_string(50, chars) def parse_apps_and_model_labels(labels): """ Parse a list of "app_label.ModelName" or "app_label" strings into actual objects and return a two-element tuple: (set of model classes, set of app_configs). Raise a CommandError if some specified models or apps don't exist. """ apps = set() models = set() for label in labels: if "." in label: try: model = installed_apps.get_model(label) except LookupError: raise CommandError("Unknown model: %s" % label) models.add(model) else: try: app_config = installed_apps.get_app_config(label) except LookupError as e: raise CommandError(str(e)) apps.add(app_config) return models, apps def get_command_line_option(argv, option): """ Return the value of a command line option (which should include leading dashes, e.g. '--testrunner') from an argument list. Return None if the option wasn't passed or if the argument list couldn't be parsed. """ parser = CommandParser(add_help=False, allow_abbrev=False) parser.add_argument(option, dest="value") try: options, _ = parser.parse_known_args(argv[2:]) except CommandError: return None else: return options.value def normalize_path_patterns(patterns): """Normalize an iterable of glob style patterns based on OS.""" patterns = [os.path.normcase(p) for p in patterns] dir_suffixes = {"%s*" % path_sep for path_sep in {"/", os.sep}} norm_patterns = [] for pattern in patterns: for dir_suffix in dir_suffixes: if pattern.endswith(dir_suffix): norm_patterns.append(pattern.removesuffix(dir_suffix)) break else: norm_patterns.append(pattern) return norm_patterns def is_ignored_path(path, ignore_patterns): """ Check if the given path should be ignored or not based on matching one of the glob style `ignore_patterns`. """ path = Path(path) def ignore(pattern): return fnmatch.fnmatchcase(path.name, pattern) or fnmatch.fnmatchcase( str(path), pattern ) return any(ignore(pattern) for pattern in normalize_path_patterns(ignore_patterns)) def find_formatters(): return {"black_path": shutil.which("black")} def run_formatters(written_files, black_path=(sentinel := object()), stderr=sys.stderr): """ Run the black formatter on the specified files. """ # Use a sentinel rather than None, as which() returns None when not found. if black_path is sentinel: black_path = shutil.which("black") if black_path: try: subprocess.run( [black_path, "--fast", "--", *written_files], capture_output=True, ) except OSError: stderr.write("Formatters failed to launch:") traceback.print_exc(file=stderr)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/__init__.py
django/core/management/__init__.py
import functools import os import pkgutil import sys from argparse import ( _AppendConstAction, _CountAction, _StoreConstAction, _SubParsersAction, ) from collections import defaultdict from difflib import get_close_matches from importlib import import_module import django from django.apps import apps from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.management.base import ( BaseCommand, CommandError, CommandParser, handle_default_options, ) from django.core.management.color import color_style from django.utils import autoreload def find_commands(management_dir): """ Given a path to a management directory, return a list of all the command names that are available. """ command_dir = os.path.join(management_dir, "commands") return [ name for _, name, is_pkg in pkgutil.iter_modules([command_dir]) if not is_pkg and not name.startswith("_") ] def load_command_class(app_name, name): """ Given a command name and an application name, return the Command class instance. Allow all errors raised by the import process (ImportError, AttributeError) to propagate. """ module = import_module("%s.management.commands.%s" % (app_name, name)) return module.Command() @functools.cache def get_commands(): """ Return a dictionary mapping command names to their callback applications. Look for a management.commands package in django.core, and in each installed application -- if a commands package exists, register all commands in that package. Core commands are always included. If a settings module has been specified, also include user-defined commands. The dictionary is in the format {command_name: app_name}. Key-value pairs from this dictionary can then be used in calls to load_command_class(app_name, command_name) The dictionary is cached on the first call and reused on subsequent calls. """ commands = {name: "django.core" for name in find_commands(__path__[0])} if not settings.configured: return commands for app_config in reversed(apps.get_app_configs()): path = os.path.join(app_config.path, "management") commands.update({name: app_config.name for name in find_commands(path)}) return commands def call_command(command_name, *args, **options): """ Call the given command, with the given options and args/kwargs. This is the primary API you should use for calling specific commands. `command_name` may be a string or a command object. Using a string is preferred unless the command object is required for further processing or testing. Some examples: call_command('migrate') call_command('shell', plain=True) call_command('sqlmigrate', 'myapp') from django.core.management.commands import flush cmd = flush.Command() call_command(cmd, verbosity=0, interactive=False) # Do something with cmd ... """ if isinstance(command_name, BaseCommand): # Command object passed in. command = command_name command_name = command.__class__.__module__.split(".")[-1] else: # Load the command object by name. try: app_name = get_commands()[command_name] except KeyError: raise CommandError("Unknown command: %r" % command_name) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. command = app_name else: command = load_command_class(app_name, command_name) # Simulate argument parsing to get the option defaults (see #10080 for # details). parser = command.create_parser("", command_name) # Use the `dest` option name from the parser option opt_mapping = { min(s_opt.option_strings).lstrip("-").replace("-", "_"): s_opt.dest for s_opt in parser._actions if s_opt.option_strings } arg_options = {opt_mapping.get(key, key): value for key, value in options.items()} parse_args = [] for arg in args: if isinstance(arg, (list, tuple)): parse_args += map(str, arg) else: parse_args.append(str(arg)) def get_actions(parser): # Parser actions and actions from sub-parser choices. for opt in parser._actions: if isinstance(opt, _SubParsersAction): for sub_opt in opt.choices.values(): yield from get_actions(sub_opt) else: yield opt parser_actions = list(get_actions(parser)) mutually_exclusive_required_options = { opt for group in parser._mutually_exclusive_groups for opt in group._group_actions if group.required } # Any required arguments which are passed in via **options must be passed # to parse_args(). for opt in parser_actions: if opt.dest in options and ( opt.required or opt in mutually_exclusive_required_options ): opt_dest_count = sum(v == opt.dest for v in opt_mapping.values()) if opt_dest_count > 1: raise TypeError( f"Cannot pass the dest {opt.dest!r} that matches multiple " f"arguments via **options." ) parse_args.append(min(opt.option_strings)) if isinstance(opt, (_AppendConstAction, _CountAction, _StoreConstAction)): continue value = arg_options[opt.dest] if isinstance(value, (list, tuple)): parse_args += map(str, value) else: parse_args.append(str(value)) defaults = parser.parse_args(args=parse_args) defaults = dict(defaults._get_kwargs(), **arg_options) # Raise an error if any unknown options were passed. stealth_options = set(command.base_stealth_options + command.stealth_options) dest_parameters = {action.dest for action in parser_actions} valid_options = (dest_parameters | stealth_options).union(opt_mapping) unknown_options = set(options) - valid_options if unknown_options: raise TypeError( "Unknown option(s) for %s command: %s. " "Valid options are: %s." % ( command_name, ", ".join(sorted(unknown_options)), ", ".join(sorted(valid_options)), ) ) # Move positional args out of options to mimic legacy optparse args = defaults.pop("args", ()) if "skip_checks" not in options: defaults["skip_checks"] = True return command.execute(*args, **defaults) class ManagementUtility: """ Encapsulate the logic of the django-admin and manage.py utilities. """ def __init__(self, argv=None): self.argv = argv or sys.argv[:] self.prog_name = os.path.basename(self.argv[0]) if self.prog_name == "__main__.py": self.prog_name = "python -m django" self.settings_exception = None def main_help_text(self, commands_only=False): """Return the script's main help text, as a string.""" if commands_only: usage = sorted(get_commands()) else: usage = [ "", "Type '%s help <subcommand>' for help on a specific subcommand." % self.prog_name, "", "Available subcommands:", ] commands_dict = defaultdict(lambda: []) for name, app in get_commands().items(): if app == "django.core": app = "django" else: app = app.rpartition(".")[-1] commands_dict[app].append(name) style = color_style() for app in sorted(commands_dict): usage.append("") usage.append(style.NOTICE("[%s]" % app)) for name in sorted(commands_dict[app]): usage.append(" %s" % name) # Output an extra note if settings are not properly configured if self.settings_exception is not None: usage.append( style.NOTICE( "Note that only Django core commands are listed " "as settings are not properly configured (error: %s)." % self.settings_exception ) ) return "\n".join(usage) def fetch_command(self, subcommand): """ Try to fetch the given subcommand, printing a message with the appropriate command called from the command line (usually "django-admin" or "manage.py") if it can't be found. """ # Get commands outside of try block to prevent swallowing exceptions commands = get_commands() try: app_name = commands[subcommand] except KeyError: if os.environ.get("DJANGO_SETTINGS_MODULE"): # If `subcommand` is missing due to misconfigured settings, the # following line will retrigger an ImproperlyConfigured # exception (get_commands() swallows the original one) so the # user is informed about it. settings.INSTALLED_APPS elif not settings.configured: sys.stderr.write("No Django settings specified.\n") possible_matches = get_close_matches(subcommand, commands) sys.stderr.write("Unknown command: %r" % subcommand) if possible_matches: sys.stderr.write(". Did you mean %s?" % possible_matches[0]) sys.stderr.write("\nType '%s help' for usage.\n" % self.prog_name) sys.exit(1) if isinstance(app_name, BaseCommand): # If the command is already loaded, use it directly. klass = app_name else: klass = load_command_class(app_name, subcommand) return klass def autocomplete(self): """ Output completion suggestions for BASH. The output of this function is passed to BASH's `COMPREPLY` variable and treated as completion suggestions. `COMPREPLY` expects a space separated string as the result. The `COMP_WORDS` and `COMP_CWORD` BASH environment variables are used to get information about the cli input. Please refer to the BASH man-page for more information about this variables. Subcommand options are saved as pairs. A pair consists of the long option string (e.g. '--exclude') and a boolean value indicating if the option requires arguments. When printing to stdout, an equal sign is appended to options which require arguments. Note: If debugging this function, it is recommended to write the debug output in a separate file. Otherwise the debug output will be treated and formatted as potential completion suggestions. """ # Don't complete if user hasn't sourced bash_completion file. if "DJANGO_AUTO_COMPLETE" not in os.environ: return cwords = os.environ["COMP_WORDS"].split()[1:] cword = int(os.environ["COMP_CWORD"]) try: curr = cwords[cword - 1] except IndexError: curr = "" subcommands = [*get_commands(), "help"] options = [("--help", False)] # subcommand if cword == 1: print(" ".join(sorted(filter(lambda x: x.startswith(curr), subcommands)))) # subcommand options # special case: the 'help' subcommand has no options elif cwords[0] in subcommands and cwords[0] != "help": subcommand_cls = self.fetch_command(cwords[0]) # special case: add the names of installed apps to options if cwords[0] in ("dumpdata", "sqlmigrate", "sqlsequencereset", "test"): try: app_configs = apps.get_app_configs() # Get the last part of the dotted path as the app name. options.extend((app_config.label, 0) for app_config in app_configs) except ImportError: # Fail silently if DJANGO_SETTINGS_MODULE isn't set. The # user will find out once they execute the command. pass parser = subcommand_cls.create_parser("", cwords[0]) options.extend( (min(s_opt.option_strings), s_opt.nargs != 0) for s_opt in parser._actions if s_opt.option_strings ) # filter out previously specified options from available options prev_opts = {x.split("=")[0] for x in cwords[1 : cword - 1]} options = (opt for opt in options if opt[0] not in prev_opts) # filter options by current input options = sorted((k, v) for k, v in options if k.startswith(curr)) for opt_label, require_arg in options: # append '=' to options which require args if require_arg: opt_label += "=" print(opt_label) # Exit code of the bash completion function is never passed back to # the user, so it's safe to always exit with 0. # For more details see #25420. sys.exit(0) def execute(self): """ Given the command-line arguments, figure out which subcommand is being run, create a parser appropriate to that command, and run it. """ try: subcommand = self.argv[1] except IndexError: subcommand = "help" # Display help if no arguments were given. # Preprocess options to extract --settings and --pythonpath. # These options could affect the commands that are available, so they # must be processed early. parser = CommandParser( prog=self.prog_name, usage="%(prog)s subcommand [options] [args]", add_help=False, allow_abbrev=False, ) parser.add_argument("--settings") parser.add_argument("--pythonpath") parser.add_argument("args", nargs="*") # catch-all try: options, args = parser.parse_known_args(self.argv[2:]) handle_default_options(options) except CommandError: pass # Ignore any option errors at this point. try: settings.INSTALLED_APPS except ImproperlyConfigured as exc: self.settings_exception = exc except ImportError as exc: self.settings_exception = exc if settings.configured: # Start the auto-reloading dev server even if the code is broken. # The hardcoded condition is a code smell but we can't rely on a # flag on the command class because we haven't located it yet. if subcommand == "runserver" and "--noreload" not in self.argv: try: autoreload.check_errors(django.setup)() except Exception: # The exception will be raised later in the child process # started by the autoreloader. Pretend it didn't happen by # loading an empty list of applications. apps.all_models = defaultdict(dict) apps.app_configs = {} apps.apps_ready = apps.models_ready = apps.ready = True # Remove options not compatible with the built-in runserver # (e.g. options for the contrib.staticfiles' runserver). # Changes here require manually testing as described in # #27522. _parser = self.fetch_command("runserver").create_parser( "django", "runserver" ) _options, _args = _parser.parse_known_args(self.argv[2:]) for _arg in _args: self.argv.remove(_arg) # In all other cases, django.setup() is required to succeed. else: django.setup() self.autocomplete() if subcommand == "help": if "--commands" in args: sys.stdout.write(self.main_help_text(commands_only=True) + "\n") elif not options.args: sys.stdout.write(self.main_help_text() + "\n") else: self.fetch_command(options.args[0]).print_help( self.prog_name, options.args[0] ) # Special-cases: We want 'django-admin --version' and # 'django-admin --help' to work, for backwards compatibility. elif subcommand == "version" or self.argv[1:] == ["--version"]: sys.stdout.write(django.get_version() + "\n") elif self.argv[1:] in (["--help"], ["-h"]): sys.stdout.write(self.main_help_text() + "\n") else: self.fetch_command(subcommand).run_from_argv(self.argv) def execute_from_command_line(argv=None): """Run a ManagementUtility.""" utility = ManagementUtility(argv) utility.execute()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/color.py
django/core/management/color.py
""" Sets up the terminal color scheme. """ import functools import os import sys from django.utils import termcolors try: import colorama # Avoid initializing colorama in non-Windows platforms. colorama.just_fix_windows_console() except ( AttributeError, # colorama <= 0.4.6. ImportError, # colorama is not installed. # If just_fix_windows_console() accesses sys.stdout with # WSGIRestrictedStdout. OSError, ): HAS_COLORAMA = False else: HAS_COLORAMA = True def supports_color(): """ Return True if the running system's terminal supports color, and False otherwise. """ def vt_codes_enabled_in_windows_registry(): """ Check the Windows Registry to see if VT code handling has been enabled by default, see https://superuser.com/a/1300251/447564. """ try: # winreg is only available on Windows. import winreg except ImportError: return False else: try: reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Console") reg_key_value, _ = winreg.QueryValueEx(reg_key, "VirtualTerminalLevel") except FileNotFoundError: return False else: return reg_key_value == 1 # isatty is not always implemented, #6223. is_a_tty = hasattr(sys.stdout, "isatty") and sys.stdout.isatty() return is_a_tty and ( sys.platform != "win32" or (HAS_COLORAMA and getattr(colorama, "fixed_windows_console", False)) or "ANSICON" in os.environ or # Windows Terminal supports VT codes. "WT_SESSION" in os.environ or # Microsoft Visual Studio Code's built-in terminal supports colors. os.environ.get("TERM_PROGRAM") == "vscode" or vt_codes_enabled_in_windows_registry() ) class Style: pass def make_style(config_string=""): """ Create a Style object from the given config_string. If config_string is empty django.utils.termcolors.DEFAULT_PALETTE is used. """ style = Style() color_settings = termcolors.parse_color_setting(config_string) # The nocolor palette has all available roles. # Use that palette as the basis for populating # the palette as defined in the environment. for role in termcolors.PALETTES[termcolors.NOCOLOR_PALETTE]: if color_settings: format = color_settings.get(role, {}) style_func = termcolors.make_style(**format) else: def style_func(x): return x setattr(style, role, style_func) # For backwards compatibility, # set style for ERROR_OUTPUT == ERROR style.ERROR_OUTPUT = style.ERROR return style @functools.cache def no_style(): """ Return a Style object with no color scheme. """ return make_style("nocolor") def color_style(force_color=False): """ Return a Style object from the Django color scheme. """ if not force_color and not supports_color(): return no_style() return make_style(os.environ.get("DJANGO_COLORS", ""))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/base.py
django/core/management/base.py
""" Base classes for writing management commands (named commands which can be executed through ``django-admin`` or ``manage.py``). """ import argparse import os import sys from argparse import ArgumentParser, HelpFormatter from functools import partial from io import TextIOBase import django from django.core import checks from django.core.exceptions import ImproperlyConfigured from django.core.management.color import color_style, no_style from django.db import DEFAULT_DB_ALIAS, connections from django.utils.version import PY314, PY315 ALL_CHECKS = "__all__" class CommandError(Exception): """ Exception class indicating a problem while executing a management command. If this exception is raised during the execution of a management command, it will be caught and turned into a nicely-printed error message to the appropriate output stream (i.e., stderr); as a result, raising this exception (with a sensible description of the error) is the preferred way to indicate that something has gone wrong in the execution of a command. """ def __init__(self, *args, returncode=1, **kwargs): self.returncode = returncode super().__init__(*args, **kwargs) class SystemCheckError(CommandError): """ The system check framework detected unrecoverable errors. """ pass class CommandParser(ArgumentParser): """ Customized ArgumentParser class to improve some error messages and prevent SystemExit in several occasions, as SystemExit is unacceptable when a command is called programmatically. """ def __init__( self, *, missing_args_message=None, called_from_command_line=None, **kwargs ): self.missing_args_message = missing_args_message self.called_from_command_line = called_from_command_line if PY314: if not PY315: kwargs.setdefault("suggest_on_error", True) if os.environ.get("DJANGO_COLORS") == "nocolor" or "--no-color" in sys.argv: kwargs.setdefault("color", False) super().__init__(**kwargs) def parse_args(self, args=None, namespace=None): # Catch missing argument for a better error message if self.missing_args_message and not ( args or any(not arg.startswith("-") for arg in args) ): self.error(self.missing_args_message) return super().parse_args(args, namespace) def error(self, message): if self.called_from_command_line: super().error(message) else: raise CommandError("Error: %s" % message) def add_subparsers(self, **kwargs): parser_class = kwargs.get("parser_class", type(self)) if issubclass(parser_class, CommandParser): kwargs["parser_class"] = partial( parser_class, called_from_command_line=self.called_from_command_line, ) return super().add_subparsers(**kwargs) def handle_default_options(options): """ Include any default options that all commands should accept here so that ManagementUtility can handle them before searching for user commands. """ if options.settings: os.environ["DJANGO_SETTINGS_MODULE"] = options.settings if options.pythonpath: sys.path.insert(0, options.pythonpath) def no_translations(handle_func): """Decorator that forces a command to run with translations deactivated.""" def wrapper(*args, **kwargs): from django.utils import translation saved_locale = translation.get_language() translation.deactivate_all() try: res = handle_func(*args, **kwargs) finally: if saved_locale is not None: translation.activate(saved_locale) return res return wrapper class DjangoHelpFormatter(HelpFormatter): """ Customized formatter so that command-specific arguments appear in the --help output before arguments common to all commands. """ show_last = { "--version", "--verbosity", "--traceback", "--settings", "--pythonpath", "--no-color", "--force-color", "--skip-checks", } def _reordered_actions(self, actions): return sorted( actions, key=lambda a: set(a.option_strings) & self.show_last != set() ) def add_usage(self, usage, actions, *args, **kwargs): super().add_usage(usage, self._reordered_actions(actions), *args, **kwargs) def add_arguments(self, actions): super().add_arguments(self._reordered_actions(actions)) class OutputWrapper: """ Wrapper around stdout/stderr """ @property def style_func(self): return self._style_func @style_func.setter def style_func(self, style_func): if style_func and self.isatty(): self._style_func = style_func else: self._style_func = lambda x: x def __init__(self, out, ending="\n"): self._out = out self.style_func = None self.ending = ending def __getattr__(self, name): return getattr(self._out, name) def flush(self): if hasattr(self._out, "flush"): self._out.flush() def isatty(self): return hasattr(self._out, "isatty") and self._out.isatty() def write(self, msg="", style_func=None, ending=None): ending = self.ending if ending is None else ending if ending and not msg.endswith(ending): msg += ending style_func = style_func or self.style_func self._out.write(style_func(msg)) TextIOBase.register(OutputWrapper) class BaseCommand: """ The base class from which all management commands ultimately derive. Use this class if you want access to all of the mechanisms which parse the command-line arguments and work out what code to call in response; if you don't need to change any of that behavior, consider using one of the subclasses defined in this file. If you are interested in overriding/customizing various aspects of the command-parsing and -execution behavior, the normal flow works as follows: 1. ``django-admin`` or ``manage.py`` loads the command class and calls its ``run_from_argv()`` method. 2. The ``run_from_argv()`` method calls ``create_parser()`` to get an ``ArgumentParser`` for the arguments, parses them, performs any environment changes requested by options like ``pythonpath``, and then calls the ``execute()`` method, passing the parsed arguments. 3. The ``execute()`` method attempts to carry out the command by calling the ``handle()`` method with the parsed arguments; any output produced by ``handle()`` will be printed to standard output and, if the command is intended to produce a block of SQL statements, will be wrapped in ``BEGIN`` and ``COMMIT``. 4. If ``handle()`` or ``execute()`` raised any exception (e.g. ``CommandError``), ``run_from_argv()`` will instead print an error message to ``stderr``. Thus, the ``handle()`` method is typically the starting point for subclasses; many built-in commands and command types either place all of their logic in ``handle()``, or perform some additional parsing work in ``handle()`` and then delegate from it to more specialized methods as needed. Several attributes affect behavior at various steps along the way: ``help`` A short description of the command, which will be printed in help messages. ``output_transaction`` A boolean indicating whether the command outputs SQL statements; if ``True``, the output will automatically be wrapped with ``BEGIN;`` and ``COMMIT;``. Default value is ``False``. ``requires_migrations_checks`` A boolean; if ``True``, the command prints a warning if the set of migrations on disk don't match the migrations in the database. ``requires_system_checks`` A list or tuple of tags, e.g. [Tags.staticfiles, Tags.models]. System checks registered in the chosen tags will be checked for errors prior to executing the command. The value '__all__' can be used to specify that all system checks should be performed. Default value is '__all__'. To validate an individual application's models rather than all applications' models, call ``self.check(app_configs)`` from ``handle()``, where ``app_configs`` is the list of application's configuration provided by the app registry. ``stealth_options`` A tuple of any options the command uses which aren't defined by the argument parser. """ # Metadata about this command. help = "" # Configuration shortcuts that alter various logic. _called_from_command_line = False output_transaction = False # Whether to wrap the output in a "BEGIN; COMMIT;" requires_migrations_checks = False requires_system_checks = "__all__" # Arguments, common to all commands, which aren't defined by the argument # parser. base_stealth_options = ("stderr", "stdout") # Command-specific options not defined by the argument parser. stealth_options = () suppressed_base_arguments = set() def __init__(self, stdout=None, stderr=None, no_color=False, force_color=False): self.stdout = OutputWrapper(stdout or sys.stdout) self.stderr = OutputWrapper(stderr or sys.stderr) if no_color and force_color: raise CommandError("'no_color' and 'force_color' can't be used together.") if no_color: self.style = no_style() else: self.style = color_style(force_color) self.stderr.style_func = self.style.ERROR if ( not isinstance(self.requires_system_checks, (list, tuple)) and self.requires_system_checks != ALL_CHECKS ): raise TypeError("requires_system_checks must be a list or tuple.") def get_version(self): """ Return the Django version, which should be correct for all built-in Django commands. User-supplied commands can override this method to return their own version. """ return django.get_version() def create_parser(self, prog_name, subcommand, **kwargs): """ Create and return the ``ArgumentParser`` which will be used to parse the arguments to this command. """ kwargs.setdefault("formatter_class", DjangoHelpFormatter) parser = CommandParser( prog="%s %s" % (os.path.basename(prog_name), subcommand), description=self.help or None, missing_args_message=getattr(self, "missing_args_message", None), called_from_command_line=getattr(self, "_called_from_command_line", None), **kwargs, ) self.add_base_argument( parser, "--version", action="version", version=self.get_version(), help="Show program's version number and exit.", ) self.add_base_argument( parser, "-v", "--verbosity", default=1, type=int, choices=[0, 1, 2, 3], help=( "Verbosity level; 0=minimal output, 1=normal output, 2=verbose output, " "3=very verbose output" ), ) self.add_base_argument( parser, "--settings", help=( "The Python path to a settings module, e.g. " '"myproject.settings.main". If this isn\'t provided, the ' "DJANGO_SETTINGS_MODULE environment variable will be used." ), ) self.add_base_argument( parser, "--pythonpath", help=( "A directory to add to the Python path, e.g. " '"/home/djangoprojects/myproject".' ), ) self.add_base_argument( parser, "--traceback", action="store_true", help="Display a full stack trace on CommandError exceptions.", ) self.add_base_argument( parser, "--no-color", action="store_true", help="Don't colorize the command output.", ) self.add_base_argument( parser, "--force-color", action="store_true", help="Force colorization of the command output.", ) if self.requires_system_checks: parser.add_argument( "--skip-checks", action="store_true", help="Skip system checks.", ) self.add_arguments(parser) return parser def add_arguments(self, parser): """ Entry point for subclassed commands to add custom arguments. """ pass def add_base_argument(self, parser, *args, **kwargs): """ Call the parser's add_argument() method, suppressing the help text according to BaseCommand.suppressed_base_arguments. """ for arg in args: if arg in self.suppressed_base_arguments: kwargs["help"] = argparse.SUPPRESS break parser.add_argument(*args, **kwargs) def print_help(self, prog_name, subcommand): """ Print the help message for this command, derived from ``self.usage()``. """ parser = self.create_parser(prog_name, subcommand) parser.print_help() def run_from_argv(self, argv): """ Set up any environment changes requested (e.g., Python path and Django settings), then run this command. If the command raises a ``CommandError``, intercept it and print it sensibly to stderr. If the ``--traceback`` option is present or the raised ``Exception`` is not ``CommandError``, raise it. """ self._called_from_command_line = True parser = self.create_parser(argv[0], argv[1]) options = parser.parse_args(argv[2:]) cmd_options = vars(options) # Move positional args out of options to mimic legacy optparse args = cmd_options.pop("args", ()) handle_default_options(options) try: self.execute(*args, **cmd_options) except CommandError as e: if options.traceback: raise # SystemCheckError takes care of its own formatting. if isinstance(e, SystemCheckError): self.stderr.write(str(e), lambda x: x) else: self.stderr.write("%s: %s" % (e.__class__.__name__, e)) sys.exit(e.returncode) finally: try: connections.close_all() except ImproperlyConfigured: # Ignore if connections aren't setup at this point (e.g. no # configured settings). pass def execute(self, *args, **options): """ Try to execute this command, performing system checks if needed (as controlled by the ``requires_system_checks`` attribute, except if force-skipped). """ if options["force_color"] and options["no_color"]: raise CommandError( "The --no-color and --force-color options can't be used together." ) if options["force_color"]: self.style = color_style(force_color=True) elif options["no_color"]: self.style = no_style() self.stderr.style_func = None if options.get("stdout"): self.stdout = OutputWrapper(options["stdout"]) if options.get("stderr"): self.stderr = OutputWrapper(options["stderr"]) if self.requires_system_checks and not options["skip_checks"]: check_kwargs = self.get_check_kwargs(options) self.check(**check_kwargs) if self.requires_migrations_checks: self.check_migrations() output = self.handle(*args, **options) if output: if self.output_transaction: connection = connections[options.get("database", DEFAULT_DB_ALIAS)] output = "%s\n%s\n%s" % ( self.style.SQL_KEYWORD(connection.ops.start_transaction_sql()), output, self.style.SQL_KEYWORD(connection.ops.end_transaction_sql()), ) self.stdout.write(output) return output def get_check_kwargs(self, options): if self.requires_system_checks == ALL_CHECKS: return {} return {"tags": self.requires_system_checks} def check( self, app_configs=None, tags=None, display_num_errors=False, include_deployment_checks=False, fail_level=checks.ERROR, databases=None, ): """ Use the system check framework to validate entire Django project. Raise CommandError for any serious message (error or critical errors). If there are only light messages (like warnings), print them to stderr and don't raise an exception. """ all_issues = checks.run_checks( app_configs=app_configs, tags=tags, include_deployment_checks=include_deployment_checks, databases=databases, ) header, body, footer = "", "", "" visible_issue_count = 0 # excludes silenced warnings if all_issues: debugs = [ e for e in all_issues if e.level < checks.INFO and not e.is_silenced() ] infos = [ e for e in all_issues if checks.INFO <= e.level < checks.WARNING and not e.is_silenced() ] warnings = [ e for e in all_issues if checks.WARNING <= e.level < checks.ERROR and not e.is_silenced() ] errors = [ e for e in all_issues if checks.ERROR <= e.level < checks.CRITICAL and not e.is_silenced() ] criticals = [ e for e in all_issues if checks.CRITICAL <= e.level and not e.is_silenced() ] sorted_issues = [ (criticals, "CRITICALS"), (errors, "ERRORS"), (warnings, "WARNINGS"), (infos, "INFOS"), (debugs, "DEBUGS"), ] for issues, group_name in sorted_issues: if issues: visible_issue_count += len(issues) formatted = ( ( self.style.ERROR(str(e)) if e.is_serious() else self.style.WARNING(str(e)) ) for e in issues ) formatted = "\n".join(sorted(formatted)) body += "\n%s:\n%s\n" % (group_name, formatted) if visible_issue_count: header = "System check identified some issues:\n" if display_num_errors: if visible_issue_count: footer += "\n" footer += "System check identified %s (%s silenced)." % ( ( "no issues" if visible_issue_count == 0 else ( "1 issue" if visible_issue_count == 1 else "%s issues" % visible_issue_count ) ), len(all_issues) - visible_issue_count, ) if any(e.is_serious(fail_level) and not e.is_silenced() for e in all_issues): msg = self.style.ERROR("SystemCheckError: %s" % header) + body + footer raise SystemCheckError(msg) else: msg = header + body + footer if msg: if visible_issue_count: self.stderr.write(msg, lambda x: x) else: self.stdout.write(msg) def check_migrations(self): """ Print a warning if the set of migrations on disk don't match the migrations in the database. """ from django.db.migrations.executor import MigrationExecutor try: executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) except ImproperlyConfigured: # No databases are configured (or the dummy one) return plan = executor.migration_plan(executor.loader.graph.leaf_nodes()) if plan: apps_waiting_migration = sorted( {migration.app_label for migration, backwards in plan} ) self.stdout.write( self.style.NOTICE( "\nYou have %(unapplied_migration_count)s unapplied migration(s). " "Your project may not work properly until you apply the " "migrations for app(s): %(apps_waiting_migration)s." % { "unapplied_migration_count": len(plan), "apps_waiting_migration": ", ".join(apps_waiting_migration), } ) ) self.stdout.write( self.style.NOTICE("Run 'python manage.py migrate' to apply them.") ) def handle(self, *args, **options): """ The actual logic of the command. Subclasses must implement this method. """ raise NotImplementedError( "subclasses of BaseCommand must provide a handle() method" ) class AppCommand(BaseCommand): """ A management command which takes one or more installed application labels as arguments, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_app_config()``, which will be called once for each application. """ missing_args_message = "Enter at least one application label." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="+", help="One or more application label.", ) def handle(self, *app_labels, **options): from django.apps import apps try: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] except (LookupError, ImportError) as e: raise CommandError( "%s. Are you sure your INSTALLED_APPS setting is correct?" % e ) output = [] for app_config in app_configs: app_output = self.handle_app_config(app_config, **options) if app_output: output.append(app_output) return "\n".join(output) def handle_app_config(self, app_config, **options): """ Perform the command's actions for app_config, an AppConfig instance corresponding to an application label given on the command line. """ raise NotImplementedError( "Subclasses of AppCommand must provide a handle_app_config() method." ) class LabelCommand(BaseCommand): """ A management command which takes one or more arbitrary arguments (labels) on the command line, and does something with each of them. Rather than implementing ``handle()``, subclasses must implement ``handle_label()``, which will be called once for each label. If the arguments should be names of installed applications, use ``AppCommand`` instead. """ label = "label" missing_args_message = "Enter at least one %s." def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.missing_args_message == LabelCommand.missing_args_message: self.missing_args_message = self.missing_args_message % self.label def add_arguments(self, parser): parser.add_argument("args", metavar=self.label, nargs="+") def handle(self, *labels, **options): output = [] for label in labels: label_output = self.handle_label(label, **options) if label_output: output.append(label_output) return "\n".join(output) def handle_label(self, label, **options): """ Perform the command's actions for ``label``, which will be the string as given on the command line. """ raise NotImplementedError( "subclasses of LabelCommand must provide a handle_label() method" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/shell.py
django/core/management/commands/shell.py
import os import select import sys import traceback from collections import defaultdict from importlib import import_module from django.apps import apps from django.core.exceptions import AppRegistryNotReady from django.core.management import BaseCommand, CommandError from django.utils.datastructures import OrderedSet from django.utils.module_loading import import_string as import_dotted_path class Command(BaseCommand): help = ( "Runs a Python interactive interpreter. Tries to use IPython or " "bpython, if one of them is available. Any standard input is executed " "as code." ) requires_system_checks = [] shells = ["ipython", "bpython", "python"] def add_arguments(self, parser): parser.add_argument( "--no-startup", action="store_true", help=( "When using plain Python, ignore the PYTHONSTARTUP environment " "variable and ~/.pythonrc.py script." ), ) parser.add_argument( "--no-imports", action="store_true", help="Disable automatic imports of models.", ) parser.add_argument( "-i", "--interface", choices=self.shells, help=( "Specify an interactive interpreter interface. Available options: " '"ipython", "bpython", and "python"' ), ) parser.add_argument( "-c", "--command", help=( "Instead of opening an interactive shell, run a command as Django and " "exit." ), ) def ipython(self, options): from IPython import start_ipython start_ipython(argv=[], user_ns=self.get_namespace(**options)) def bpython(self, options): import bpython bpython.embed(self.get_namespace(**options)) def python(self, options): import code # Set up a dictionary to serve as the environment for the shell. imported_objects = self.get_namespace(**options) # We want to honor both $PYTHONSTARTUP and .pythonrc.py, so follow # system conventions and get $PYTHONSTARTUP first then .pythonrc.py. if not options["no_startup"]: for pythonrc in OrderedSet( [os.environ.get("PYTHONSTARTUP"), os.path.expanduser("~/.pythonrc.py")] ): if not pythonrc: continue if not os.path.isfile(pythonrc): continue with open(pythonrc) as handle: pythonrc_code = handle.read() # Match the behavior of the cpython shell where an error in # PYTHONSTARTUP prints an exception and continues. try: exec(compile(pythonrc_code, pythonrc, "exec"), imported_objects) except Exception: traceback.print_exc() # By default, this will set up readline to do tab completion and to # read and write history to the .python_history file, but this can be # overridden by $PYTHONSTARTUP or ~/.pythonrc.py. try: hook = sys.__interactivehook__ except AttributeError: # Match the behavior of the cpython shell where a missing # sys.__interactivehook__ is ignored. pass else: try: hook() except Exception: # Match the behavior of the cpython shell where an error in # sys.__interactivehook__ prints a warning and the exception # and continues. print("Failed calling sys.__interactivehook__") traceback.print_exc() # Set up tab completion for objects imported by $PYTHONSTARTUP or # ~/.pythonrc.py. try: import readline import rlcompleter readline.set_completer(rlcompleter.Completer(imported_objects).complete) except ImportError: pass # Start the interactive interpreter. code.interact(local=imported_objects) def get_auto_imports(self): """Return a sequence of import paths for objects to be auto-imported. By default, import paths for models in INSTALLED_APPS and some common utilities are included, with models from earlier apps taking precedence in case of a name collision. For example, for an unchanged INSTALLED_APPS, this method returns: [ "django.conf.settings", "django.db.connection", "django.db.models", "django.db.models.functions", "django.db.reset_queries", "django.utils.timezone", "django.contrib.sessions.models.Session", "django.contrib.contenttypes.models.ContentType", "django.contrib.auth.models.User", "django.contrib.auth.models.Group", "django.contrib.auth.models.Permission", "django.contrib.admin.models.LogEntry", ] """ default_imports = [ "django.conf.settings", "django.db.connection", "django.db.models", "django.db.models.functions", "django.db.reset_queries", "django.utils.timezone", ] app_models_imports = default_imports + [ f"{model.__module__}.{model.__name__}" for model in reversed(apps.get_models()) if model.__module__ ] return app_models_imports def get_namespace(self, **options): if options and options.get("no_imports"): return {} verbosity = options["verbosity"] if options else 0 try: apps.check_models_ready() except AppRegistryNotReady: if verbosity > 0: settings_env_var = os.getenv("DJANGO_SETTINGS_MODULE") self.stdout.write( "Automatic imports are disabled since settings are not configured." f"\nDJANGO_SETTINGS_MODULE value is {settings_env_var!r}.\n" "HINT: Ensure that the settings module is configured and set.", self.style.ERROR, ending="\n\n", ) return {} path_imports = self.get_auto_imports() if path_imports is None: return {} auto_imports = defaultdict(list) import_errors = [] for path in path_imports: try: obj = import_dotted_path(path) if "." in path else import_module(path) except ImportError: import_errors.append(path) continue if "." in path: module, name = path.rsplit(".", 1) else: module = None name = path if (name, obj) not in auto_imports[module]: auto_imports[module].append((name, obj)) namespace = { name: obj for items in auto_imports.values() for name, obj in items } if verbosity < 1: return namespace errors = len(import_errors) if errors: msg = "\n".join(f" {e}" for e in import_errors) objects = "objects" if errors != 1 else "object" self.stdout.write( f"{errors} {objects} could not be automatically imported:\n\n{msg}", self.style.ERROR, ending="\n\n", ) amount = len(namespace) objects_str = "objects" if amount != 1 else "object" msg = f"{amount} {objects_str} imported automatically" if verbosity < 2: if amount: msg += " (use -v 2 for details)" self.stdout.write(f"{msg}.", self.style.SUCCESS, ending="\n\n") return namespace top_level = auto_imports.pop(None, []) import_string = "\n".join( [f" import {obj}" for obj, _ in top_level] + [ f" from {module} import {objects}" for module, imported_objects in auto_imports.items() if (objects := ", ".join(i[0] for i in imported_objects)) ] ) try: import isort except ImportError: pass else: import_string = isort.code(import_string) if import_string: msg = f"{msg}:\n\n{import_string}" else: msg = f"{msg}." self.stdout.write(msg, self.style.SUCCESS, ending="\n\n") return namespace def handle(self, **options): # Execute the command and exit. if options["command"]: exec(options["command"], {**globals(), **self.get_namespace(**options)}) return # Execute stdin if it has anything to read and exit. # Not supported on Windows due to select.select() limitations. if ( sys.platform != "win32" and not sys.stdin.isatty() and select.select([sys.stdin], [], [], 0)[0] ): exec(sys.stdin.read(), {**globals(), **self.get_namespace(**options)}) return available_shells = ( [options["interface"]] if options["interface"] else self.shells ) for shell in available_shells: try: return getattr(self, shell)(options) except ImportError: pass raise CommandError("Couldn't import {} interface.".format(shell))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/migrate.py
django/core/management/commands/migrate.py
import sys import time from importlib import import_module from django.apps import apps from django.core.management.base import BaseCommand, CommandError, no_translations from django.core.management.sql import emit_post_migrate_signal, emit_pre_migrate_signal from django.db import DEFAULT_DB_ALIAS, connections, router from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.executor import MigrationExecutor from django.db.migrations.loader import AmbiguityError from django.db.migrations.state import ModelState, ProjectState from django.utils.module_loading import module_has_submodule from django.utils.text import Truncator class Command(BaseCommand): autodetector = MigrationAutodetector help = ( "Updates database schema. Manages both apps with migrations and those without." ) def add_arguments(self, parser): parser.add_argument( "app_label", nargs="?", help="App label of an application to synchronize the state.", ) parser.add_argument( "migration_name", nargs="?", help="Database state will be brought to the state after that " 'migration. Use the name "zero" to unapply all migrations.', ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( 'Nominates a database to synchronize. Defaults to the "default" ' "database." ), ) parser.add_argument( "--fake", action="store_true", help="Mark migrations as run without actually running them.", ) parser.add_argument( "--fake-initial", action="store_true", help=( "Detect if tables already exist and fake-apply initial migrations if " "so. Make sure that the current database schema matches your initial " "migration before using this flag. Django will only check for an " "existing table name." ), ) parser.add_argument( "--plan", action="store_true", help="Shows a list of the migration actions that will be performed.", ) parser.add_argument( "--run-syncdb", action="store_true", help="Creates tables for apps without migrations.", ) parser.add_argument( "--check", action="store_true", dest="check_unapplied", help=( "Exits with a non-zero status if unapplied migrations exist and does " "not actually apply migrations." ), ) parser.add_argument( "--prune", action="store_true", dest="prune", help="Delete nonexistent migrations from the django_migrations table.", ) def get_check_kwargs(self, options): kwargs = super().get_check_kwargs(options) return {**kwargs, "databases": [options["database"]]} @no_translations def handle(self, *args, **options): database = options["database"] self.verbosity = options["verbosity"] self.interactive = options["interactive"] # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): if module_has_submodule(app_config.module, "management"): import_module(".management", app_config.name) # Get the database we're operating from connection = connections[database] # Hook for backends needing any database preparation connection.prepare_database() # Work out which apps have migrations and which do not executor = MigrationExecutor(connection, self.migration_progress_callback) # Raise an error if any migrations are applied before their # dependencies. executor.loader.check_consistent_history(connection) # Before anything else, see if there's conflicting apps and drop out # hard if there are any conflicts = executor.loader.detect_conflicts() if conflicts: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they supplied command line arguments, work out what they mean. run_syncdb = options["run_syncdb"] target_app_labels_only = True if options["app_label"]: # Validate app_label. app_label = options["app_label"] try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if run_syncdb: if app_label in executor.loader.migrated_apps: raise CommandError( "Can't use run_syncdb with app '%s' as it has migrations." % app_label ) elif app_label not in executor.loader.migrated_apps: raise CommandError("App '%s' does not have migrations." % app_label) if options["app_label"] and options["migration_name"]: migration_name = options["migration_name"] if migration_name == "zero": targets = [(app_label, None)] else: try: migration = executor.loader.get_migration_by_prefix( app_label, migration_name ) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. " "Please be more specific." % (migration_name, app_label) ) except KeyError: raise CommandError( "Cannot find a migration matching '%s' from app '%s'." % (migration_name, app_label) ) target = (app_label, migration.name) # Partially applied squashed migrations are not included in the # graph, use the last replacement instead. if ( target not in executor.loader.graph.nodes and target in executor.loader.replacements ): incomplete_migration = executor.loader.replacements[target] target = incomplete_migration.replaces[-1] targets = [target] target_app_labels_only = False elif options["app_label"]: targets = [ key for key in executor.loader.graph.leaf_nodes() if key[0] == app_label ] else: targets = executor.loader.graph.leaf_nodes() if options["prune"]: if not options["app_label"]: raise CommandError( "Migrations can be pruned only when an app is specified." ) if self.verbosity > 0: self.stdout.write("Pruning migrations:", self.style.MIGRATE_HEADING) to_prune = sorted( migration for migration in set(executor.loader.applied_migrations) - set(executor.loader.disk_migrations) if migration[0] == app_label ) squashed_migrations_with_deleted_replaced_migrations = [ migration_key for migration_key, migration_obj in executor.loader.replacements.items() if any(replaced in to_prune for replaced in migration_obj.replaces) ] if squashed_migrations_with_deleted_replaced_migrations: self.stdout.write( self.style.NOTICE( " Cannot use --prune because the following squashed " "migrations have their 'replaces' attributes and may not " "be recorded as applied:" ) ) for migration in squashed_migrations_with_deleted_replaced_migrations: app, name = migration self.stdout.write(f" {app}.{name}") self.stdout.write( self.style.NOTICE( " Re-run 'manage.py migrate' if they are not marked as " "applied, and remove 'replaces' attributes in their " "Migration classes." ) ) else: if to_prune: for migration in to_prune: app, name = migration if self.verbosity > 0: self.stdout.write( self.style.MIGRATE_LABEL(f" Pruning {app}.{name}"), ending="", ) executor.recorder.record_unapplied(app, name) if self.verbosity > 0: self.stdout.write(self.style.SUCCESS(" OK")) elif self.verbosity > 0: self.stdout.write(" No migrations to prune.") plan = executor.migration_plan(targets) if options["plan"]: self.stdout.write("Planned operations:", self.style.MIGRATE_LABEL) if not plan: self.stdout.write(" No planned migration operations.") else: for migration, backwards in plan: self.stdout.write(str(migration), self.style.MIGRATE_HEADING) for operation in migration.operations: message, is_error = self.describe_operation( operation, backwards ) style = self.style.WARNING if is_error else None self.stdout.write(" " + message, style) if options["check_unapplied"]: sys.exit(1) return if options["check_unapplied"]: if plan: sys.exit(1) return if options["prune"]: return # At this point, ignore run_syncdb if there aren't any apps to sync. run_syncdb = options["run_syncdb"] and executor.loader.unmigrated_apps # Print some useful info if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Operations to perform:")) if run_syncdb: if options["app_label"]: self.stdout.write( self.style.MIGRATE_LABEL( " Synchronize unmigrated app: %s" % app_label ) ) else: self.stdout.write( self.style.MIGRATE_LABEL(" Synchronize unmigrated apps: ") + (", ".join(sorted(executor.loader.unmigrated_apps))) ) if target_app_labels_only: self.stdout.write( self.style.MIGRATE_LABEL(" Apply all migrations: ") + (", ".join(sorted({a for a, n in targets})) or "(none)") ) else: if targets[0][1] is None: self.stdout.write( self.style.MIGRATE_LABEL(" Unapply all migrations: ") + str(targets[0][0]) ) else: self.stdout.write( self.style.MIGRATE_LABEL(" Target specific migration: ") + "%s, from %s" % (targets[0][1], targets[0][0]) ) pre_migrate_state = executor._create_project_state(with_applied_migrations=True) pre_migrate_apps = pre_migrate_state.apps emit_pre_migrate_signal( self.verbosity, self.interactive, connection.alias, stdout=self.stdout, apps=pre_migrate_apps, plan=plan, ) # Run the syncdb phase. if run_syncdb: if self.verbosity >= 1: self.stdout.write( self.style.MIGRATE_HEADING("Synchronizing apps without migrations:") ) if options["app_label"]: self.sync_apps(connection, [app_label]) else: self.sync_apps(connection, executor.loader.unmigrated_apps) # Migrate! if self.verbosity >= 1: self.stdout.write(self.style.MIGRATE_HEADING("Running migrations:")) if not plan: if self.verbosity >= 1: self.stdout.write(" No migrations to apply.") # If there's changes that aren't in migrations yet, tell them # how to fix it. autodetector = self.autodetector( executor.loader.project_state(), ProjectState.from_apps(apps), ) changes = autodetector.changes(graph=executor.loader.graph) if changes: self.stdout.write( self.style.NOTICE( " Your models in app(s): %s have changes that are not " "yet reflected in a migration, and so won't be " "applied." % ", ".join(repr(app) for app in sorted(changes)) ) ) self.stdout.write( self.style.NOTICE( " Run 'manage.py makemigrations' to make new " "migrations, and then re-run 'manage.py migrate' to " "apply them." ) ) fake = False fake_initial = False else: fake = options["fake"] fake_initial = options["fake_initial"] post_migrate_state = executor.migrate( targets, plan=plan, state=pre_migrate_state.clone(), fake=fake, fake_initial=fake_initial, ) # post_migrate signals have access to all models. Ensure that all # models are reloaded in case any are delayed. post_migrate_state.clear_delayed_apps_cache() post_migrate_apps = post_migrate_state.apps # Re-render models of real apps to include relationships now that # we've got a final state. This wouldn't be necessary if real apps # models were rendered with relationships in the first place. with post_migrate_apps.bulk_update(): model_keys = [] for model_state in post_migrate_apps.real_models: model_key = model_state.app_label, model_state.name_lower model_keys.append(model_key) post_migrate_apps.unregister_model(*model_key) post_migrate_apps.render_multiple( [ModelState.from_model(apps.get_model(*model)) for model in model_keys] ) # Send the post_migrate signal, so individual apps can do whatever they # need to do at this point. emit_post_migrate_signal( self.verbosity, self.interactive, connection.alias, stdout=self.stdout, apps=post_migrate_apps, plan=plan, ) def migration_progress_callback(self, action, migration=None, fake=False): if self.verbosity >= 1: compute_time = self.verbosity > 1 if action == "apply_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Applying %s..." % migration, ending="") self.stdout.flush() elif action == "apply_success": elapsed = ( " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" ) if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "unapply_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Unapplying %s..." % migration, ending="") self.stdout.flush() elif action == "unapply_success": elapsed = ( " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" ) if fake: self.stdout.write(self.style.SUCCESS(" FAKED" + elapsed)) else: self.stdout.write(self.style.SUCCESS(" OK" + elapsed)) elif action == "render_start": if compute_time: self.start = time.monotonic() self.stdout.write(" Rendering model states...", ending="") self.stdout.flush() elif action == "render_success": elapsed = ( " (%.3fs)" % (time.monotonic() - self.start) if compute_time else "" ) self.stdout.write(self.style.SUCCESS(" DONE" + elapsed)) def sync_apps(self, connection, app_labels): """Run the old syncdb-style operation on a list of app_labels.""" with connection.cursor() as cursor: tables = connection.introspection.table_names(cursor) # Build the manifest of apps and models that are to be synchronized. all_models = [ ( app_config.label, router.get_migratable_models( app_config, connection.alias, include_auto_created=False ), ) for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config.label in app_labels ] def model_installed(model): opts = model._meta converter = connection.introspection.identifier_converter return not ( (converter(opts.db_table) in tables) or ( opts.auto_created and converter(opts.auto_created._meta.db_table) in tables ) ) manifest = { app_name: list(filter(model_installed, model_list)) for app_name, model_list in all_models } # Create the tables for each model if self.verbosity >= 1: self.stdout.write(" Creating tables...") with connection.schema_editor() as editor: for app_name, model_list in manifest.items(): for model in model_list: # Never install unmanaged models, etc. if not model._meta.can_migrate(connection): continue if self.verbosity >= 3: self.stdout.write( " Processing %s.%s model" % (app_name, model._meta.object_name) ) if self.verbosity >= 1: self.stdout.write( " Creating table %s" % model._meta.db_table ) editor.create_model(model) # Deferred SQL is executed when exiting the editor's context. if self.verbosity >= 1: self.stdout.write(" Running deferred SQL...") @staticmethod def describe_operation(operation, backwards): """Return a string that describes a migration operation for --plan.""" prefix = "" is_error = False if hasattr(operation, "code"): code = operation.reverse_code if backwards else operation.code action = (code.__doc__ or "") if code else None elif hasattr(operation, "sql"): action = operation.reverse_sql if backwards else operation.sql else: action = "" if backwards: prefix = "Undo " if action is not None: action = str(action).replace("\n", "") elif backwards: action = "IRREVERSIBLE" is_error = True if action: action = " -> " + action truncated = Truncator(action) return prefix + operation.describe() + truncated.chars(40), is_error
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/startapp.py
django/core/management/commands/startapp.py
from django.core.management.templates import TemplateCommand class Command(TemplateCommand): help = ( "Creates a Django app directory structure for the given app name in " "the current directory or optionally in the given directory." ) missing_args_message = "You must provide an application name." def handle(self, **options): app_name = options.pop("name") target = options.pop("directory") super().handle("app", app_name, target, **options)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/check.py
django/core/management/commands/check.py
from django.apps import apps from django.core import checks from django.core.checks.registry import registry from django.core.management.base import BaseCommand, CommandError from django.db import connections class Command(BaseCommand): help = "Checks the entire Django project for potential problems." requires_system_checks = [] def add_arguments(self, parser): parser.add_argument("args", metavar="app_label", nargs="*") parser.add_argument( "--tag", "-t", action="append", dest="tags", help="Run only checks labeled with given tag.", ) parser.add_argument( "--list-tags", action="store_true", help=( "List available tags. Specify --deploy to include available deployment " "tags." ), ) parser.add_argument( "--deploy", action="store_true", help="Check deployment settings.", ) parser.add_argument( "--fail-level", default="ERROR", choices=["CRITICAL", "ERROR", "WARNING", "INFO", "DEBUG"], help=( "Message level that will cause the command to exit with a " "non-zero status. Default is ERROR." ), ) parser.add_argument( "--database", action="append", choices=tuple(connections), dest="databases", help="Run database related checks against these aliases.", ) def handle(self, *app_labels, **options): include_deployment_checks = options["deploy"] if options["list_tags"]: self.stdout.write( "\n".join(sorted(registry.tags_available(include_deployment_checks))) ) return if app_labels: app_configs = [apps.get_app_config(app_label) for app_label in app_labels] else: app_configs = None tags = options["tags"] if tags: try: invalid_tag = next( tag for tag in tags if not checks.tag_exists(tag, include_deployment_checks) ) except StopIteration: # no invalid tags pass else: raise CommandError( 'There is no system check with the "%s" tag.' % invalid_tag ) self.check( app_configs=app_configs, tags=tags, display_num_errors=True, include_deployment_checks=include_deployment_checks, fail_level=getattr(checks, options["fail_level"]), databases=options["databases"], )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/flush.py
django/core/management/commands/flush.py
from importlib import import_module from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal, sql_flush from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Removes ALL DATA from the database, including data added during " 'migrations. Does not achieve a "fresh install" state.' ) stealth_options = ("reset_sequences", "allow_cascade", "inhibit_post_migrate") def add_arguments(self, parser): parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help='Nominates a database to flush. Defaults to the "default" database.', ) def handle(self, **options): database = options["database"] connection = connections[database] verbosity = options["verbosity"] interactive = options["interactive"] # The following are stealth options used by Django's internals. reset_sequences = options.get("reset_sequences", True) allow_cascade = options.get("allow_cascade", False) inhibit_post_migrate = options.get("inhibit_post_migrate", False) self.style = no_style() # Import the 'management' module within each installed app, to register # dispatcher events. for app_config in apps.get_app_configs(): try: import_module(".management", app_config.name) except ImportError: pass sql_list = sql_flush( self.style, connection, reset_sequences=reset_sequences, allow_cascade=allow_cascade, ) if interactive: confirm = input( """You have requested a flush of the database. This will IRREVERSIBLY DESTROY all data currently in the "%s" database, and return each table to an empty state. Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: """ % connection.settings_dict["NAME"] ) else: confirm = "yes" if confirm == "yes": try: connection.ops.execute_sql_flush(sql_list) except Exception as exc: raise CommandError( "Database %s couldn't be flushed. Possible reasons:\n" " * The database isn't running or isn't configured correctly.\n" " * At least one of the expected database tables doesn't exist.\n" " * The SQL was invalid.\n" "Hint: Look at the output of 'django-admin sqlflush'. " "That's the SQL this command wasn't able to run." % (connection.settings_dict["NAME"],) ) from exc # Empty sql_list may signify an empty database and post_migrate # would then crash. if sql_list and not inhibit_post_migrate: # Emit the post migrate signal. This allows individual # applications to respond as if the database had been migrated # from scratch. emit_post_migrate_signal(verbosity, interactive, database) else: self.stdout.write("Flush cancelled.")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/optimizemigration.py
django/core/management/commands/optimizemigration.py
import shutil import sys from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import run_formatters from django.db import migrations from django.db.migrations.exceptions import AmbiguityError from django.db.migrations.loader import MigrationLoader from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.writer import MigrationWriter from django.utils.version import get_docs_version class Command(BaseCommand): help = "Optimizes the operations for the named migration." def add_arguments(self, parser): parser.add_argument( "app_label", help="App label of the application to optimize the migration for.", ) parser.add_argument( "migration_name", help="Migration name to optimize the operations for." ) parser.add_argument( "--check", action="store_true", help="Exit with a non-zero status if the migration can be optimized.", ) def handle(self, *args, **options): verbosity = options["verbosity"] app_label = options["app_label"] migration_name = options["migration_name"] check = options["check"] # Validate app_label. try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) # Load the current graph state. loader = MigrationLoader(None) if app_label not in loader.migrated_apps: raise CommandError(f"App '{app_label}' does not have migrations.") # Find a migration. try: migration = loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError( f"More than one migration matches '{migration_name}' in app " f"'{app_label}'. Please be more specific." ) except KeyError: raise CommandError( f"Cannot find a migration matching '{migration_name}' from app " f"'{app_label}'." ) # Optimize the migration. optimizer = MigrationOptimizer() new_operations = optimizer.optimize(migration.operations, migration.app_label) if len(migration.operations) == len(new_operations): if verbosity > 0: self.stdout.write("No optimizations possible.") return else: if verbosity > 0: self.stdout.write( "Optimizing from %d operations to %d operations." % (len(migration.operations), len(new_operations)) ) if check: sys.exit(1) # Set the new migration optimizations. migration.operations = new_operations # Write out the optimized migration file. writer = MigrationWriter(migration) migration_file_string = writer.as_string() if writer.needs_manual_porting: if migration.replaces: raise CommandError( "Migration will require manual porting but is already a squashed " "migration.\nTransition to a normal migration first: " "https://docs.djangoproject.com/en/%s/topics/migrations/" "#squashing-migrations" % get_docs_version() ) # Make a new migration with those operations. subclass = type( "Migration", (migrations.Migration,), { "dependencies": migration.dependencies, "operations": new_operations, "replaces": [(migration.app_label, migration.name)], }, ) optimized_migration_name = "%s_optimized" % migration.name optimized_migration = subclass(optimized_migration_name, app_label) writer = MigrationWriter(optimized_migration) migration_file_string = writer.as_string() if verbosity > 0: self.stdout.write( self.style.MIGRATE_HEADING("Manual porting required") + "\n" " Your migrations contained functions that must be manually " "copied over,\n" " as we could not safely copy their implementation.\n" " See the comment at the top of the optimized migration for " "details." ) if shutil.which("black"): self.stdout.write( self.style.WARNING( "Optimized migration couldn't be formatted using the " '"black" command. You can call it manually.' ) ) with open(writer.path, "w", encoding="utf-8") as fh: fh.write(migration_file_string) run_formatters([writer.path], stderr=self.stderr) if verbosity > 0: self.stdout.write( self.style.MIGRATE_HEADING(f"Optimized migration {writer.path}") )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/loaddata.py
django/core/management/commands/loaddata.py
import functools import glob import gzip import os import sys import warnings import zipfile from itertools import product from django.apps import apps from django.conf import settings from django.core import serializers from django.core.exceptions import ImproperlyConfigured from django.core.management.base import BaseCommand, CommandError from django.core.management.color import no_style from django.core.management.utils import parse_apps_and_model_labels from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, IntegrityError, connections, router, transaction, ) from django.utils.functional import cached_property try: import bz2 has_bz2 = True except ImportError: has_bz2 = False try: import lzma has_lzma = True except ImportError: has_lzma = False READ_STDIN = "-" class Command(BaseCommand): help = "Installs the named fixture(s) in the database." missing_args_message = ( "No database fixture specified. Please provide the path of at least " "one fixture in the command line." ) def add_arguments(self, parser): parser.add_argument( "args", metavar="fixture", nargs="+", help="Fixture labels." ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( "Nominates a specific database to load fixtures into. Defaults to the " '"default" database.' ), ) parser.add_argument( "--app", dest="app_label", help="Only look for fixtures in the specified app.", ) parser.add_argument( "--ignorenonexistent", "-i", action="store_true", dest="ignore", help="Ignores entries in the serialized data for fields that do not " "currently exist on the model.", ) parser.add_argument( "-e", "--exclude", action="append", default=[], help=( "An app_label or app_label.ModelName to exclude. Can be used multiple " "times." ), ) parser.add_argument( "--format", help="Format of serialized data when reading from stdin.", ) def handle(self, *fixture_labels, **options): self.ignore = options["ignore"] self.using = options["database"] self.app_label = options["app_label"] self.verbosity = options["verbosity"] self.excluded_models, self.excluded_apps = parse_apps_and_model_labels( options["exclude"] ) self.format = options["format"] with transaction.atomic(using=self.using): self.loaddata(fixture_labels) # Close the DB connection -- unless we're still in a transaction. This # is required as a workaround for an edge case in MySQL: if the same # connection is used to create tables, load data, and query, the query # can return incorrect results. See Django #7572, MySQL #37735. if transaction.get_autocommit(self.using): connections[self.using].close() @cached_property def compression_formats(self): """A dict mapping format names to (open function, mode arg) tuples.""" # Forcing binary mode may be revisited after dropping Python 2 support # (see #22399). compression_formats = { None: (open, "rb"), "gz": (gzip.GzipFile, "rb"), "zip": (SingleZipReader, "r"), "stdin": (lambda *args: sys.stdin, None), } if has_bz2: compression_formats["bz2"] = (bz2.BZ2File, "r") if has_lzma: compression_formats["lzma"] = (lzma.LZMAFile, "r") compression_formats["xz"] = (lzma.LZMAFile, "r") return compression_formats def reset_sequences(self, connection, models): """Reset database sequences for the given connection and models.""" sequence_sql = connection.ops.sequence_reset_sql(no_style(), models) if sequence_sql: if self.verbosity >= 2: self.stdout.write("Resetting sequences") with connection.cursor() as cursor: for line in sequence_sql: cursor.execute(line) def loaddata(self, fixture_labels): connection = connections[self.using] # Keep a count of the installed objects and fixtures self.fixture_count = 0 self.loaded_object_count = 0 self.fixture_object_count = 0 self.models = set() self.serialization_formats = serializers.get_public_serializer_formats() # Django's test suite repeatedly tries to load initial_data fixtures # from apps that don't have any fixtures. Because disabling constraint # checks can be expensive on some database (especially MSSQL), bail # out early if no fixtures are found. for fixture_label in fixture_labels: if self.find_fixtures(fixture_label): break else: return self.objs_with_deferred_fields = [] with connection.constraint_checks_disabled(): for fixture_label in fixture_labels: self.load_label(fixture_label) for obj in self.objs_with_deferred_fields: obj.save_deferred_fields(using=self.using) # Since we disabled constraint checks, we must manually check for # any invalid keys that might have been added table_names = [model._meta.db_table for model in self.models] try: connection.check_constraints(table_names=table_names) except Exception as e: e.args = ("Problem installing fixtures: %s" % e,) raise # If we found even one object in a fixture, we need to reset the # database sequences. if self.loaded_object_count > 0: self.reset_sequences(connection, self.models) if self.verbosity >= 1: if self.fixture_object_count == self.loaded_object_count: self.stdout.write( "Installed %d object(s) from %d fixture(s)" % (self.loaded_object_count, self.fixture_count) ) else: self.stdout.write( "Installed %d object(s) (of %d) from %d fixture(s)" % ( self.loaded_object_count, self.fixture_object_count, self.fixture_count, ) ) def save_obj(self, obj): """Save an object if permitted.""" if ( obj.object._meta.app_config in self.excluded_apps or type(obj.object) in self.excluded_models ): return False saved = False if router.allow_migrate_model(self.using, obj.object.__class__): saved = True self.models.add(obj.object.__class__) try: obj.save(using=self.using) # psycopg raises ValueError if data contains NUL chars. except (DatabaseError, IntegrityError, ValueError) as e: e.args = ( "Could not load %(object_label)s(pk=%(pk)s): %(error_msg)s" % { "object_label": obj.object._meta.label, "pk": obj.object.pk, "error_msg": e, }, ) raise if obj.deferred_fields: self.objs_with_deferred_fields.append(obj) return saved def load_label(self, fixture_label): """Load fixtures files for a given label.""" show_progress = self.verbosity >= 3 for fixture_file, fixture_dir, fixture_name in self.find_fixtures( fixture_label ): _, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file)) open_method, mode = self.compression_formats[cmp_fmt] fixture = open_method(fixture_file, mode) self.fixture_count += 1 objects_in_fixture = 0 loaded_objects_in_fixture = 0 if self.verbosity >= 2: self.stdout.write( "Installing %s fixture '%s' from %s." % (ser_fmt, fixture_name, humanize(fixture_dir)) ) try: objects = serializers.deserialize( ser_fmt, fixture, using=self.using, ignorenonexistent=self.ignore, handle_forward_references=True, ) for obj in objects: objects_in_fixture += 1 if self.save_obj(obj): loaded_objects_in_fixture += 1 if show_progress: self.stdout.write( "\rProcessed %i object(s)." % loaded_objects_in_fixture, ending="", ) except Exception as e: if not isinstance(e, CommandError): e.args = ( "Problem installing fixture '%s': %s" % (fixture_file, e), ) raise finally: fixture.close() if objects_in_fixture and show_progress: self.stdout.write() # Add a newline after progress indicator. self.loaded_object_count += loaded_objects_in_fixture self.fixture_object_count += objects_in_fixture # Warn if the fixture we loaded contains 0 objects. if objects_in_fixture == 0: warnings.warn( "No fixture data found for '%s'. (File format may be " "invalid.)" % fixture_name, RuntimeWarning, ) def get_fixture_name_and_dirs(self, fixture_name): dirname, basename = os.path.split(fixture_name) if os.path.isabs(fixture_name): fixture_dirs = [dirname] else: fixture_dirs = self.fixture_dirs if os.path.sep in os.path.normpath(fixture_name): fixture_dirs = [os.path.join(dir_, dirname) for dir_ in fixture_dirs] return basename, fixture_dirs def get_targets(self, fixture_name, ser_fmt, cmp_fmt): databases = [self.using, None] cmp_fmts = self.compression_formats if cmp_fmt is None else [cmp_fmt] ser_fmts = self.serialization_formats if ser_fmt is None else [ser_fmt] return { "%s.%s" % ( fixture_name, ".".join([ext for ext in combo if ext]), ) for combo in product(databases, ser_fmts, cmp_fmts) } def find_fixture_files_in_dir(self, fixture_dir, fixture_name, targets): fixture_files_in_dir = [] path = os.path.join(fixture_dir, fixture_name) for candidate in glob.iglob(glob.escape(path) + "*"): if os.path.basename(candidate) in targets: # Save the fixture_dir and fixture_name for future error # messages. fixture_files_in_dir.append((candidate, fixture_dir, fixture_name)) return fixture_files_in_dir @functools.cache def find_fixtures(self, fixture_label): """Find fixture files for a given label.""" if fixture_label == READ_STDIN: return [(READ_STDIN, None, READ_STDIN)] fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label) if self.verbosity >= 2: self.stdout.write("Loading '%s' fixtures..." % fixture_name) fixture_name, fixture_dirs = self.get_fixture_name_and_dirs(fixture_name) targets = self.get_targets(fixture_name, ser_fmt, cmp_fmt) fixture_files = [] for fixture_dir in fixture_dirs: if self.verbosity >= 2: self.stdout.write("Checking %s for fixtures..." % humanize(fixture_dir)) fixture_files_in_dir = self.find_fixture_files_in_dir( fixture_dir, fixture_name, targets, ) if self.verbosity >= 2 and not fixture_files_in_dir: self.stdout.write( "No fixture '%s' in %s." % (fixture_name, humanize(fixture_dir)) ) # Check kept for backwards-compatibility; it isn't clear why # duplicates are only allowed in different directories. if len(fixture_files_in_dir) > 1: raise CommandError( "Multiple fixtures named '%s' in %s. Aborting." % (fixture_name, humanize(fixture_dir)) ) fixture_files.extend(fixture_files_in_dir) if not fixture_files: raise CommandError("No fixture named '%s' found." % fixture_name) return fixture_files @cached_property def fixture_dirs(self): """ Return a list of fixture directories. The list contains the 'fixtures' subdirectory of each installed application, if it exists, the directories in FIXTURE_DIRS, and the current directory. """ dirs = [] fixture_dirs = settings.FIXTURE_DIRS if len(fixture_dirs) != len(set(fixture_dirs)): raise ImproperlyConfigured("settings.FIXTURE_DIRS contains duplicates.") for app_config in apps.get_app_configs(): app_label = app_config.label app_dir = os.path.join(app_config.path, "fixtures") if app_dir in [str(d) for d in fixture_dirs]: raise ImproperlyConfigured( "'%s' is a default fixture directory for the '%s' app " "and cannot be listed in settings.FIXTURE_DIRS." % (app_dir, app_label) ) if self.app_label and app_label != self.app_label: continue if os.path.isdir(app_dir): dirs.append(app_dir) dirs.extend(fixture_dirs) dirs.append("") return [os.path.realpath(d) for d in dirs] def parse_name(self, fixture_name): """ Split fixture name in name, serialization format, compression format. """ if fixture_name == READ_STDIN: if not self.format: raise CommandError( "--format must be specified when reading from stdin." ) return READ_STDIN, self.format, "stdin" parts = fixture_name.rsplit(".", 2) if len(parts) > 1 and parts[-1] in self.compression_formats: cmp_fmt = parts[-1] parts = parts[:-1] else: cmp_fmt = None if len(parts) > 1: if parts[-1] in self.serialization_formats: ser_fmt = parts[-1] parts = parts[:-1] else: raise CommandError( "Problem installing fixture '%s': %s is not a known " "serialization format." % (".".join(parts[:-1]), parts[-1]) ) else: ser_fmt = None name = ".".join(parts) return name, ser_fmt, cmp_fmt class SingleZipReader(zipfile.ZipFile): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if len(self.namelist()) != 1: raise ValueError("Zip-compressed fixtures must contain one file.") def read(self): return zipfile.ZipFile.read(self, self.namelist()[0]) def humanize(dirname): return "'%s'" % dirname if dirname else "absolute path"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/sqlsequencereset.py
django/core/management/commands/sqlsequencereset.py
from django.core.management.base import AppCommand from django.db import DEFAULT_DB_ALIAS, connections class Command(AppCommand): help = ( "Prints the SQL statements for resetting sequences for the given app name(s)." ) output_transaction = True def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( 'Nominates a database to print the SQL for. Defaults to the "default" ' "database." ), ) def handle_app_config(self, app_config, **options): if app_config.models_module is None: return connection = connections[options["database"]] models = app_config.get_models(include_auto_created=True) statements = connection.ops.sequence_reset_sql(self.style, models) if not statements and options["verbosity"] >= 1: self.stderr.write("No sequences found.") return "\n".join(statements)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/compilemessages.py
django/core/management/commands/compilemessages.py
import codecs import concurrent.futures import glob import os import tempfile from pathlib import Path from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import find_command, is_ignored_path, popen_wrapper def has_bom(fn): with fn.open("rb") as f: sample = f.read(4) return sample.startswith( (codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE) ) def is_dir_writable(path): try: with tempfile.NamedTemporaryFile(dir=path): pass except OSError: return False return True class Command(BaseCommand): help = "Compiles .po files to .mo files for use with builtin gettext support." requires_system_checks = [] program = "msgfmt" program_options = ["--check-format"] def add_arguments(self, parser): parser.add_argument( "--locale", "-l", action="append", default=[], help="Locale(s) to process (e.g. de_AT). Default is to process all. " "Can be used multiple times.", ) parser.add_argument( "--exclude", "-x", action="append", default=[], help="Locales to exclude. Default is none. Can be used multiple times.", ) parser.add_argument( "--use-fuzzy", "-f", dest="fuzzy", action="store_true", help="Use fuzzy translations.", ) parser.add_argument( "--ignore", "-i", action="append", dest="ignore_patterns", default=[], metavar="PATTERN", help="Ignore directories matching this glob-style pattern. " "Use multiple times to ignore more.", ) def handle(self, **options): locale = options["locale"] exclude = options["exclude"] ignore_patterns = set(options["ignore_patterns"]) self.verbosity = options["verbosity"] if options["fuzzy"]: self.program_options = [*self.program_options, "-f"] if find_command(self.program) is None: raise CommandError( f"Can't find {self.program}. Make sure you have GNU gettext " "tools 0.19 or newer installed." ) basedirs = [os.path.join("conf", "locale"), "locale"] if os.environ.get("DJANGO_SETTINGS_MODULE"): from django.conf import settings basedirs.extend(settings.LOCALE_PATHS) # Walk entire tree, looking for locale directories for dirpath, dirnames, filenames in os.walk(".", topdown=True): # As we may modify dirnames, iterate through a copy of it instead for dirname in list(dirnames): if is_ignored_path( os.path.normpath(os.path.join(dirpath, dirname)), ignore_patterns ): dirnames.remove(dirname) elif dirname == "locale": basedirs.append(os.path.join(dirpath, dirname)) # Gather existing directories. basedirs = set(map(os.path.abspath, filter(os.path.isdir, basedirs))) if not basedirs: raise CommandError( "This script should be run from the Django Git " "checkout or your project or app tree, or with " "the settings module specified." ) # Build locale list all_locales = [] for basedir in basedirs: locale_dirs = filter(os.path.isdir, glob.glob("%s/*" % basedir)) all_locales.extend(map(os.path.basename, locale_dirs)) # Account for excluded locales locales = locale or all_locales locales = set(locales).difference(exclude) self.has_errors = False for basedir in basedirs: if locales: dirs = [ os.path.join(basedir, locale, "LC_MESSAGES") for locale in locales ] else: dirs = [basedir] locations = [] for ldir in dirs: for dirpath, dirnames, filenames in os.walk(ldir): locations.extend( (dirpath, f) for f in filenames if f.endswith(".po") ) if locations: self.compile_messages(locations) if self.has_errors: raise CommandError("compilemessages generated one or more errors.") def compile_messages(self, locations): """ Locations is a list of tuples: [(directory, file), ...] """ with concurrent.futures.ThreadPoolExecutor() as executor: futures = [] for i, (dirpath, f) in enumerate(locations): po_path = Path(dirpath) / f mo_path = po_path.with_suffix(".mo") try: if mo_path.stat().st_mtime >= po_path.stat().st_mtime: if self.verbosity > 0: self.stdout.write( "File “%s” is already compiled and up to date." % po_path ) continue except FileNotFoundError: pass if self.verbosity > 0: self.stdout.write("processing file %s in %s" % (f, dirpath)) if has_bom(po_path): self.stderr.write( "The %s file has a BOM (Byte Order Mark). Django only " "supports .po files encoded in UTF-8 and without any BOM." % po_path ) self.has_errors = True continue # Check writability on first location if i == 0 and not is_dir_writable(mo_path.parent): self.stderr.write( "The po files under %s are in a seemingly not writable " "location. mo files will not be updated/created." % dirpath ) self.has_errors = True return args = [self.program, *self.program_options, "-o", mo_path, po_path] futures.append(executor.submit(popen_wrapper, args)) for future in concurrent.futures.as_completed(futures): output, errors, status = future.result() if status: if self.verbosity > 0: if errors: self.stderr.write( "Execution of %s failed: %s" % (self.program, errors) ) else: self.stderr.write("Execution of %s failed" % self.program) self.has_errors = True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/showmigrations.py
django/core/management/commands/showmigrations.py
import sys from django.apps import apps from django.core.management.base import BaseCommand from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.loader import MigrationLoader from django.db.migrations.recorder import MigrationRecorder class Command(BaseCommand): help = "Shows all available migrations for the current project" def add_arguments(self, parser): parser.add_argument( "app_label", nargs="*", help="App labels of applications to limit the output to.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( "Nominates a database to show migrations for. Defaults to the " '"default" database.' ), ) formats = parser.add_mutually_exclusive_group() formats.add_argument( "--list", "-l", action="store_const", dest="format", const="list", help=( "Shows a list of all migrations and which are applied. " "With a verbosity level of 2 or above, the applied datetimes " "will be included." ), ) formats.add_argument( "--plan", "-p", action="store_const", dest="format", const="plan", help=( "Shows all migrations in the order they will be applied. With a " "verbosity level of 2 or above all direct migration dependencies and " "reverse dependencies (run_before) will be included." ), ) parser.set_defaults(format="list") def handle(self, *args, **options): self.verbosity = options["verbosity"] # Get the database we're operating from db = options["database"] connection = connections[db] if options["format"] == "plan": return self.show_plan(connection, options["app_label"]) else: return self.show_list(connection, options["app_label"]) def _validate_app_names(self, loader, app_names): has_bad_names = False for app_name in app_names: try: apps.get_app_config(app_name) except LookupError as err: self.stderr.write(str(err)) has_bad_names = True if has_bad_names: sys.exit(2) def show_list(self, connection, app_names=None): """ Show a list of all migrations on the system, or only those of some named apps. """ # Load migrations from disk/DB loader = MigrationLoader(connection, ignore_no_migrations=True) recorder = MigrationRecorder(connection) recorded_migrations = recorder.applied_migrations() graph = loader.graph # If we were passed a list of apps, validate it if app_names: self._validate_app_names(loader, app_names) # Otherwise, show all apps in alphabetic order else: app_names = sorted(loader.migrated_apps) # For each app, print its migrations in order from oldest (roots) to # newest (leaves). for app_name in app_names: self.stdout.write(app_name, self.style.MIGRATE_LABEL) shown = set() for node in graph.leaf_nodes(app_name): for plan_node in graph.forwards_plan(node): if plan_node not in shown and plan_node[0] == app_name: # Give it a nice title if it's a squashed one title = plan_node[1] if graph.nodes[plan_node].replaces: title += " (%s squashed migrations)" % len( graph.nodes[plan_node].replaces ) applied_migration = loader.applied_migrations.get(plan_node) # Mark it as applied/unapplied if applied_migration: if plan_node in recorded_migrations: output = " [X] %s" % title else: title += " Run 'manage.py migrate' to finish recording." output = " [-] %s" % title if self.verbosity >= 2 and hasattr( applied_migration, "applied" ): output += ( " (applied at %s)" % applied_migration.applied.strftime( "%Y-%m-%d %H:%M:%S" ) ) self.stdout.write(output) else: self.stdout.write(" [ ] %s" % title) shown.add(plan_node) # If we didn't print anything, then a small message if not shown: self.stdout.write(" (no migrations)", self.style.ERROR) def show_plan(self, connection, app_names=None): """ Show all known migrations (or only those of the specified app_names) in the order they will be applied. """ # Load migrations from disk/DB loader = MigrationLoader(connection) graph = loader.graph if app_names: self._validate_app_names(loader, app_names) targets = [key for key in graph.leaf_nodes() if key[0] in app_names] else: targets = graph.leaf_nodes() plan = [] seen = set() # Generate the plan for target in targets: for migration in graph.forwards_plan(target): if migration not in seen: node = graph.node_map[migration] plan.append(node) seen.add(migration) # Output def print_deps(node): out = [] for parent in sorted(node.parents): out.append("%s.%s" % parent.key) if out: return " ... (%s)" % ", ".join(out) return "" for node in plan: deps = "" if self.verbosity >= 2: deps = print_deps(node) if node.key in loader.applied_migrations: self.stdout.write("[X] %s.%s%s" % (node.key[0], node.key[1], deps)) else: self.stdout.write("[ ] %s.%s%s" % (node.key[0], node.key[1], deps)) if not plan: self.stdout.write("(no migrations)", self.style.ERROR)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/testserver.py
django/core/management/commands/testserver.py
from django.core.management import call_command from django.core.management.base import BaseCommand from django.db import connection class Command(BaseCommand): help = "Runs a development server with data from the given fixture(s)." requires_system_checks = [] def add_arguments(self, parser): parser.add_argument( "args", metavar="fixture", nargs="*", help="Path(s) to fixtures to load before running the server.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--addrport", default="", help="Port number or ipaddr:port to run the server on.", ) parser.add_argument( "--ipv6", "-6", action="store_true", dest="use_ipv6", help="Tells Django to use an IPv6 address.", ) def handle(self, *fixture_labels, **options): verbosity = options["verbosity"] interactive = options["interactive"] # Create a test database. db_name = connection.creation.create_test_db( verbosity=verbosity, autoclobber=not interactive ) # Import the fixture data into the test database. call_command("loaddata", *fixture_labels, verbosity=verbosity) # Run the development server. Turn off auto-reloading because it causes # a strange error -- it causes this handle() method to be called # multiple times. shutdown_message = ( "\nServer stopped.\nNote that the test database, %r, has not been " "deleted. You can explore it on your own." % db_name ) use_threading = connection.features.test_db_allows_multiple_connections call_command( "runserver", addrport=options["addrport"], shutdown_message=shutdown_message, use_reloader=False, use_ipv6=options["use_ipv6"], use_threading=use_threading, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/squashmigrations.py
django/core/management/commands/squashmigrations.py
import os import shutil from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import run_formatters from django.db import migrations from django.db.migrations.loader import AmbiguityError, MigrationLoader from django.db.migrations.migration import SwappableTuple from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.writer import MigrationWriter class Command(BaseCommand): help = ( "Squashes an existing set of migrations (from first until specified) into a " "single new one." ) def add_arguments(self, parser): parser.add_argument( "app_label", help="App label of the application to squash migrations for.", ) parser.add_argument( "start_migration_name", nargs="?", help=( "Migrations will be squashed starting from and including this " "migration." ), ) parser.add_argument( "migration_name", help="Migrations will be squashed until and including this migration.", ) parser.add_argument( "--no-optimize", action="store_true", help="Do not try to optimize the squashed operations.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--squashed-name", help="Sets the name of the new squashed migration.", ) parser.add_argument( "--no-header", action="store_false", dest="include_header", help="Do not add a header comment to the new squashed migration.", ) def handle(self, **options): self.verbosity = options["verbosity"] self.interactive = options["interactive"] app_label = options["app_label"] start_migration_name = options["start_migration_name"] migration_name = options["migration_name"] no_optimize = options["no_optimize"] squashed_name = options["squashed_name"] include_header = options["include_header"] # Validate app_label. try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) # Load the current graph state, check the app and migration they asked # for exists. loader = MigrationLoader(None) if app_label not in loader.migrated_apps: raise CommandError( "App '%s' does not have migrations (so squashmigrations on " "it makes no sense)" % app_label ) migration = self.find_migration(loader, app_label, migration_name) # Work out the list of predecessor migrations migrations_to_squash = [ loader.get_migration(al, mn) for al, mn in loader.graph.forwards_plan( (migration.app_label, migration.name) ) if al == migration.app_label ] if start_migration_name: start_migration = self.find_migration( loader, app_label, start_migration_name ) start = loader.get_migration( start_migration.app_label, start_migration.name ) try: start_index = migrations_to_squash.index(start) migrations_to_squash = migrations_to_squash[start_index:] except ValueError: raise CommandError( "The migration '%s' cannot be found. Maybe it comes after " "the migration '%s'?\n" "Have a look at:\n" " python manage.py showmigrations %s\n" "to debug this issue." % (start_migration, migration, app_label) ) # Tell them what we're doing and optionally ask if we should proceed if self.verbosity > 0 or self.interactive: self.stdout.write( self.style.MIGRATE_HEADING("Will squash the following migrations:") ) for migration in migrations_to_squash: self.stdout.write(" - %s" % migration.name) if self.interactive: answer = None while not answer or answer not in "yn": answer = input("Do you wish to proceed? [y/N] ") if not answer: answer = "n" break else: answer = answer[0].lower() if answer != "y": return # Load the operations from all those migrations and concat together, # along with collecting external dependencies and detecting # double-squashing operations = [] dependencies = set() # We need to take all dependencies from the first migration in the list # as it may be 0002 depending on 0001 first_migration = True for smigration in migrations_to_squash: operations.extend(smigration.operations) for dependency in smigration.dependencies: if isinstance(dependency, SwappableTuple): if settings.AUTH_USER_MODEL == dependency.setting: dependencies.add(("__setting__", "AUTH_USER_MODEL")) else: dependencies.add(dependency) elif dependency[0] != smigration.app_label or first_migration: dependencies.add(dependency) first_migration = False if no_optimize: if self.verbosity > 0: self.stdout.write( self.style.MIGRATE_HEADING("(Skipping optimization.)") ) new_operations = operations else: if self.verbosity > 0: self.stdout.write(self.style.MIGRATE_HEADING("Optimizing...")) optimizer = MigrationOptimizer() new_operations = optimizer.optimize(operations, migration.app_label) if self.verbosity > 0: if len(new_operations) == len(operations): self.stdout.write(" No optimizations possible.") else: self.stdout.write( " Optimized from %s operations to %s operations." % (len(operations), len(new_operations)) ) replaces = [(m.app_label, m.name) for m in migrations_to_squash] # Make a new migration with those operations subclass = type( "Migration", (migrations.Migration,), { "dependencies": dependencies, "operations": new_operations, "replaces": replaces, }, ) if start_migration_name: if squashed_name: # Use the name from --squashed-name. prefix, _ = start_migration.name.split("_", 1) name = "%s_%s" % (prefix, squashed_name) else: # Generate a name. name = "%s_squashed_%s" % (start_migration.name, migration.name) new_migration = subclass(name, app_label) else: name = "0001_%s" % (squashed_name or "squashed_%s" % migration.name) new_migration = subclass(name, app_label) new_migration.initial = True # Write out the new migration file writer = MigrationWriter(new_migration, include_header) if os.path.exists(writer.path): raise CommandError( f"Migration {new_migration.name} already exists. Use a different name." ) with open(writer.path, "w", encoding="utf-8") as fh: fh.write(writer.as_string()) run_formatters([writer.path], stderr=self.stderr) if self.verbosity > 0: self.stdout.write( self.style.MIGRATE_HEADING( "Created new squashed migration %s" % writer.path ) + "\n" " You should commit this migration but leave the old ones in place;\n" " the new migration will be used for new installs. Once you are sure\n" " all instances of the codebase have applied the migrations you " "squashed,\n" " you can delete them." ) if writer.needs_manual_porting: self.stdout.write( self.style.MIGRATE_HEADING("Manual porting required") + "\n" " Your migrations contained functions that must be manually " "copied over,\n" " as we could not safely copy their implementation.\n" " See the comment at the top of the squashed migration for " "details." ) if shutil.which("black"): self.stdout.write( self.style.WARNING( "Squashed migration couldn't be formatted using the " '"black" command. You can call it manually.' ) ) def find_migration(self, loader, app_label, name): try: return loader.get_migration_by_prefix(app_label, name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. Please be " "more specific." % (name, app_label) ) except KeyError: raise CommandError( "Cannot find a migration matching '%s' from app '%s'." % (name, app_label) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/sqlflush.py
django/core/management/commands/sqlflush.py
from django.core.management.base import BaseCommand from django.core.management.sql import sql_flush from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Returns a list of the SQL statements required to return all tables in " "the database to the state they were in just after they were installed." ) output_transaction = True def add_arguments(self, parser): super().add_arguments(parser) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( 'Nominates a database to print the SQL for. Defaults to the "default" ' "database." ), ) def handle(self, **options): sql_statements = sql_flush(self.style, connections[options["database"]]) if not sql_statements and options["verbosity"] >= 1: self.stderr.write("No tables found.") return "\n".join(sql_statements)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/makemigrations.py
django/core/management/commands/makemigrations.py
import os import sys import warnings from itertools import takewhile from django.apps import apps from django.conf import settings from django.core.management.base import BaseCommand, CommandError, no_translations from django.core.management.utils import run_formatters from django.db import DEFAULT_DB_ALIAS, OperationalError, connections, router from django.db.migrations import Migration from django.db.migrations.autodetector import MigrationAutodetector from django.db.migrations.loader import MigrationLoader from django.db.migrations.migration import SwappableTuple from django.db.migrations.optimizer import MigrationOptimizer from django.db.migrations.questioner import ( InteractiveMigrationQuestioner, MigrationQuestioner, NonInteractiveMigrationQuestioner, ) from django.db.migrations.state import ProjectState from django.db.migrations.utils import get_migration_name_timestamp from django.db.migrations.writer import MigrationWriter class Command(BaseCommand): autodetector = MigrationAutodetector help = "Creates new migration(s) for apps." def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label", nargs="*", help="Specify the app label(s) to create migrations for.", ) parser.add_argument( "--dry-run", action="store_true", help="Just show what migrations would be made; don't actually write them.", ) parser.add_argument( "--merge", action="store_true", help="Enable fixing of migration conflicts.", ) parser.add_argument( "--empty", action="store_true", help="Create an empty migration.", ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "-n", "--name", help="Use this name for migration file(s).", ) parser.add_argument( "--no-header", action="store_false", dest="include_header", help="Do not add header comments to new migration file(s).", ) parser.add_argument( "--check", action="store_true", dest="check_changes", help=( "Exit with a non-zero status if model changes are missing migrations " "and don't actually write them. Implies --dry-run." ), ) parser.add_argument( "--scriptable", action="store_true", dest="scriptable", help=( "Divert log output and input prompts to stderr, writing only " "paths of generated migration files to stdout." ), ) parser.add_argument( "--update", action="store_true", dest="update", help=( "Merge model changes into the latest migration and optimize the " "resulting operations." ), ) @property def log_output(self): return self.stderr if self.scriptable else self.stdout def log(self, msg): self.log_output.write(msg) @no_translations def handle(self, *app_labels, **options): self.written_files = [] self.verbosity = options["verbosity"] self.interactive = options["interactive"] self.dry_run = options["dry_run"] self.merge = options["merge"] self.empty = options["empty"] self.migration_name = options["name"] if self.migration_name and not self.migration_name.isidentifier(): raise CommandError("The migration name must be a valid Python identifier.") self.include_header = options["include_header"] check_changes = options["check_changes"] if check_changes: self.dry_run = True self.scriptable = options["scriptable"] self.update = options["update"] # If logs and prompts are diverted to stderr, remove the ERROR style. if self.scriptable: self.stderr.style_func = None # Make sure the app they asked for exists app_labels = set(app_labels) has_bad_labels = False for app_label in app_labels: try: apps.get_app_config(app_label) except LookupError as err: self.stderr.write(str(err)) has_bad_labels = True if has_bad_labels: sys.exit(2) # Load the current graph state. Pass in None for the connection so # the loader doesn't try to resolve replaced migrations from DB. loader = MigrationLoader(None, ignore_no_migrations=True) # Raise an error if any migrations are applied before their # dependencies. consistency_check_labels = {config.label for config in apps.get_app_configs()} # Non-default databases are only checked if database routers used. aliases_to_check = ( connections if settings.DATABASE_ROUTERS else [DEFAULT_DB_ALIAS] ) for alias in sorted(aliases_to_check): connection = connections[alias] if connection.settings_dict["ENGINE"] != "django.db.backends.dummy" and any( # At least one model must be migrated to the database. router.allow_migrate( connection.alias, app_label, model_name=model._meta.object_name ) for app_label in consistency_check_labels for model in apps.get_app_config(app_label).get_models() ): try: loader.check_consistent_history(connection) except OperationalError as error: warnings.warn( "Got an error checking a consistent migration history " "performed for database connection '%s': %s" % (alias, error), RuntimeWarning, ) # Before anything else, see if there's conflicting apps and drop out # hard if there are any and they don't want to merge conflicts = loader.detect_conflicts() # If app_labels is specified, filter out conflicting migrations for # unspecified apps. if app_labels: conflicts = { app_label: conflict for app_label, conflict in conflicts.items() if app_label in app_labels } if conflicts and not self.merge: name_str = "; ".join( "%s in %s" % (", ".join(names), app) for app, names in conflicts.items() ) raise CommandError( "Conflicting migrations detected; multiple leaf nodes in the " "migration graph: (%s).\nTo fix them run " "'python manage.py makemigrations --merge'" % name_str ) # If they want to merge and there's nothing to merge, then politely # exit if self.merge and not conflicts: self.log("No conflicts detected to merge.") return # If they want to merge and there is something to merge, then # divert into the merge code if self.merge and conflicts: return self.handle_merge(loader, conflicts) if self.interactive: questioner = InteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run, prompt_output=self.log_output, ) else: questioner = NonInteractiveMigrationQuestioner( specified_apps=app_labels, dry_run=self.dry_run, verbosity=self.verbosity, log=self.log, ) # Set up autodetector autodetector = self.autodetector( loader.project_state(), ProjectState.from_apps(apps), questioner, ) # If they want to make an empty migration, make one for each app if self.empty: if not app_labels: raise CommandError( "You must supply at least one app label when using --empty." ) # Make a fake changes() result we can pass to arrange_for_graph changes = {app: [Migration("custom", app)] for app in app_labels} changes = autodetector.arrange_for_graph( changes=changes, graph=loader.graph, migration_name=self.migration_name, ) self.write_migration_files(changes) return # Detect changes changes = autodetector.changes( graph=loader.graph, trim_to_apps=app_labels or None, convert_apps=app_labels or None, migration_name=self.migration_name, ) if not changes: # No changes? Tell them. if self.verbosity >= 1: if app_labels: if len(app_labels) == 1: self.log("No changes detected in app '%s'" % app_labels.pop()) else: self.log( "No changes detected in apps '%s'" % ("', '".join(app_labels)) ) else: self.log("No changes detected") else: if self.update: self.write_to_last_migration_files(changes) else: self.write_migration_files(changes) if check_changes: sys.exit(1) def write_to_last_migration_files(self, changes): loader = MigrationLoader(connections[DEFAULT_DB_ALIAS]) new_changes = {} update_previous_migration_paths = {} for app_label, app_migrations in changes.items(): # Find last migration. leaf_migration_nodes = loader.graph.leaf_nodes(app=app_label) if len(leaf_migration_nodes) == 0: raise CommandError( f"App {app_label} has no migration, cannot update last migration." ) leaf_migration_node = leaf_migration_nodes[0] # Multiple leaf nodes have already been checked earlier in command. leaf_migration = loader.graph.nodes[leaf_migration_node] # Updated migration cannot be a squash migration, a dependency of # another migration, and cannot be already applied. if leaf_migration.replaces: raise CommandError( f"Cannot update squash migration '{leaf_migration}'." ) if leaf_migration_node in loader.applied_migrations: raise CommandError( f"Cannot update applied migration '{leaf_migration}'." ) depending_migrations = [ migration for migration in loader.disk_migrations.values() if leaf_migration_node in migration.dependencies ] if depending_migrations: formatted_migrations = ", ".join( [f"'{migration}'" for migration in depending_migrations] ) raise CommandError( f"Cannot update migration '{leaf_migration}' that migrations " f"{formatted_migrations} depend on." ) # Build new migration. for migration in app_migrations: leaf_migration.operations.extend(migration.operations) for dependency in migration.dependencies: if isinstance(dependency, SwappableTuple): if settings.AUTH_USER_MODEL == dependency.setting: leaf_migration.dependencies.append( ("__setting__", "AUTH_USER_MODEL") ) else: leaf_migration.dependencies.append(dependency) elif dependency[0] != migration.app_label: leaf_migration.dependencies.append(dependency) # Optimize migration. optimizer = MigrationOptimizer() leaf_migration.operations = optimizer.optimize( leaf_migration.operations, app_label ) # Update name. previous_migration_path = MigrationWriter(leaf_migration).path name_fragment = self.migration_name or leaf_migration.suggest_name() suggested_name = leaf_migration.name[:4] + f"_{name_fragment}" if leaf_migration.name == suggested_name: new_name = leaf_migration.name + "_updated" else: new_name = suggested_name leaf_migration.name = new_name # Register overridden migration. new_changes[app_label] = [leaf_migration] update_previous_migration_paths[app_label] = previous_migration_path self.write_migration_files(new_changes, update_previous_migration_paths) def write_migration_files(self, changes, update_previous_migration_paths=None): """ Take a changes dict and write them out as migration files. """ directory_created = {} for app_label, app_migrations in changes.items(): if self.verbosity >= 1: self.log(self.style.MIGRATE_HEADING("Migrations for '%s':" % app_label)) for migration in app_migrations: # Describe the migration writer = MigrationWriter(migration, self.include_header) if self.verbosity >= 1: # Display a relative path if it's below the current working # directory, or an absolute path otherwise. migration_string = self.get_relative_path(writer.path) self.log(" %s\n" % self.style.MIGRATE_LABEL(migration_string)) for operation in migration.operations: self.log(" %s" % operation.formatted_description()) if self.scriptable: self.stdout.write(migration_string) if not self.dry_run: # Write the migrations file to the disk. migrations_directory = os.path.dirname(writer.path) if not directory_created.get(app_label): os.makedirs(migrations_directory, exist_ok=True) init_path = os.path.join(migrations_directory, "__init__.py") if not os.path.isfile(init_path): open(init_path, "w").close() # We just do this once per app directory_created[app_label] = True migration_string = writer.as_string() with open(writer.path, "w", encoding="utf-8") as fh: fh.write(migration_string) self.written_files.append(writer.path) if update_previous_migration_paths: prev_path = update_previous_migration_paths[app_label] rel_prev_path = self.get_relative_path(prev_path) if writer.needs_manual_porting: migration_path = self.get_relative_path(writer.path) self.log( self.style.WARNING( f"Updated migration {migration_path} requires " f"manual porting.\n" f"Previous migration {rel_prev_path} was kept and " f"must be deleted after porting functions manually." ) ) else: os.remove(prev_path) self.log(f"Deleted {rel_prev_path}") elif self.verbosity == 3: # Alternatively, makemigrations --dry-run --verbosity 3 # will log the migrations rather than saving the file to # the disk. self.log( self.style.MIGRATE_HEADING( "Full migrations file '%s':" % writer.filename ) ) self.log(writer.as_string()) run_formatters(self.written_files, stderr=self.stderr) @staticmethod def get_relative_path(path): try: migration_string = os.path.relpath(path) except ValueError: migration_string = path if migration_string.startswith(".."): migration_string = path return migration_string def handle_merge(self, loader, conflicts): """ Handles merging together conflicted migrations interactively, if it's safe; otherwise, advises on how to fix it. """ if self.interactive: questioner = InteractiveMigrationQuestioner(prompt_output=self.log_output) else: questioner = MigrationQuestioner(defaults={"ask_merge": True}) for app_label, migration_names in conflicts.items(): # Grab out the migrations in question, and work out their # common ancestor. merge_migrations = [] for migration_name in migration_names: migration = loader.get_migration(app_label, migration_name) migration.ancestry = [ mig for mig in loader.graph.forwards_plan((app_label, migration_name)) if mig[0] == migration.app_label ] merge_migrations.append(migration) def all_items_equal(seq): return all(item == seq[0] for item in seq[1:]) merge_migrations_generations = zip(*(m.ancestry for m in merge_migrations)) common_ancestor_count = sum( 1 for common_ancestor_generation in takewhile( all_items_equal, merge_migrations_generations ) ) if not common_ancestor_count: raise ValueError( "Could not find common ancestor of %s" % migration_names ) # Now work out the operations along each divergent branch for migration in merge_migrations: migration.branch = migration.ancestry[common_ancestor_count:] migrations_ops = ( loader.get_migration(node_app, node_name).operations for node_app, node_name in migration.branch ) migration.merged_operations = sum(migrations_ops, []) # In future, this could use some of the Optimizer code # (can_optimize_through) to automatically see if they're # mergeable. For now, we always just prompt the user. if self.verbosity > 0: self.log(self.style.MIGRATE_HEADING("Merging %s" % app_label)) for migration in merge_migrations: self.log(self.style.MIGRATE_LABEL(" Branch %s" % migration.name)) for operation in migration.merged_operations: self.log(" %s" % operation.formatted_description()) if questioner.ask_merge(app_label): # If they still want to merge it, then write out an empty # file depending on the migrations needing merging. numbers = [ self.autodetector.parse_number(migration.name) for migration in merge_migrations ] try: biggest_number = max(x for x in numbers if x is not None) except ValueError: biggest_number = 1 subclass = type( "Migration", (Migration,), { "dependencies": [ (app_label, migration.name) for migration in merge_migrations ], }, ) parts = ["%04i" % (biggest_number + 1)] if self.migration_name: parts.append(self.migration_name) else: parts.append("merge") leaf_names = "_".join( sorted(migration.name for migration in merge_migrations) ) if len(leaf_names) > 47: parts.append(get_migration_name_timestamp()) else: parts.append(leaf_names) migration_name = "_".join(parts) new_migration = subclass(migration_name, app_label) writer = MigrationWriter(new_migration, self.include_header) if not self.dry_run: # Write the merge migrations file to the disk with open(writer.path, "w", encoding="utf-8") as fh: fh.write(writer.as_string()) run_formatters([writer.path], stderr=self.stderr) if self.verbosity > 0: self.log("\nCreated new merge migration %s" % writer.path) if self.scriptable: self.stdout.write(writer.path) elif self.verbosity == 3: # Alternatively, makemigrations --merge --dry-run # --verbosity 3 will log the merge migrations rather than # saving the file to the disk. self.log( self.style.MIGRATE_HEADING( "Full merge migrations file '%s':" % writer.filename ) ) self.log(writer.as_string())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/inspectdb.py
django/core/management/commands/inspectdb.py
import keyword import re from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.models.constants import LOOKUP_SEP from django.db.models.deletion import DatabaseOnDelete class Command(BaseCommand): help = ( "Introspects the database tables in the given database and outputs a Django " "model module." ) requires_system_checks = [] stealth_options = ("table_name_filter",) db_module = "django.db" def add_arguments(self, parser): parser.add_argument( "table", nargs="*", type=str, help="Selects what tables or views should be introspected.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( 'Nominates a database to introspect. Defaults to using the "default" ' "database." ), ) parser.add_argument( "--include-partitions", action="store_true", help="Also output models for partition tables.", ) parser.add_argument( "--include-views", action="store_true", help="Also output models for database views.", ) def handle(self, **options): try: for line in self.handle_inspection(options): self.stdout.write(line) except NotImplementedError: raise CommandError( "Database inspection isn't supported for the currently selected " "database backend." ) def handle_inspection(self, options): connection = connections[options["database"]] # 'table_name_filter' is a stealth option table_name_filter = options.get("table_name_filter") with connection.cursor() as cursor: yield "# This is an auto-generated Django model module." yield "# You'll have to do the following manually to clean this up:" yield "# * Rearrange models' order" yield "# * Make sure each model has one field with primary_key=True" yield ( "# * Make sure each ForeignKey and OneToOneField has `on_delete` set " "to the desired behavior" ) yield ( "# * Remove `managed = False` lines if you wish to allow " "Django to create, modify, and delete the table" ) yield ( "# Feel free to rename the models, but don't rename db_table values or " "field names." ) yield "from %s import models" % self.db_module known_models = [] # Determine types of tables and/or views to be introspected. types = {"t"} if options["include_partitions"]: types.add("p") if options["include_views"]: types.add("v") table_info = connection.introspection.get_table_list(cursor) table_info = {info.name: info for info in table_info if info.type in types} for table_name in options["table"] or sorted(name for name in table_info): if table_name_filter is not None and callable(table_name_filter): if not table_name_filter(table_name): continue try: try: relations = connection.introspection.get_relations( cursor, table_name ) except NotImplementedError: relations = {} try: constraints = connection.introspection.get_constraints( cursor, table_name ) except NotImplementedError: constraints = {} primary_key_columns = ( connection.introspection.get_primary_key_columns( cursor, table_name ) or [] ) primary_key_column = ( primary_key_columns[0] if len(primary_key_columns) == 1 else None ) unique_columns = [ c["columns"][0] for c in constraints.values() if c["unique"] and len(c["columns"]) == 1 ] table_description = connection.introspection.get_table_description( cursor, table_name ) except Exception as e: yield "# Unable to inspect table '%s'" % table_name yield "# The error was: %s" % e continue model_name = self.normalize_table_name(table_name) yield "" yield "" yield "class %s(models.Model):" % model_name known_models.append(model_name) if len(primary_key_columns) > 1: fields = ", ".join([f"'{col}'" for col in primary_key_columns]) yield f" pk = models.CompositePrimaryKey({fields})" used_column_names = [] # Holds column names used in the table so far column_to_field_name = {} # Maps column names to names of model fields used_relations = set() # Holds foreign relations used in the table. for row in table_description: comment_notes = ( [] ) # Holds Field notes, to be displayed in a Python comment. extra_params = {} # Holds Field parameters such as 'db_column'. column_name = row.name is_relation = column_name in relations att_name, params, notes = self.normalize_col_name( column_name, used_column_names, is_relation ) extra_params.update(params) comment_notes.extend(notes) used_column_names.append(att_name) column_to_field_name[column_name] = att_name # Add primary_key and unique, if necessary. if column_name == primary_key_column: extra_params["primary_key"] = True elif column_name in unique_columns: extra_params["unique"] = True if is_relation: ref_db_column, ref_db_table, db_on_delete = relations[ column_name ] if extra_params.pop("unique", False) or extra_params.get( "primary_key" ): rel_type = "OneToOneField" else: rel_type = "ForeignKey" ref_pk_column = ( connection.introspection.get_primary_key_column( cursor, ref_db_table ) ) if ref_pk_column and ref_pk_column != ref_db_column: extra_params["to_field"] = ref_db_column rel_to = ( "self" if ref_db_table == table_name else self.normalize_table_name(ref_db_table) ) if rel_to in known_models: field_type = "%s(%s" % (rel_type, rel_to) else: field_type = "%s('%s'" % (rel_type, rel_to) if rel_to in used_relations: extra_params["related_name"] = "%s_%s_set" % ( model_name.lower(), att_name, ) if db_on_delete and isinstance(db_on_delete, DatabaseOnDelete): extra_params["on_delete"] = f"models.{db_on_delete}" used_relations.add(rel_to) else: # Calling `get_field_type` to get the field type string # and any additional parameters and notes. field_type, field_params, field_notes = self.get_field_type( connection, table_name, row ) extra_params.update(field_params) comment_notes.extend(field_notes) field_type += "(" # Don't output 'id = meta.AutoField(primary_key=True)', # because that's assumed if it doesn't exist. if att_name == "id" and extra_params == {"primary_key": True}: if field_type == "AutoField(": continue elif ( field_type == connection.features.introspected_field_types["AutoField"] + "(" ): comment_notes.append("AutoField?") # Add 'null' and 'blank', if the 'null_ok' flag was present # in the table description. if row.null_ok: # If it's NULL... extra_params["blank"] = True extra_params["null"] = True field_desc = "%s = %s%s" % ( att_name, # Custom fields will have a dotted path "" if "." in field_type else "models.", field_type, ) on_delete_qualname = extra_params.pop("on_delete", None) if field_type.startswith(("ForeignKey(", "OneToOneField(")): if on_delete_qualname: field_desc += f", {on_delete_qualname}" else: field_desc += ", models.DO_NOTHING" # Add comment. if connection.features.supports_comments and row.comment: extra_params["db_comment"] = row.comment if extra_params: if not field_desc.endswith("("): field_desc += ", " field_desc += ", ".join( "%s=%r" % (k, v) for k, v in extra_params.items() ) field_desc += ")" if comment_notes: field_desc += " # " + " ".join(comment_notes) yield " %s" % field_desc comment = None if info := table_info.get(table_name): is_view = info.type == "v" is_partition = info.type == "p" if connection.features.supports_comments: comment = info.comment else: is_view = False is_partition = False yield from self.get_meta( table_name, constraints, column_to_field_name, is_view, is_partition, comment, ) def normalize_col_name(self, col_name, used_column_names, is_relation): """ Modify the column name to make it Python-compatible as a field name """ field_params = {} field_notes = [] new_name = col_name.lower() if new_name != col_name: field_notes.append("Field name made lowercase.") if is_relation: if new_name.endswith("_id"): new_name = new_name.removesuffix("_id") else: field_params["db_column"] = col_name new_name, num_repl = re.subn(r"\W", "_", new_name) if num_repl > 0: field_notes.append("Field renamed to remove unsuitable characters.") if new_name.find(LOOKUP_SEP) >= 0: while new_name.find(LOOKUP_SEP) >= 0: new_name = new_name.replace(LOOKUP_SEP, "_") if col_name.lower().find(LOOKUP_SEP) >= 0: # Only add the comment if the double underscore was in the # original name field_notes.append( "Field renamed because it contained more than one '_' in a row." ) if new_name.startswith("_"): new_name = "field%s" % new_name field_notes.append("Field renamed because it started with '_'.") if new_name.endswith("_"): new_name = "%sfield" % new_name field_notes.append("Field renamed because it ended with '_'.") if keyword.iskeyword(new_name): new_name += "_field" field_notes.append("Field renamed because it was a Python reserved word.") if new_name[0].isdigit(): new_name = "number_%s" % new_name field_notes.append( "Field renamed because it wasn't a valid Python identifier." ) if new_name in used_column_names: num = 0 while "%s_%d" % (new_name, num) in used_column_names: num += 1 new_name = "%s_%d" % (new_name, num) field_notes.append("Field renamed because of name conflict.") if col_name != new_name and field_notes: field_params["db_column"] = col_name return new_name, field_params, field_notes def normalize_table_name(self, table_name): """Translate the table name to a Python-compatible model name.""" return re.sub(r"[^a-zA-Z0-9]", "", table_name.title()) def get_field_type(self, connection, table_name, row): """ Given the database connection, the table name, and the cursor row description, this routine will return the given field type name, as well as any additional keyword parameters and notes for the field. """ field_params = {} field_notes = [] try: field_type = connection.introspection.get_field_type(row.type_code, row) except KeyError: field_type = "TextField" field_notes.append("This field type is a guess.") # Add max_length for all CharFields. if field_type == "CharField" and row.display_size: if (size := int(row.display_size)) and size > 0: field_params["max_length"] = size if field_type in {"CharField", "TextField"} and row.collation: field_params["db_collation"] = row.collation if field_type == "DecimalField" and ( # This can generate DecimalFields with only one of max_digits and # decimal_fields specified. This configuration would be incorrect, # but nothing more correct could be generated. row.precision is not None or row.scale is not None ): field_params["max_digits"] = row.precision field_params["decimal_places"] = row.scale return field_type, field_params, field_notes def get_meta( self, table_name, constraints, column_to_field_name, is_view, is_partition, comment, ): """ Return a sequence comprising the lines of code necessary to construct the inner Meta class for the model corresponding to the given database table name. """ unique_together = [] has_unsupported_constraint = False for params in constraints.values(): if params["unique"]: columns = params["columns"] if None in columns: has_unsupported_constraint = True columns = [ x for x in columns if x is not None and x in column_to_field_name ] if len(columns) > 1 and not params["primary_key"]: unique_together.append( str(tuple(column_to_field_name[c] for c in columns)) ) if is_view: managed_comment = " # Created from a view. Don't remove." elif is_partition: managed_comment = " # Created from a partition. Don't remove." else: managed_comment = "" meta = [""] if has_unsupported_constraint: meta.append(" # A unique constraint could not be introspected.") meta += [ " class Meta:", " managed = False%s" % managed_comment, " db_table = %r" % table_name, ] if unique_together: tup = "(" + ", ".join(unique_together) + ",)" meta += [" unique_together = %s" % tup] if comment: meta += [f" db_table_comment = {comment!r}"] return meta
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/runserver.py
django/core/management/commands/runserver.py
import errno import os import re import socket import sys from datetime import datetime from django.conf import settings from django.core.management.base import BaseCommand, CommandError from django.core.servers.basehttp import WSGIServer, get_internal_wsgi_application, run from django.db import connections from django.utils import autoreload from django.utils.regex_helper import _lazy_re_compile from django.utils.version import get_docs_version naiveip_re = _lazy_re_compile( r"""^(?: (?P<addr> (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) | # IPv4 address (?P<ipv6>\[[a-fA-F0-9:]+\]) | # IPv6 address (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN ):)?(?P<port>\d+)$""", re.X, ) class Command(BaseCommand): help = "Starts a lightweight web server for development." stealth_options = ("shutdown_message",) suppressed_base_arguments = {"--verbosity", "--traceback"} default_addr = "127.0.0.1" default_addr_ipv6 = "::1" default_port = "8000" protocol = "http" server_cls = WSGIServer def add_arguments(self, parser): parser.add_argument( "addrport", nargs="?", help="Optional port number, or ipaddr:port" ) parser.add_argument( "--ipv6", "-6", action="store_true", dest="use_ipv6", help="Tells Django to use an IPv6 address.", ) parser.add_argument( "--nothreading", action="store_false", dest="use_threading", help="Tells Django to NOT use threading.", ) parser.add_argument( "--noreload", action="store_false", dest="use_reloader", help="Tells Django to NOT use the auto-reloader.", ) def execute(self, *args, **options): if options["no_color"]: # We rely on the environment because it's currently the only # way to reach WSGIRequestHandler. This seems an acceptable # compromise considering `runserver` runs indefinitely. os.environ["DJANGO_COLORS"] = "nocolor" super().execute(*args, **options) def get_handler(self, *args, **options): """Return the default WSGI handler for the runner.""" return get_internal_wsgi_application() def get_check_kwargs(self, options): """Validation is called explicitly each time the server reloads.""" return {"tags": set()} def handle(self, *args, **options): if not settings.DEBUG and not settings.ALLOWED_HOSTS: raise CommandError("You must set settings.ALLOWED_HOSTS if DEBUG is False.") self.use_ipv6 = options["use_ipv6"] if self.use_ipv6 and not socket.has_ipv6: raise CommandError("Your Python does not support IPv6.") self._raw_ipv6 = False if not options["addrport"]: self.addr = "" self.port = self.default_port else: m = re.match(naiveip_re, options["addrport"]) if m is None: raise CommandError( '"%s" is not a valid port number ' "or address:port pair." % options["addrport"] ) self.addr, _ipv4, _ipv6, _fqdn, self.port = m.groups() if not self.port.isdigit(): raise CommandError("%r is not a valid port number." % self.port) if self.addr: if _ipv6: self.addr = self.addr[1:-1] self.use_ipv6 = True self._raw_ipv6 = True elif self.use_ipv6 and not _fqdn: raise CommandError('"%s" is not a valid IPv6 address.' % self.addr) if not self.addr: self.addr = self.default_addr_ipv6 if self.use_ipv6 else self.default_addr self._raw_ipv6 = self.use_ipv6 self.run(**options) def run(self, **options): """Run the server, using the autoreloader if needed.""" use_reloader = options["use_reloader"] if use_reloader: autoreload.run_with_reloader(self.inner_run, **options) else: self.inner_run(None, **options) def inner_run(self, *args, **options): # If an exception was silenced in ManagementUtility.execute in order # to be raised in the child process, raise it now. autoreload.raise_last_exception() threading = options["use_threading"] # 'shutdown_message' is a stealth option. shutdown_message = options.get("shutdown_message", "") if not options["skip_checks"]: self.stdout.write("Performing system checks...\n\n") check_kwargs = super().get_check_kwargs(options) check_kwargs["display_num_errors"] = True self.check(**check_kwargs) # Need to check migrations here, so can't use the # requires_migrations_check attribute. self.check_migrations() # Close all connections opened during migration checking. for conn in connections.all(initialized_only=True): conn.close() try: handler = self.get_handler(*args, **options) run( self.addr, int(self.port), handler, ipv6=self.use_ipv6, threading=threading, on_bind=self.on_bind, server_cls=self.server_cls, ) except OSError as e: # Use helpful error messages instead of ugly tracebacks. ERRORS = { errno.EACCES: "You don't have permission to access that port.", errno.EADDRINUSE: "That port is already in use.", errno.EADDRNOTAVAIL: "That IP address can't be assigned to.", } try: error_text = ERRORS[e.errno] except KeyError: error_text = e self.stderr.write("Error: %s" % error_text) # Need to use an OS exit because sys.exit doesn't work in a thread os._exit(1) except KeyboardInterrupt: if shutdown_message: self.stdout.write(shutdown_message) sys.exit(0) def on_bind(self, server_port): quit_command = "CTRL-BREAK" if sys.platform == "win32" else "CONTROL-C" if self._raw_ipv6: addr = f"[{self.addr}]" elif self.addr == "0": addr = "0.0.0.0" else: addr = self.addr now = datetime.now().strftime("%B %d, %Y - %X") version = self.get_version() print( f"{now}\n" f"Django version {version}, using settings {settings.SETTINGS_MODULE!r}\n" f"Starting development server at {self.protocol}://{addr}:{server_port}/\n" f"Quit the server with {quit_command}.", file=self.stdout, ) docs_version = get_docs_version() if os.environ.get("DJANGO_RUNSERVER_HIDE_WARNING") != "true": self.stdout.write( self.style.WARNING( "WARNING: This is a development server. Do not use it in a " "production setting. Use a production WSGI or ASGI server " "instead.\nFor more information on production servers see: " f"https://docs.djangoproject.com/en/{docs_version}/howto/" "deployment/" ) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/makemessages.py
django/core/management/commands/makemessages.py
import glob import os import re import sys from functools import total_ordering from itertools import dropwhile from pathlib import Path import django from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.files.temp import NamedTemporaryFile from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import ( find_command, handle_extensions, is_ignored_path, popen_wrapper, ) from django.utils.encoding import DEFAULT_LOCALE_ENCODING from django.utils.functional import cached_property from django.utils.regex_helper import _lazy_re_compile from django.utils.text import get_text_list from django.utils.translation import templatize plural_forms_re = _lazy_re_compile( r'^(?P<value>"Plural-Forms.+?\\n")\s*$', re.MULTILINE | re.DOTALL ) STATUS_OK = 0 NO_LOCALE_DIR = object() def check_programs(*programs): for program in programs: if find_command(program) is None: raise CommandError( f"Can't find {program}. Make sure you have GNU gettext tools " "0.19 or newer installed." ) def is_valid_locale(locale): return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z0-9].*$", locale) @total_ordering class TranslatableFile: def __init__(self, dirpath, file_name, locale_dir): self.file = file_name self.dirpath = dirpath self.locale_dir = locale_dir def __repr__(self): return "<%s: %s>" % ( self.__class__.__name__, os.sep.join([self.dirpath, self.file]), ) def __eq__(self, other): return self.path == other.path def __lt__(self, other): return self.path < other.path @property def path(self): return os.path.join(self.dirpath, self.file) class BuildFile: """ Represent the state of a translatable file during the build process. """ def __init__(self, command, domain, translatable): self.command = command self.domain = domain self.translatable = translatable @cached_property def is_templatized(self): if self.domain == "django": file_ext = os.path.splitext(self.translatable.file)[1] return file_ext != ".py" return False @cached_property def path(self): return self.translatable.path @cached_property def work_path(self): """ Path to a file which is being fed into GNU gettext pipeline. This may be either a translatable or its preprocessed version. """ if not self.is_templatized: return self.path filename = f"{self.translatable.file}.py" return os.path.join(self.translatable.dirpath, filename) def preprocess(self): """ Preprocess (if necessary) a translatable file before passing it to xgettext GNU gettext utility. """ if not self.is_templatized: return with open(self.path, encoding="utf-8") as fp: src_data = fp.read() if self.domain == "django": content = templatize(src_data, origin=self.path[2:]) with open(self.work_path, "w", encoding="utf-8") as fp: fp.write(content) def postprocess_messages(self, msgs): """ Postprocess messages generated by xgettext GNU gettext utility. Transform paths as if these messages were generated from original translatable files rather than from preprocessed versions. """ if not self.is_templatized: return msgs # Remove '.py' suffix if os.name == "nt": # Preserve '.\' prefix on Windows to respect gettext behavior old_path = self.work_path new_path = self.path else: old_path = self.work_path[2:] new_path = self.path[2:] return re.sub( r"^(#: .*)(" + re.escape(old_path) + r")", lambda match: match[0].replace(old_path, new_path), msgs, flags=re.MULTILINE, ) def cleanup(self): """ Remove a preprocessed copy of a translatable file (if any). """ if self.is_templatized: # This check is needed for the case of a symlinked file and its # source being processed inside a single group (locale dir); # removing either of those two removes both. if os.path.exists(self.work_path): os.unlink(self.work_path) def normalize_eols(raw_contents): """ Take a block of raw text that will be passed through str.splitlines() to get universal newlines treatment. Return the resulting block of text with normalized `\n` EOL sequences ready to be written to disk using current platform's native EOLs. """ lines_list = raw_contents.splitlines() # Ensure last line has its EOL if lines_list and lines_list[-1]: lines_list.append("") return "\n".join(lines_list) def write_pot_file(potfile, msgs): """ Write the `potfile` with the `msgs` contents, making sure its format is valid. """ pot_lines = msgs.splitlines() if os.path.exists(potfile): # Strip the header lines = dropwhile(len, pot_lines) else: lines = [] found, header_read = False, False for line in pot_lines: if not found and not header_read: if "charset=CHARSET" in line: found = True line = line.replace("charset=CHARSET", "charset=UTF-8") if not line and not found: header_read = True lines.append(line) msgs = "\n".join(lines) # Force newlines of POT files to '\n' to work around # https://savannah.gnu.org/bugs/index.php?52395 with open(potfile, "a", encoding="utf-8", newline="\n") as fp: fp.write(msgs) class Command(BaseCommand): help = ( "Runs over the entire source tree of the current directory and pulls out all " "strings marked for translation. It creates (or updates) a message file in the " "conf/locale (in the django tree) or locale (for projects and applications) " "directory.\n\nYou must run this command with one of either the --locale, " "--exclude, or --all options." ) translatable_file_class = TranslatableFile build_file_class = BuildFile requires_system_checks = [] msgmerge_options = ["-q", "--backup=none", "--previous", "--update"] msguniq_options = ["--to-code=utf-8"] msgattrib_options = ["--no-obsolete"] xgettext_options = ["--from-code=UTF-8", "--add-comments=Translators"] def add_arguments(self, parser): parser.add_argument( "--locale", "-l", default=[], action="append", help=( "Creates or updates the message files for the given locale(s) (e.g. " "pt_BR). Can be used multiple times." ), ) parser.add_argument( "--exclude", "-x", default=[], action="append", help="Locales to exclude. Default is none. Can be used multiple times.", ) parser.add_argument( "--domain", "-d", default="django", help='The domain of the message files (default: "django").', ) parser.add_argument( "--all", "-a", action="store_true", help="Updates the message files for all existing locales.", ) parser.add_argument( "--extension", "-e", dest="extensions", action="append", help='The file extension(s) to examine (default: "html,txt,py", or "js" ' 'if the domain is "djangojs"). Separate multiple extensions with ' "commas, or use -e multiple times.", ) parser.add_argument( "--symlinks", "-s", action="store_true", help="Follows symlinks to directories when examining source code " "and templates for translation strings.", ) parser.add_argument( "--ignore", "-i", action="append", dest="ignore_patterns", default=[], metavar="PATTERN", help="Ignore files or directories matching this glob-style pattern. " "Use multiple times to ignore more.", ) parser.add_argument( "--no-default-ignore", action="store_false", dest="use_default_ignore_patterns", help=( "Don't ignore the common glob-style patterns 'CVS', '.*', '*~' and " "'*.pyc'." ), ) parser.add_argument( "--no-wrap", action="store_true", help="Don't break long message lines into several lines.", ) parser.add_argument( "--no-location", action="store_true", help="Don't write '#: filename:line' lines.", ) parser.add_argument( "--add-location", choices=("full", "file", "never"), const="full", nargs="?", help=( "Controls '#: filename:line' lines. If the option is 'full' " "(the default if not given), the lines include both file name " "and line number. If it's 'file', the line number is omitted. If " "it's 'never', the lines are suppressed (same as --no-location). " "--add-location requires gettext 0.19 or newer." ), ) parser.add_argument( "--no-obsolete", action="store_true", help="Remove obsolete message strings.", ) parser.add_argument( "--keep-pot", action="store_true", help="Keep .pot file after making messages. Useful when debugging.", ) def handle(self, *args, **options): locale = options["locale"] exclude = options["exclude"] self.domain = options["domain"] self.verbosity = options["verbosity"] process_all = options["all"] extensions = options["extensions"] self.symlinks = options["symlinks"] ignore_patterns = options["ignore_patterns"] if options["use_default_ignore_patterns"]: ignore_patterns += ["CVS", ".*", "*~", "*.pyc"] self.ignore_patterns = list(set(ignore_patterns)) # Avoid messing with mutable class variables if options["no_wrap"]: self.msgmerge_options = self.msgmerge_options[:] + ["--no-wrap"] self.msguniq_options = self.msguniq_options[:] + ["--no-wrap"] self.msgattrib_options = self.msgattrib_options[:] + ["--no-wrap"] self.xgettext_options = self.xgettext_options[:] + ["--no-wrap"] if options["no_location"]: self.msgmerge_options = self.msgmerge_options[:] + ["--no-location"] self.msguniq_options = self.msguniq_options[:] + ["--no-location"] self.msgattrib_options = self.msgattrib_options[:] + ["--no-location"] self.xgettext_options = self.xgettext_options[:] + ["--no-location"] if options["add_location"]: arg_add_location = "--add-location=%s" % options["add_location"] self.msgmerge_options = self.msgmerge_options[:] + [arg_add_location] self.msguniq_options = self.msguniq_options[:] + [arg_add_location] self.msgattrib_options = self.msgattrib_options[:] + [arg_add_location] self.xgettext_options = self.xgettext_options[:] + [arg_add_location] self.no_obsolete = options["no_obsolete"] self.keep_pot = options["keep_pot"] if self.domain not in ("django", "djangojs"): raise CommandError( "currently makemessages only supports domains " "'django' and 'djangojs'" ) if self.domain == "djangojs": exts = extensions or ["js"] else: exts = extensions or ["html", "txt", "py"] self.extensions = handle_extensions(exts) if (not locale and not exclude and not process_all) or self.domain is None: raise CommandError( "Type '%s help %s' for usage information." % (os.path.basename(sys.argv[0]), sys.argv[1]) ) if self.verbosity > 1: self.stdout.write( "examining files with the extensions: %s" % get_text_list(list(self.extensions), "and") ) self.invoked_for_django = False self.locale_paths = [] self.default_locale_path = None if os.path.isdir(os.path.join("conf", "locale")): self.locale_paths = [os.path.abspath(os.path.join("conf", "locale"))] self.default_locale_path = self.locale_paths[0] self.ignore_patterns.append("views/templates/i18n_catalog.js") self.invoked_for_django = True else: if self.settings_available: for path in settings.LOCALE_PATHS: locale_path = os.path.abspath(path) if locale_path not in self.locale_paths: self.locale_paths.append(locale_path) # Allow to run makemessages inside an app dir if os.path.isdir("locale"): locale_path = os.path.abspath("locale") if locale_path not in self.locale_paths: self.locale_paths.append(locale_path) if self.locale_paths: self.default_locale_path = self.locale_paths[0] os.makedirs(self.default_locale_path, exist_ok=True) # Build locale list looks_like_locale = re.compile(r"[a-z]{2}") locale_dirs = filter( os.path.isdir, glob.glob("%s/*" % self.default_locale_path) ) all_locales = [ lang_code for lang_code in map(os.path.basename, locale_dirs) if looks_like_locale.match(lang_code) ] # Account for excluded locales if process_all: locales = all_locales else: locales = locale or all_locales locales = set(locales).difference(exclude) if locales: check_programs("msguniq", "msgmerge", "msgattrib") check_programs("xgettext") try: potfiles = self.build_potfiles() # Build po files for each selected locale for locale in locales: if not is_valid_locale(locale): # Try to guess what valid locale it could be # Valid examples are: en_GB, shi_Latn_MA and # nl_NL-x-informal # Search for characters followed by a non character (i.e. # separator) match = re.match( r"^(?P<language>[a-zA-Z]+)" r"(?P<separator>[^a-zA-Z])" r"(?P<territory>.+)$", locale, ) if match: locale_parts = match.groupdict() language = locale_parts["language"].lower() territory = ( locale_parts["territory"][:2].upper() + locale_parts["territory"][2:] ) proposed_locale = f"{language}_{territory}" else: # It could be a language in uppercase proposed_locale = locale.lower() # Recheck if the proposed locale is valid if is_valid_locale(proposed_locale): self.stdout.write( "invalid locale %s, did you mean %s?" % ( locale, proposed_locale, ), ) else: self.stdout.write("invalid locale %s" % locale) continue if self.verbosity > 0: self.stdout.write("processing locale %s" % locale) for potfile in potfiles: self.write_po_file(potfile, locale) finally: if not self.keep_pot: self.remove_potfiles() @cached_property def gettext_version(self): # Gettext tools will output system-encoded bytestrings instead of # UTF-8, when looking up the version. It's especially a problem on # Windows. out, err, status = popen_wrapper( ["xgettext", "--version"], stdout_encoding=DEFAULT_LOCALE_ENCODING, ) m = re.search(r"(\d+)\.(\d+)\.?(\d+)?", out) if m: return tuple(int(d) for d in m.groups() if d is not None) else: raise CommandError("Unable to get gettext version. Is it installed?") @cached_property def settings_available(self): try: settings.LOCALE_PATHS except ImproperlyConfigured: if self.verbosity > 1: self.stderr.write("Running without configured settings.") return False return True def build_potfiles(self): """ Build pot files and apply msguniq to them. """ file_list = self.find_files(".") self.remove_potfiles() self.process_files(file_list) potfiles = [] for path in self.locale_paths: potfile = os.path.join(path, "%s.pot" % self.domain) if not os.path.exists(potfile): continue args = ["msguniq", *self.msguniq_options, potfile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msguniq\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) msgs = normalize_eols(msgs) with open(potfile, "w", encoding="utf-8") as fp: fp.write(msgs) potfiles.append(potfile) return potfiles def remove_potfiles(self): for path in self.locale_paths: pot_path = os.path.join(path, "%s.pot" % self.domain) if os.path.exists(pot_path): os.unlink(pot_path) def find_files(self, root): """ Get all files in the given root. Also check that there is a matching locale dir for each file. """ all_files = [] ignored_roots = [] if self.settings_available: ignored_roots = [ os.path.normpath(p) for p in (settings.MEDIA_ROOT, settings.STATIC_ROOT) if p ] for dirpath, dirnames, filenames in os.walk( root, topdown=True, followlinks=self.symlinks ): for dirname in dirnames[:]: if ( is_ignored_path( os.path.normpath(os.path.join(dirpath, dirname)), self.ignore_patterns, ) or os.path.join(os.path.abspath(dirpath), dirname) in ignored_roots ): dirnames.remove(dirname) if self.verbosity > 1: self.stdout.write("ignoring directory %s" % dirname) elif dirname == "locale": dirnames.remove(dirname) locale_dir = os.path.join(os.path.abspath(dirpath), dirname) if locale_dir in self.locale_paths: self.locale_paths.remove(locale_dir) self.locale_paths.insert(0, locale_dir) for filename in filenames: file_path = os.path.normpath(os.path.join(dirpath, filename)) file_ext = os.path.splitext(filename)[1] if file_ext not in self.extensions or is_ignored_path( file_path, self.ignore_patterns ): if self.verbosity > 1: self.stdout.write( "ignoring file %s in %s" % (filename, dirpath) ) else: locale_dir = None for path in self.locale_paths: if os.path.abspath(dirpath).startswith(os.path.dirname(path)): locale_dir = path break locale_dir = locale_dir or self.default_locale_path or NO_LOCALE_DIR all_files.append( self.translatable_file_class(dirpath, filename, locale_dir) ) return sorted(all_files) def process_files(self, file_list): """ Group translatable files by locale directory and run pot file build process for each group. """ file_groups = {} for translatable in file_list: file_group = file_groups.setdefault(translatable.locale_dir, []) file_group.append(translatable) for locale_dir, files in file_groups.items(): self.process_locale_dir(locale_dir, files) def process_locale_dir(self, locale_dir, files): """ Extract translatable literals from the specified files, creating or updating the POT file for a given locale directory. Use the xgettext GNU gettext utility. """ build_files = [] for translatable in files: if self.verbosity > 1: self.stdout.write( "processing file %s in %s" % (translatable.file, translatable.dirpath) ) if self.domain not in ("djangojs", "django"): continue build_file = self.build_file_class(self, self.domain, translatable) try: build_file.preprocess() except UnicodeDecodeError as e: self.stdout.write( "UnicodeDecodeError: skipped file %s in %s (reason: %s)" % ( translatable.file, translatable.dirpath, e, ) ) continue except BaseException: # Cleanup before exit. for build_file in build_files: build_file.cleanup() raise build_files.append(build_file) if self.domain == "djangojs": args = [ "xgettext", "-d", self.domain, "--language=JavaScript", "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", "--output=-", ] elif self.domain == "django": args = [ "xgettext", "-d", self.domain, "--language=Python", "--keyword=gettext_noop", "--keyword=gettext_lazy", "--keyword=ngettext_lazy:1,2", "--keyword=pgettext:1c,2", "--keyword=npgettext:1c,2,3", "--keyword=pgettext_lazy:1c,2", "--keyword=npgettext_lazy:1c,2,3", "--output=-", ] else: return input_files = [bf.work_path for bf in build_files] with NamedTemporaryFile(mode="w+") as input_files_list: input_files_list.write("\n".join(input_files)) input_files_list.flush() args.extend(["--files-from", input_files_list.name]) args.extend(self.xgettext_options) msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: for build_file in build_files: build_file.cleanup() raise CommandError( "errors happened while running xgettext on %s\n%s" % ("\n".join(input_files), errors) ) elif self.verbosity > 0: # Print warnings self.stdout.write(errors) if msgs: if locale_dir is NO_LOCALE_DIR: for build_file in build_files: build_file.cleanup() file_path = os.path.normpath(build_files[0].path) raise CommandError( "Unable to find a locale path to store translations for " "file %s. Make sure the 'locale' directory exists in an " "app or LOCALE_PATHS setting is set." % file_path ) for build_file in build_files: msgs = build_file.postprocess_messages(msgs) potfile = os.path.join(locale_dir, "%s.pot" % self.domain) write_pot_file(potfile, msgs) for build_file in build_files: build_file.cleanup() def write_po_file(self, potfile, locale): """ Create or update the PO file for self.domain and `locale`. Use contents of the existing `potfile`. Use msgmerge and msgattrib GNU gettext utilities. """ basedir = os.path.join(os.path.dirname(potfile), locale, "LC_MESSAGES") os.makedirs(basedir, exist_ok=True) pofile = os.path.join(basedir, "%s.po" % self.domain) if os.path.exists(pofile): args = ["msgmerge", *self.msgmerge_options, pofile, potfile] _, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgmerge\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) msgs = Path(pofile).read_text(encoding="utf-8") else: with open(potfile, encoding="utf-8") as fp: msgs = fp.read() if not self.invoked_for_django: msgs = self.copy_plural_forms(msgs, locale) msgs = normalize_eols(msgs) msgs = msgs.replace( "#. #-#-#-#-# %s.pot (PACKAGE VERSION) #-#-#-#-#\n" % self.domain, "" ) with open(pofile, "w", encoding="utf-8") as fp: fp.write(msgs) if self.no_obsolete: args = ["msgattrib", *self.msgattrib_options, "-o", pofile, pofile] msgs, errors, status = popen_wrapper(args) if errors: if status != STATUS_OK: raise CommandError( "errors happened while running msgattrib\n%s" % errors ) elif self.verbosity > 0: self.stdout.write(errors) def copy_plural_forms(self, msgs, locale): """ Copy plural forms header contents from a Django catalog of locale to the msgs string, inserting it at the right place. msgs should be the contents of a newly created .po file. """ django_dir = os.path.normpath(os.path.join(os.path.dirname(django.__file__))) if self.domain == "djangojs": domains = ("djangojs", "django") else: domains = ("django",) for domain in domains: django_po = os.path.join( django_dir, "conf", "locale", locale, "LC_MESSAGES", "%s.po" % domain ) if os.path.exists(django_po): with open(django_po, encoding="utf-8") as fp: m = plural_forms_re.search(fp.read()) if m: plural_form_line = m["value"] if self.verbosity > 1: self.stdout.write("copying plural forms: %s" % plural_form_line) lines = [] found = False for line in msgs.splitlines(): if not found and (not line or plural_forms_re.search(line)): line = plural_form_line found = True lines.append(line) msgs = "\n".join(lines) break return msgs
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/diffsettings.py
django/core/management/commands/diffsettings.py
from django.core.management.base import BaseCommand def module_to_dict(module, omittable=lambda k: k.startswith("_") or not k.isupper()): """Convert a module namespace to a Python dictionary.""" return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)} class Command(BaseCommand): help = """Displays differences between the current settings.py and Django's default settings.""" requires_system_checks = [] def add_arguments(self, parser): parser.add_argument( "--all", action="store_true", help=( 'Display all settings, regardless of their value. In "hash" ' 'mode, default values are prefixed by "###".' ), ) parser.add_argument( "--default", metavar="MODULE", help=( "The settings module to compare the current settings against. Leave " "empty to compare against Django's default settings." ), ) parser.add_argument( "--output", default="hash", choices=("hash", "unified"), help=( "Selects the output format. 'hash' mode displays each changed " "setting, with the settings that don't appear in the defaults " "followed by ###. 'unified' mode prefixes the default setting " "with a minus sign, followed by the changed setting prefixed " "with a plus sign." ), ) def handle(self, **options): from django.conf import Settings, global_settings, settings # Because settings are imported lazily, we need to explicitly load # them. if not settings.configured: settings._setup() user_settings = module_to_dict(settings._wrapped) default = options["default"] default_settings = module_to_dict( Settings(default) if default else global_settings ) output_func = { "hash": self.output_hash, "unified": self.output_unified, }[options["output"]] return "\n".join(output_func(user_settings, default_settings, **options)) def output_hash(self, user_settings, default_settings, **options): # Inspired by Postfix's "postconf -n". output = [] for key in sorted(user_settings): if key not in default_settings: output.append("%s = %s ###" % (key, user_settings[key])) elif user_settings[key] != default_settings[key]: output.append("%s = %s" % (key, user_settings[key])) elif options["all"]: output.append("### %s = %s" % (key, user_settings[key])) return output def output_unified(self, user_settings, default_settings, **options): output = [] for key in sorted(user_settings): if key not in default_settings: output.append( self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])) ) elif user_settings[key] != default_settings[key]: output.append( self.style.ERROR("- %s = %s" % (key, default_settings[key])) ) output.append( self.style.SUCCESS("+ %s = %s" % (key, user_settings[key])) ) elif options["all"]: output.append(" %s = %s" % (key, user_settings[key])) return output
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/__init__.py
django/core/management/commands/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/startproject.py
django/core/management/commands/startproject.py
from django.core.checks.security.base import SECRET_KEY_INSECURE_PREFIX from django.core.management.templates import TemplateCommand from django.core.management.utils import get_random_secret_key class Command(TemplateCommand): help = ( "Creates a Django project directory structure for the given project " "name in the current directory or optionally in the given directory." ) missing_args_message = "You must provide a project name." def handle(self, **options): project_name = options.pop("name") target = options.pop("directory") # Create a random SECRET_KEY to put it in the main settings. options["secret_key"] = SECRET_KEY_INSECURE_PREFIX + get_random_secret_key() super().handle("project", project_name, target, **options)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/createcachetable.py
django/core/management/commands/createcachetable.py
from django.conf import settings from django.core.cache import caches from django.core.cache.backends.db import BaseDatabaseCache from django.core.management.base import BaseCommand, CommandError from django.db import ( DEFAULT_DB_ALIAS, DatabaseError, connections, models, router, transaction, ) class Command(BaseCommand): help = "Creates the tables needed to use the SQL cache backend." requires_system_checks = [] def add_arguments(self, parser): parser.add_argument( "args", metavar="table_name", nargs="*", help=( "Optional table names. Otherwise, settings.CACHES is used to find " "cache tables." ), ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help="Nominates a database onto which the cache tables will be " 'installed. Defaults to the "default" database.', ) parser.add_argument( "--dry-run", action="store_true", help="Does not create the table, just prints the SQL that would be run.", ) def handle(self, *tablenames, **options): db = options["database"] self.verbosity = options["verbosity"] dry_run = options["dry_run"] if tablenames: # Legacy behavior, tablename specified as argument for tablename in tablenames: self.create_table(db, tablename, dry_run) else: for cache_alias in settings.CACHES: cache = caches[cache_alias] if isinstance(cache, BaseDatabaseCache): self.create_table(db, cache._table, dry_run) def create_table(self, database, tablename, dry_run): cache = BaseDatabaseCache(tablename, {}) if not router.allow_migrate_model(database, cache.cache_model_class): return connection = connections[database] if tablename in connection.introspection.table_names(): if self.verbosity > 0: self.stdout.write("Cache table '%s' already exists." % tablename) return fields = ( # "key" is a reserved word in MySQL, so use "cache_key" instead. models.CharField( name="cache_key", max_length=255, unique=True, primary_key=True ), models.TextField(name="value"), models.DateTimeField(name="expires", db_index=True), ) table_output = [] index_output = [] qn = connection.ops.quote_name for f in fields: field_output = [ qn(f.name), f.db_type(connection=connection), "%sNULL" % ("NOT " if not f.null else ""), ] if f.primary_key: field_output.append("PRIMARY KEY") elif f.unique: field_output.append("UNIQUE") if f.db_index: unique = "UNIQUE " if f.unique else "" index_output.append( "CREATE %sINDEX %s ON %s (%s);" % ( unique, qn("%s_%s" % (tablename, f.name)), qn(tablename), qn(f.name), ) ) table_output.append(" ".join(field_output)) full_statement = ["CREATE TABLE %s (" % qn(tablename)] for i, line in enumerate(table_output): full_statement.append( " %s%s" % (line, "," if i < len(table_output) - 1 else "") ) full_statement.append(");") full_statement = "\n".join(full_statement) if dry_run: self.stdout.write(full_statement) for statement in index_output: self.stdout.write(statement) return with transaction.atomic( using=database, savepoint=connection.features.can_rollback_ddl ): with connection.cursor() as curs: try: curs.execute(full_statement) except DatabaseError as e: raise CommandError( "Cache table '%s' could not be created.\nThe error was: %s." % (tablename, e) ) for statement in index_output: curs.execute(statement) if self.verbosity > 1: self.stdout.write("Cache table '%s' created." % tablename)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/test.py
django/core/management/commands/test.py
import sys from django.conf import settings from django.core.management.base import BaseCommand from django.core.management.utils import get_command_line_option from django.test.runner import get_max_test_processes from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner class Command(BaseCommand): help = "Discover and run tests in the specified modules or the current directory." # DiscoverRunner runs the checks after databases are set up. requires_system_checks = [] test_runner = None def run_from_argv(self, argv): """ Pre-parse the command line to extract the value of the --testrunner option. This allows a test runner to define additional command line arguments. """ self.test_runner = get_command_line_option(argv, "--testrunner") super().run_from_argv(argv) def add_arguments(self, parser): parser.add_argument( "args", metavar="test_label", nargs="*", help=( "Module paths to test; can be modulename, modulename.TestCase or " "modulename.TestCase.test_method" ), ) parser.add_argument( "--noinput", "--no-input", action="store_false", dest="interactive", help="Tells Django to NOT prompt the user for input of any kind.", ) parser.add_argument( "--testrunner", help="Tells Django to use specified test runner class instead of " "the one specified by the TEST_RUNNER setting.", ) test_runner_class = get_runner(settings, self.test_runner) if hasattr(test_runner_class, "add_arguments"): test_runner_class.add_arguments(parser) def handle(self, *test_labels, **options): TestRunner = get_runner(settings, options["testrunner"]) time_keeper = TimeKeeper() if options.get("timing", False) else NullTimeKeeper() parallel = options.get("parallel") if parallel == "auto": options["parallel"] = get_max_test_processes() test_runner = TestRunner(**options) with time_keeper.timed("Total run"): failures = test_runner.run_tests(test_labels) time_keeper.print_results() if failures: sys.exit(1)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/sendtestemail.py
django/core/management/commands/sendtestemail.py
import socket from django.core.mail import mail_admins, mail_managers, send_mail from django.core.management.base import BaseCommand from django.utils import timezone class Command(BaseCommand): help = "Sends a test email to the email addresses specified as arguments." missing_args_message = ( "You must specify some email recipients, or pass the --managers or --admin " "options." ) def add_arguments(self, parser): parser.add_argument( "email", nargs="*", help="One or more email addresses to send a test email to.", ) parser.add_argument( "--managers", action="store_true", help="Send a test email to the addresses specified in settings.MANAGERS.", ) parser.add_argument( "--admins", action="store_true", help="Send a test email to the addresses specified in settings.ADMINS.", ) def handle(self, *args, **kwargs): subject = "Test email from %s on %s" % (socket.gethostname(), timezone.now()) send_mail( subject=subject, message="If you're reading this, it was successful.", from_email=None, recipient_list=kwargs["email"], ) if kwargs["managers"]: mail_managers(subject, "This email was sent to the site managers.") if kwargs["admins"]: mail_admins(subject, "This email was sent to the site admins.")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/dbshell.py
django/core/management/commands/dbshell.py
import subprocess from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections class Command(BaseCommand): help = ( "Runs the command-line client for specified database, or the " "default database if none is provided." ) requires_system_checks = [] def add_arguments(self, parser): parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( "Nominates a database onto which to open a shell. Defaults to the " '"default" database.' ), ) parameters = parser.add_argument_group("parameters") parameters.add_argument("parameters", nargs="*") def handle(self, **options): connection = connections[options["database"]] try: connection.client.runshell(options["parameters"]) except FileNotFoundError: # Note that we're assuming the FileNotFoundError relates to the # command missing. It could be raised for some other reason, in # which case this error message would be inaccurate. Still, this # message catches the common case. raise CommandError( "You appear not to have the %r program installed or on your path." % connection.client.executable_name ) except subprocess.CalledProcessError as e: raise CommandError( '"%s" returned non-zero exit status %s.' % ( " ".join(map(str, e.cmd)), e.returncode, ), returncode=e.returncode, )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/dumpdata.py
django/core/management/commands/dumpdata.py
import gzip import os import warnings from django.apps import apps from django.core import serializers from django.core.management.base import BaseCommand, CommandError from django.core.management.utils import parse_apps_and_model_labels from django.db import DEFAULT_DB_ALIAS, connections, router try: import bz2 has_bz2 = True except ImportError: has_bz2 = False try: import lzma has_lzma = True except ImportError: has_lzma = False class ProxyModelWarning(Warning): pass class Command(BaseCommand): help = ( "Output the contents of the database as a fixture of the given format " "(using each model's default manager unless --all is specified)." ) def add_arguments(self, parser): parser.add_argument( "args", metavar="app_label[.ModelName]", nargs="*", help=( "Restricts dumped data to the specified app_label or " "app_label.ModelName." ), ) parser.add_argument( "--format", default="json", help="Specifies the output serialization format for fixtures.", ) parser.add_argument( "--indent", type=int, help="Specifies the indent level to use when pretty-printing output.", ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help="Nominates a specific database to dump fixtures from. " 'Defaults to the "default" database.', ) parser.add_argument( "-e", "--exclude", action="append", default=[], help="An app_label or app_label.ModelName to exclude " "(use multiple --exclude to exclude multiple apps/models).", ) parser.add_argument( "--natural-foreign", action="store_true", dest="use_natural_foreign_keys", help="Use natural foreign keys if they are available.", ) parser.add_argument( "--natural-primary", action="store_true", dest="use_natural_primary_keys", help="Use natural primary keys if they are available.", ) parser.add_argument( "-a", "--all", action="store_true", dest="use_base_manager", help=( "Use Django's base manager to dump all models stored in the database, " "including those that would otherwise be filtered or modified by a " "custom manager." ), ) parser.add_argument( "--pks", dest="primary_keys", help="Only dump objects with given primary keys. Accepts a comma-separated " "list of keys. This option only works when you specify one model.", ) parser.add_argument( "-o", "--output", help="Specifies file to which the output is written." ) def handle(self, *app_labels, **options): format = options["format"] indent = options["indent"] using = options["database"] excludes = options["exclude"] output = options["output"] show_traceback = options["traceback"] use_natural_foreign_keys = options["use_natural_foreign_keys"] use_natural_primary_keys = options["use_natural_primary_keys"] use_base_manager = options["use_base_manager"] pks = options["primary_keys"] if pks: primary_keys = [pk.strip() for pk in pks.split(",")] else: primary_keys = [] excluded_models, excluded_apps = parse_apps_and_model_labels(excludes) if not app_labels: if primary_keys: raise CommandError("You can only use --pks option with one model") app_list = dict.fromkeys( app_config for app_config in apps.get_app_configs() if app_config.models_module is not None and app_config not in excluded_apps ) else: if len(app_labels) > 1 and primary_keys: raise CommandError("You can only use --pks option with one model") app_list = {} for label in app_labels: try: app_label, model_label = label.split(".") try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None or app_config in excluded_apps: continue try: model = app_config.get_model(model_label) except LookupError: raise CommandError( "Unknown model: %s.%s" % (app_label, model_label) ) app_list_value = app_list.setdefault(app_config, []) # We may have previously seen an "all-models" request for # this app (no model qualifier was given). In this case # there is no need adding specific models to the list. if app_list_value is not None and model not in app_list_value: app_list_value.append(model) except ValueError: if primary_keys: raise CommandError( "You can only use --pks option with one model" ) # This is just an app - no model qualifier app_label = label try: app_config = apps.get_app_config(app_label) except LookupError as e: raise CommandError(str(e)) if app_config.models_module is None or app_config in excluded_apps: continue app_list[app_config] = None # Check that the serialization format exists; this is a shortcut to # avoid collating all the objects and _then_ failing. if format not in serializers.get_public_serializer_formats(): try: serializers.get_serializer(format) except serializers.SerializerDoesNotExist: pass raise CommandError("Unknown serialization format: %s" % format) def get_objects(count_only=False): """ Collate the objects to be serialized. If count_only is True, just count the number of objects to be serialized. """ if use_natural_foreign_keys: models = serializers.sort_dependencies( app_list.items(), allow_cycles=True ) else: # There is no need to sort dependencies when natural foreign # keys are not used. models = [] for app_config, model_list in app_list.items(): if model_list is None: models.extend(app_config.get_models()) else: models.extend(model_list) for model in models: if model in excluded_models: continue if model._meta.proxy and model._meta.proxy_for_model not in models: warnings.warn( "%s is a proxy model and won't be serialized." % model._meta.label, category=ProxyModelWarning, ) if not model._meta.proxy and router.allow_migrate_model(using, model): if use_base_manager: objects = model._base_manager else: objects = model._default_manager queryset = objects.using(using).order_by(model._meta.pk.name) if primary_keys: queryset = queryset.filter(pk__in=primary_keys) if count_only: yield queryset.order_by().count() else: chunk_size = ( 2000 if queryset._prefetch_related_lookups else None ) yield from queryset.iterator(chunk_size=chunk_size) try: self.stdout.ending = None progress_output = None object_count = 0 # If dumpdata is outputting to stdout, there is no way to display # progress if output and self.stdout.isatty() and options["verbosity"] > 0: progress_output = self.stdout object_count = sum(get_objects(count_only=True)) if output: file_root, file_ext = os.path.splitext(output) compression_formats = { ".bz2": (open, {}, file_root), ".gz": (gzip.open, {}, output), ".lzma": (open, {}, file_root), ".xz": (open, {}, file_root), ".zip": (open, {}, file_root), } if has_bz2: compression_formats[".bz2"] = (bz2.open, {}, output) if has_lzma: compression_formats[".lzma"] = ( lzma.open, {"format": lzma.FORMAT_ALONE}, output, ) compression_formats[".xz"] = (lzma.open, {}, output) try: open_method, kwargs, file_path = compression_formats[file_ext] except KeyError: open_method, kwargs, file_path = (open, {}, output) if file_path != output: file_name = os.path.basename(file_path) warnings.warn( f"Unsupported file extension ({file_ext}). " f"Fixtures saved in '{file_name}'.", RuntimeWarning, ) stream = open_method(file_path, "wt", **kwargs) else: stream = None try: serializers.serialize( format, get_objects(), indent=indent, use_natural_foreign_keys=use_natural_foreign_keys, use_natural_primary_keys=use_natural_primary_keys, stream=stream or self.stdout, progress_output=progress_output, object_count=object_count, ) finally: if stream: stream.close() except Exception as e: if show_traceback: raise raise CommandError("Unable to serialize database: %s" % e)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/management/commands/sqlmigrate.py
django/core/management/commands/sqlmigrate.py
from django.apps import apps from django.core.management.base import BaseCommand, CommandError from django.db import DEFAULT_DB_ALIAS, connections from django.db.migrations.loader import AmbiguityError, MigrationLoader class Command(BaseCommand): help = "Prints the SQL statements for the named migration." output_transaction = True def add_arguments(self, parser): parser.add_argument( "app_label", help="App label of the application containing the migration." ) parser.add_argument( "migration_name", help="Migration name to print the SQL for." ) parser.add_argument( "--database", default=DEFAULT_DB_ALIAS, choices=tuple(connections), help=( 'Nominates a database to create SQL for. Defaults to the "default" ' "database." ), ) parser.add_argument( "--backwards", action="store_true", help="Creates SQL to unapply the migration, rather than to apply it", ) def execute(self, *args, **options): # sqlmigrate doesn't support coloring its output, so make the # BEGIN/COMMIT statements added by output_transaction colorless also. self.style.SQL_KEYWORD = lambda noop: noop return super().execute(*args, **options) def handle(self, *args, **options): # Get the database we're operating from connection = connections[options["database"]] # Load up a loader to get all the migration data, but don't replace # migrations. loader = MigrationLoader(connection, replace_migrations=False) # Resolve command-line arguments into a migration app_label, migration_name = options["app_label"], options["migration_name"] # Validate app_label try: apps.get_app_config(app_label) except LookupError as err: raise CommandError(str(err)) if app_label not in loader.migrated_apps: raise CommandError("App '%s' does not have migrations" % app_label) try: migration = loader.get_migration_by_prefix(app_label, migration_name) except AmbiguityError: raise CommandError( "More than one migration matches '%s' in app '%s'. Please be more " "specific." % (migration_name, app_label) ) except KeyError: raise CommandError( "Cannot find a migration matching '%s' from app '%s'. Is it in " "INSTALLED_APPS?" % (migration_name, app_label) ) target = (app_label, migration.name) # Show begin/end around output for atomic migrations, if the database # supports transactional DDL. self.output_transaction = ( migration.atomic and connection.features.can_rollback_ddl ) # Make a plan that represents just the requested migrations and show # SQL for it plan = [(loader.graph.nodes[target], options["backwards"])] sql_statements = loader.collect_sql(plan) if not sql_statements and options["verbosity"] >= 1: self.stderr.write("No operations found.") return "\n".join(sql_statements)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/jsonl.py
django/core/serializers/jsonl.py
""" Serialize data to/from JSON Lines """ import json from django.core.serializers.base import DeserializationError from django.core.serializers.json import DjangoJSONEncoder from django.core.serializers.python import Deserializer as PythonDeserializer from django.core.serializers.python import Serializer as PythonSerializer class Serializer(PythonSerializer): """Convert a queryset to JSON Lines.""" internal_use_only = False def _init_options(self): self._current = None self.json_kwargs = self.options.copy() self.json_kwargs.pop("stream", None) self.json_kwargs.pop("fields", None) self.json_kwargs.pop("indent", None) self.json_kwargs["separators"] = (",", ": ") self.json_kwargs.setdefault("cls", DjangoJSONEncoder) self.json_kwargs.setdefault("ensure_ascii", False) def start_serialization(self): self._init_options() def end_object(self, obj): # self._current has the field data json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) self.stream.write("\n") self._current = None def getvalue(self): # Grandparent super return super(PythonSerializer, self).getvalue() class Deserializer(PythonDeserializer): """Deserialize a stream or string of JSON data.""" def __init__(self, stream_or_string, **options): if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode() if isinstance(stream_or_string, str): stream_or_string = stream_or_string.splitlines() super().__init__(Deserializer._get_lines(stream_or_string), **options) def _handle_object(self, obj): try: yield from super()._handle_object(obj) except (GeneratorExit, DeserializationError): raise except Exception as exc: raise DeserializationError(f"Error deserializing object: {exc}") from exc @staticmethod def _get_lines(stream): for line in stream: if not line.strip(): continue try: yield json.loads(line) except Exception as exc: raise DeserializationError() from exc
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/python.py
django/core/serializers/python.py
""" A Python "serializer". Doesn't do much serializing per se -- just converts to and from basic Python data types (lists, dicts, strings, etc.). Useful as a basis for other serializers. """ from django.apps import apps from django.core.serializers import base from django.db import DEFAULT_DB_ALIAS, models from django.db.models import CompositePrimaryKey from django.utils.encoding import is_protected_type class Serializer(base.Serializer): """ Serialize a QuerySet to basic Python objects. """ internal_use_only = True def start_serialization(self): self._current = None self.objects = [] def end_serialization(self): pass def start_object(self, obj): self._current = {} def end_object(self, obj): self.objects.append(self.get_dump_object(obj)) self._current = None def get_dump_object(self, obj): data = {"model": str(obj._meta)} if not self.use_natural_primary_keys or not self._resolve_natural_key(obj): data["pk"] = self._value_from_field(obj, obj._meta.pk) data["fields"] = self._current return data def _value_from_field(self, obj, field): if isinstance(field, CompositePrimaryKey): return [self._value_from_field(obj, f) for f in field] value = field.value_from_object(obj) # Protected types (i.e., primitives like None, numbers, dates, # and Decimals) are passed through as is. All other values are # converted to string first. return value if is_protected_type(value) else field.value_to_string(obj) def handle_field(self, obj, field): self._current[field.name] = self._value_from_field(obj, field) def handle_fk_field(self, obj, field): if self.use_natural_foreign_keys and ( natural_key_value := self._resolve_fk_natural_key(obj, field) ): value = natural_key_value else: value = self._value_from_field(obj, field) self._current[field.name] = value def handle_m2m_field(self, obj, field): if field.remote_field.through._meta.auto_created: if self.use_natural_foreign_keys and self._model_supports_natural_key( field.remote_field.model ): def m2m_value(value): if natural := value.natural_key(): return natural else: return self._value_from_field(value, value._meta.pk) def queryset_iterator(obj, field): attr = getattr(obj, field.name) chunk_size = ( 2000 if getattr(attr, "prefetch_cache_name", None) else None ) return attr.iterator(chunk_size) else: def m2m_value(value): return self._value_from_field(value, value._meta.pk) def queryset_iterator(obj, field): query_set = getattr(obj, field.name).select_related(None).only("pk") chunk_size = 2000 if query_set._prefetch_related_lookups else None return query_set.iterator(chunk_size=chunk_size) m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get( field.name, queryset_iterator(obj, field), ) self._current[field.name] = [m2m_value(related) for related in m2m_iter] def getvalue(self): return self.objects class Deserializer(base.Deserializer): """ Deserialize simple Python objects back into Django ORM instances. It's expected that you pass the Python objects themselves (instead of a stream or a string) to the constructor """ def __init__( self, object_list, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options ): super().__init__(object_list, **options) self.handle_forward_references = options.pop("handle_forward_references", False) self.using = using self.ignorenonexistent = ignorenonexistent self.field_names_cache = {} # Model: <list of field_names> self._iterator = None def __iter__(self): for obj in self.stream: yield from self._handle_object(obj) def __next__(self): if self._iterator is None: self._iterator = iter(self) return next(self._iterator) def _handle_object(self, obj): data = {} m2m_data = {} deferred_fields = {} # Look up the model and starting build a dict of data for it. try: Model = self._get_model_from_node(obj["model"]) except base.DeserializationError: if self.ignorenonexistent: return raise if "pk" in obj: try: data[Model._meta.pk.attname] = Model._meta.pk.to_python(obj.get("pk")) except Exception as e: raise base.DeserializationError.WithData( e, obj["model"], obj.get("pk"), None ) if Model not in self.field_names_cache: self.field_names_cache[Model] = {f.name for f in Model._meta.get_fields()} field_names = self.field_names_cache[Model] # Handle each field for field_name, field_value in obj["fields"].items(): if self.ignorenonexistent and field_name not in field_names: # skip fields no longer on model continue field = Model._meta.get_field(field_name) # Handle M2M relations if field.remote_field and isinstance( field.remote_field, models.ManyToManyRel ): try: values = self._handle_m2m_field_node(field, field_value) if values == base.DEFER_FIELD: deferred_fields[field] = field_value else: m2m_data[field.name] = values except base.M2MDeserializationError as e: raise base.DeserializationError.WithData( e.original_exc, obj["model"], obj.get("pk"), e.pk ) # Handle FK fields elif field.remote_field and isinstance( field.remote_field, models.ManyToOneRel ): try: value = self._handle_fk_field_node(field, field_value) if value == base.DEFER_FIELD: deferred_fields[field] = field_value else: data[field.attname] = value except Exception as e: raise base.DeserializationError.WithData( e, obj["model"], obj.get("pk"), field_value ) # Handle all other fields else: try: data[field.name] = field.to_python(field_value) except Exception as e: raise base.DeserializationError.WithData( e, obj["model"], obj.get("pk"), field_value ) model_instance = base.build_instance(Model, data, self.using) yield base.DeserializedObject(model_instance, m2m_data, deferred_fields) def _handle_m2m_field_node(self, field, field_value): return base.deserialize_m2m_values( field, field_value, self.using, self.handle_forward_references ) def _handle_fk_field_node(self, field, field_value): return base.deserialize_fk_value( field, field_value, self.using, self.handle_forward_references ) @staticmethod def _get_model_from_node(model_identifier): """Look up a model from an "app_label.model_name" string.""" try: return apps.get_model(model_identifier) except (LookupError, TypeError): raise base.DeserializationError( f"Invalid model identifier: {model_identifier}" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/__init__.py
django/core/serializers/__init__.py
""" Interfaces for serializing Django objects. Usage:: from django.core import serializers json = serializers.serialize("json", some_queryset) objects = list(serializers.deserialize("json", json)) To add your own serializers, use the SERIALIZATION_MODULES setting:: SERIALIZATION_MODULES = { "csv": "path.to.csv.serializer", "txt": "path.to.txt.serializer", } """ import importlib from django.apps import apps from django.conf import settings from django.core.serializers.base import SerializerDoesNotExist # Built-in serializers BUILTIN_SERIALIZERS = { "xml": "django.core.serializers.xml_serializer", "python": "django.core.serializers.python", "json": "django.core.serializers.json", "yaml": "django.core.serializers.pyyaml", "jsonl": "django.core.serializers.jsonl", } _serializers = {} class BadSerializer: """ Stub serializer to hold exception raised during registration This allows the serializer registration to cache serializers and if there is an error raised in the process of creating a serializer it will be raised and passed along to the caller when the serializer is used. """ internal_use_only = False def __init__(self, exception): self.exception = exception def __call__(self, *args, **kwargs): raise self.exception def register_serializer(format, serializer_module, serializers=None): """Register a new serializer. ``serializer_module`` should be the fully qualified module name for the serializer. If ``serializers`` is provided, the registration will be added to the provided dictionary. If ``serializers`` is not provided, the registration will be made directly into the global register of serializers. Adding serializers directly is not a thread-safe operation. """ if serializers is None and not _serializers: _load_serializers() try: module = importlib.import_module(serializer_module) except ImportError as exc: bad_serializer = BadSerializer(exc) module = type( "BadSerializerModule", (), { "Deserializer": bad_serializer, "Serializer": bad_serializer, }, ) if serializers is None: _serializers[format] = module else: serializers[format] = module def unregister_serializer(format): "Unregister a given serializer. This is not a thread-safe operation." if not _serializers: _load_serializers() if format not in _serializers: raise SerializerDoesNotExist(format) del _serializers[format] def get_serializer(format): if not _serializers: _load_serializers() if format not in _serializers: raise SerializerDoesNotExist(format) return _serializers[format].Serializer def get_serializer_formats(): if not _serializers: _load_serializers() return list(_serializers) def get_public_serializer_formats(): if not _serializers: _load_serializers() return [k for k, v in _serializers.items() if not v.Serializer.internal_use_only] def get_deserializer(format): if not _serializers: _load_serializers() if format not in _serializers: raise SerializerDoesNotExist(format) return _serializers[format].Deserializer def serialize(format, queryset, **options): """ Serialize a queryset (or any iterator that returns database objects) using a certain serializer. """ s = get_serializer(format)() s.serialize(queryset, **options) return s.getvalue() def deserialize(format, stream_or_string, **options): """ Deserialize a stream or a string. Return an iterator that yields ``(obj, m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* -- object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name : list_of_related_objects}``. """ d = get_deserializer(format) return d(stream_or_string, **options) def _load_serializers(): """ Register built-in and settings-defined serializers. This is done lazily so that user code has a chance to (e.g.) set up custom settings without needing to be careful of import order. """ global _serializers serializers = {} for format in BUILTIN_SERIALIZERS: register_serializer(format, BUILTIN_SERIALIZERS[format], serializers) if hasattr(settings, "SERIALIZATION_MODULES"): for format in settings.SERIALIZATION_MODULES: register_serializer( format, settings.SERIALIZATION_MODULES[format], serializers ) _serializers = serializers def sort_dependencies(app_list, allow_cycles=False): """Sort a list of (app_config, models) pairs into a single list of models. The single list of models is sorted so that any model with a natural key is serialized before a normal model, and any model with a natural key dependency has it's dependencies serialized first. If allow_cycles is True, return the best-effort ordering that will respect most of dependencies but ignore some of them to break the cycles. """ # Process the list of models, and get the list of dependencies model_dependencies = [] models = set() for app_config, model_list in app_list: if model_list is None: model_list = app_config.get_models() for model in model_list: models.add(model) # Add any explicitly defined dependencies if hasattr(model, "natural_key"): deps = getattr(model.natural_key, "dependencies", []) if deps: deps = [apps.get_model(dep) for dep in deps] else: deps = [] # Now add a dependency for any FK relation with a model that # defines a natural key for field in model._meta.fields: if field.remote_field: rel_model = field.remote_field.model if hasattr(rel_model, "natural_key") and rel_model != model: deps.append(rel_model) # Also add a dependency for any simple M2M relation with a model # that defines a natural key. M2M relations with explicit through # models don't count as dependencies. for field in model._meta.many_to_many: if field.remote_field.through._meta.auto_created: rel_model = field.remote_field.model if hasattr(rel_model, "natural_key") and rel_model != model: deps.append(rel_model) model_dependencies.append((model, deps)) model_dependencies.reverse() # Now sort the models to ensure that dependencies are met. This # is done by repeatedly iterating over the input list of models. # If all the dependencies of a given model are in the final list, # that model is promoted to the end of the final list. This process # continues until the input list is empty, or we do a full iteration # over the input models without promoting a model to the final list. # If we do a full iteration without a promotion, that means there are # circular dependencies in the list. model_list = [] while model_dependencies: skipped = [] changed = False while model_dependencies: model, deps = model_dependencies.pop() # If all of the models in the dependency list are either already # on the final model list, or not on the original serialization # list, then we've found another model with all it's dependencies # satisfied. if all(d not in models or d in model_list for d in deps): model_list.append(model) changed = True else: skipped.append((model, deps)) if not changed: if allow_cycles: # If cycles are allowed, add the last skipped model and ignore # its dependencies. This could be improved by some graph # analysis to ignore as few dependencies as possible. model, _ = skipped.pop() model_list.append(model) else: raise RuntimeError( "Can't resolve dependencies for %s in serialized app list." % ", ".join( model._meta.label for model, deps in sorted( skipped, key=lambda obj: obj[0].__name__ ) ), ) model_dependencies = skipped return model_list
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/json.py
django/core/serializers/json.py
""" Serialize data to/from JSON """ import datetime import decimal import json import uuid from django.core.serializers.base import DeserializationError from django.core.serializers.python import Deserializer as PythonDeserializer from django.core.serializers.python import Serializer as PythonSerializer from django.utils.duration import duration_iso_string from django.utils.functional import Promise from django.utils.timezone import is_aware class Serializer(PythonSerializer): """Convert a queryset to JSON.""" internal_use_only = False def _init_options(self): self._current = None self.json_kwargs = self.options.copy() self.json_kwargs.pop("stream", None) self.json_kwargs.pop("fields", None) if self.options.get("indent"): # Prevent trailing spaces self.json_kwargs["separators"] = (",", ": ") self.json_kwargs.setdefault("cls", DjangoJSONEncoder) self.json_kwargs.setdefault("ensure_ascii", False) def start_serialization(self): self._init_options() self.stream.write("[") def end_serialization(self): if self.options.get("indent"): self.stream.write("\n") self.stream.write("]") self.stream.write("\n") def end_object(self, obj): # self._current has the field data indent = self.options.get("indent") if not self.first: self.stream.write(",") if not indent: self.stream.write(" ") if indent: self.stream.write("\n") json.dump(self.get_dump_object(obj), self.stream, **self.json_kwargs) self._current = None def getvalue(self): # Grandparent super return super(PythonSerializer, self).getvalue() class Deserializer(PythonDeserializer): """Deserialize a stream or string of JSON data.""" def __init__(self, stream_or_string, **options): if not isinstance(stream_or_string, (bytes, str)): stream_or_string = stream_or_string.read() if isinstance(stream_or_string, bytes): stream_or_string = stream_or_string.decode() try: objects = json.loads(stream_or_string) except Exception as exc: raise DeserializationError() from exc super().__init__(objects, **options) def _handle_object(self, obj): try: yield from super()._handle_object(obj) except (GeneratorExit, DeserializationError): raise except Exception as exc: raise DeserializationError(f"Error deserializing object: {exc}") from exc class DjangoJSONEncoder(json.JSONEncoder): """ JSONEncoder subclass that knows how to encode date/time, decimal types, and UUIDs. """ def default(self, o): # See "Date Time String Format" in the ECMA-262 specification. if isinstance(o, datetime.datetime): r = o.isoformat() if o.microsecond: r = r[:23] + r[26:] if r.endswith("+00:00"): r = r.removesuffix("+00:00") + "Z" return r elif isinstance(o, datetime.date): return o.isoformat() elif isinstance(o, datetime.time): if is_aware(o): raise ValueError("JSON can't represent timezone-aware times.") r = o.isoformat() if o.microsecond: r = r[:12] return r elif isinstance(o, datetime.timedelta): return duration_iso_string(o) elif isinstance(o, (decimal.Decimal, uuid.UUID, Promise)): return str(o) else: return super().default(o)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/base.py
django/core/serializers/base.py
""" Module for abstract serializer/unserializer base classes. """ from io import StringIO from django.core.exceptions import ObjectDoesNotExist from django.db import models DEFER_FIELD = object() class SerializerDoesNotExist(KeyError): """The requested serializer was not found.""" pass class SerializationError(Exception): """Something bad happened during serialization.""" pass class DeserializationError(Exception): """Something bad happened during deserialization.""" @classmethod def WithData(cls, original_exc, model, fk, field_value): """ Factory method for creating a deserialization error which has a more explanatory message. """ return cls( "%s: (%s:pk=%s) field_value was '%s'" % (original_exc, model, fk, field_value) ) class M2MDeserializationError(Exception): """Something bad happened during deserialization of a ManyToManyField.""" def __init__(self, original_exc, pk): self.original_exc = original_exc self.pk = pk class ProgressBar: progress_width = 75 def __init__(self, output, total_count): self.output = output self.total_count = total_count self.prev_done = 0 def update(self, count): if not self.output: return perc = count * 100 // self.total_count done = perc * self.progress_width // 100 if self.prev_done >= done: return self.prev_done = done cr = "" if self.total_count == 1 else "\r" self.output.write( cr + "[" + "." * done + " " * (self.progress_width - done) + "]" ) if done == self.progress_width: self.output.write("\n") self.output.flush() class Serializer: """ Abstract serializer base class. """ # Indicates if the implemented serializer is only available for # internal Django use. internal_use_only = False progress_class = ProgressBar stream_class = StringIO def serialize( self, queryset, *, stream=None, fields=None, use_natural_foreign_keys=False, use_natural_primary_keys=False, progress_output=None, object_count=0, **options, ): """ Serialize a queryset. """ self.options = options self.stream = stream if stream is not None else self.stream_class() self.selected_fields = fields self.use_natural_foreign_keys = use_natural_foreign_keys self.use_natural_primary_keys = use_natural_primary_keys progress_bar = self.progress_class(progress_output, object_count) self.start_serialization() self.first = True for count, obj in enumerate(queryset, start=1): self.start_object(obj) # Use the concrete parent class' _meta instead of the object's # _meta This is to avoid local_fields problems for proxy models. # Refs #17717. concrete_model = obj._meta.concrete_model # When using natural primary keys, retrieve the pk field of the # parent for multi-table inheritance child models. That field must # be serialized, otherwise deserialization isn't possible. if self.use_natural_primary_keys: pk = concrete_model._meta.pk pk_parent = ( pk if pk.remote_field and pk.remote_field.parent_link else None ) else: pk_parent = None for field in concrete_model._meta.local_fields: if field.serialize or field is pk_parent: if field.remote_field is None: if ( self.selected_fields is None or field.attname in self.selected_fields ): self.handle_field(obj, field) else: if ( self.selected_fields is None or field.attname[:-3] in self.selected_fields ): self.handle_fk_field(obj, field) for field in concrete_model._meta.local_many_to_many: if field.serialize: if ( self.selected_fields is None or field.attname in self.selected_fields ): self.handle_m2m_field(obj, field) self.end_object(obj) progress_bar.update(count) self.first = self.first and False self.end_serialization() return self.getvalue() def start_serialization(self): """ Called when serializing of the queryset starts. """ raise NotImplementedError( "subclasses of Serializer must provide a start_serialization() method" ) def end_serialization(self): """ Called when serializing of the queryset ends. """ pass def start_object(self, obj): """ Called when serializing of an object starts. """ raise NotImplementedError( "subclasses of Serializer must provide a start_object() method" ) def end_object(self, obj): """ Called when serializing of an object ends. """ pass def handle_field(self, obj, field): """ Called to handle each individual (non-relational) field on an object. """ raise NotImplementedError( "subclasses of Serializer must provide a handle_field() method" ) def handle_fk_field(self, obj, field): """ Called to handle a ForeignKey field. """ raise NotImplementedError( "subclasses of Serializer must provide a handle_fk_field() method" ) def handle_m2m_field(self, obj, field): """ Called to handle a ManyToManyField. """ raise NotImplementedError( "subclasses of Serializer must provide a handle_m2m_field() method" ) def getvalue(self): """ Return the fully serialized queryset (or None if the output stream is not seekable). """ if callable(getattr(self.stream, "getvalue", None)): return self.stream.getvalue() def _resolve_natural_key(self, obj): """Return a natural key tuple for the given object when available.""" try: return obj.natural_key() except AttributeError: return None def _resolve_fk_natural_key(self, obj, field): """ Return the natural key for a ForeignKey's related object, or None if not supported. """ if not self._model_supports_natural_key(field.remote_field.model): return None related = getattr(obj, field.name, None) try: return related.natural_key() except AttributeError: return None def _model_supports_natural_key(self, model): """Return True if the model defines a natural_key() method.""" try: return callable(model.natural_key) except AttributeError: return False class Deserializer: """ Abstract base deserializer class. """ def __init__(self, stream_or_string, **options): """ Init this serializer given a stream or a string """ self.options = options if isinstance(stream_or_string, str): self.stream = StringIO(stream_or_string) else: self.stream = stream_or_string def __iter__(self): return self def __next__(self): """Iteration interface -- return the next item in the stream""" raise NotImplementedError( "subclasses of Deserializer must provide a __next__() method" ) class DeserializedObject: """ A deserialized model. Basically a container for holding the pre-saved deserialized data along with the many-to-many data saved with the object. Call ``save()`` to save the object (with the many-to-many data) to the database; call ``save(save_m2m=False)`` to save just the object fields (and not touch the many-to-many stuff.) """ def __init__(self, obj, m2m_data=None, deferred_fields=None): self.object = obj self.m2m_data = m2m_data self.deferred_fields = deferred_fields def __repr__(self): return "<%s: %s(pk=%s)>" % ( self.__class__.__name__, self.object._meta.label, self.object.pk, ) def save(self, save_m2m=True, using=None, **kwargs): # Call save on the Model baseclass directly. This bypasses any # model-defined save. The save is also forced to be raw. # raw=True is passed to any pre/post_save and m2m_changed signals. models.Model.save_base(self.object, using=using, raw=True, **kwargs) if self.m2m_data and save_m2m: for accessor_name, object_list in self.m2m_data.items(): getattr(self.object, accessor_name).set_base(object_list, raw=True) # prevent a second (possibly accidental) call to save() from saving # the m2m data twice. self.m2m_data = None def save_deferred_fields(self, using=None): self.m2m_data = {} for field, field_value in self.deferred_fields.items(): opts = self.object._meta label = opts.app_label + "." + opts.model_name if isinstance(field.remote_field, models.ManyToManyRel): try: values = deserialize_m2m_values( field, field_value, using, handle_forward_references=False ) except M2MDeserializationError as e: raise DeserializationError.WithData( e.original_exc, label, self.object.pk, e.pk ) self.m2m_data[field.name] = values elif isinstance(field.remote_field, models.ManyToOneRel): try: value = deserialize_fk_value( field, field_value, using, handle_forward_references=False ) except Exception as e: raise DeserializationError.WithData( e, label, self.object.pk, field_value ) setattr(self.object, field.attname, value) self.save() def build_instance(Model, data, db): """ Build a model instance. If the model instance doesn't have a primary key and the model supports natural keys, try to retrieve it from the database. """ default_manager = Model._meta.default_manager pk = data.get(Model._meta.pk.attname) if ( pk is None and hasattr(default_manager, "get_by_natural_key") and hasattr(Model, "natural_key") ): obj = Model(**data) obj._state.db = db natural_key = obj.natural_key() try: data[Model._meta.pk.attname] = Model._meta.pk.to_python( default_manager.db_manager(db).get_by_natural_key(*natural_key).pk ) except Model.DoesNotExist: pass return Model(**data) def deserialize_m2m_values(field, field_value, using, handle_forward_references): model = field.remote_field.model if hasattr(model._default_manager, "get_by_natural_key"): def m2m_convert(value): if hasattr(value, "__iter__") and not isinstance(value, str): return ( model._default_manager.db_manager(using) .get_by_natural_key(*value) .pk ) else: return model._meta.pk.to_python(value) else: def m2m_convert(v): return model._meta.pk.to_python(v) try: pks_iter = iter(field_value) except TypeError as e: raise M2MDeserializationError(e, field_value) try: values = [] for pk in pks_iter: values.append(m2m_convert(pk)) return values except Exception as e: if isinstance(e, ObjectDoesNotExist) and handle_forward_references: return DEFER_FIELD else: raise M2MDeserializationError(e, pk) def deserialize_fk_value(field, field_value, using, handle_forward_references): if field_value is None: return None model = field.remote_field.model default_manager = model._default_manager field_name = field.remote_field.field_name if ( hasattr(default_manager, "get_by_natural_key") and hasattr(field_value, "__iter__") and not isinstance(field_value, str) ): try: obj = default_manager.db_manager(using).get_by_natural_key(*field_value) except ObjectDoesNotExist: if handle_forward_references: return DEFER_FIELD else: raise value = getattr(obj, field_name) # If this is a natural foreign key to an object that has a FK/O2O as # the foreign key, use the FK value. if model._meta.pk.remote_field: value = value.pk return value return model._meta.get_field(field_name).to_python(field_value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/xml_serializer.py
django/core/serializers/xml_serializer.py
""" XML serializer. """ import json from contextlib import contextmanager from xml.dom import minidom, pulldom from xml.sax import handler from xml.sax.expatreader import ExpatParser as _ExpatParser from django.apps import apps from django.conf import settings from django.core.exceptions import ObjectDoesNotExist from django.core.serializers import base from django.db import DEFAULT_DB_ALIAS, models from django.utils.xmlutils import SimplerXMLGenerator, UnserializableContentError @contextmanager def fast_cache_clearing(): """Workaround for performance issues in minidom document checks. Speeds up repeated DOM operations by skipping unnecessary full traversal of the DOM tree. """ module_helper_was_lambda = False if original_fn := getattr(minidom, "_in_document", None): module_helper_was_lambda = original_fn.__name__ == "<lambda>" if not module_helper_was_lambda: minidom._in_document = lambda node: bool(node.ownerDocument) try: yield finally: if original_fn and not module_helper_was_lambda: minidom._in_document = original_fn class Serializer(base.Serializer): """Serialize a QuerySet to XML.""" def indent(self, level): if self.options.get("indent") is not None: self.xml.ignorableWhitespace( "\n" + " " * self.options.get("indent") * level ) def start_serialization(self): """ Start serialization -- open the XML document and the root element. """ self.xml = SimplerXMLGenerator( self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET) ) self.xml.startDocument() self.xml.startElement("django-objects", {"version": "1.0"}) def end_serialization(self): """ End serialization -- end the document. """ self.indent(0) self.xml.endElement("django-objects") self.xml.endDocument() def start_object(self, obj): """ Called as each object is handled. """ if not hasattr(obj, "_meta"): raise base.SerializationError( "Non-model object (%s) encountered during serialization" % type(obj) ) self.indent(1) attrs = {"model": str(obj._meta)} if not self.use_natural_primary_keys or not self._resolve_natural_key(obj): obj_pk = obj.pk if obj_pk is not None: attrs["pk"] = obj._meta.pk.value_to_string(obj) self.xml.startElement("object", attrs) def end_object(self, obj): """ Called after handling all fields for an object. """ self.indent(1) self.xml.endElement("object") def handle_field(self, obj, field): """ Handle each field on an object (except for ForeignKeys and ManyToManyFields). """ self.indent(2) self.xml.startElement( "field", { "name": field.name, "type": field.get_internal_type(), }, ) # Get a "string version" of the object's data. if getattr(obj, field.name) is not None: value = field.value_to_string(obj) if field.get_internal_type() == "JSONField": # Dump value since JSONField.value_to_string() doesn't output # strings. value = json.dumps(value, cls=field.encoder) try: self.xml.characters(value) except UnserializableContentError: raise ValueError( "%s.%s (pk:%s) contains unserializable characters" % (obj.__class__.__name__, field.name, obj.pk) ) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_fk_field(self, obj, field): """ Handle a ForeignKey (they need to be treated slightly differently from regular fields). """ self._start_relational_field(field) related_att = getattr(obj, field.attname) if related_att is not None: if self.use_natural_foreign_keys and ( natural_key_value := self._resolve_fk_natural_key(obj, field) ): # Iterable natural keys are rolled out as subelements for key_value in natural_key_value: self.xml.startElement("natural", {}) if key_value is None: self.xml.addQuickElement("None") else: self.xml.characters(str(key_value)) self.xml.endElement("natural") else: self.xml.characters(str(related_att)) else: self.xml.addQuickElement("None") self.xml.endElement("field") def handle_m2m_field(self, obj, field): """ Handle a ManyToManyField. Related objects are only serialized as references to the object's PK (i.e. the related *data* is not dumped, just the relation). """ if field.remote_field.through._meta.auto_created: self._start_relational_field(field) if self.use_natural_foreign_keys and self._model_supports_natural_key( field.remote_field.model ): # If the objects in the m2m have a natural key, use it def handle_m2m(value): if natural := self._resolve_natural_key(value): # Iterable natural keys are rolled out as subelements self.xml.startElement("object", {}) for key_value in natural: self.xml.startElement("natural", {}) if key_value is None: self.xml.addQuickElement("None") else: self.xml.characters(str(key_value)) self.xml.endElement("natural") self.xml.endElement("object") else: self.xml.addQuickElement("object", attrs={"pk": str(value.pk)}) def queryset_iterator(obj, field): attr = getattr(obj, field.name) chunk_size = ( 2000 if getattr(attr, "prefetch_cache_name", None) else None ) return attr.iterator(chunk_size) else: def handle_m2m(value): self.xml.addQuickElement("object", attrs={"pk": str(value.pk)}) def queryset_iterator(obj, field): query_set = getattr(obj, field.name).select_related(None).only("pk") chunk_size = 2000 if query_set._prefetch_related_lookups else None return query_set.iterator(chunk_size=chunk_size) m2m_iter = getattr(obj, "_prefetched_objects_cache", {}).get( field.name, queryset_iterator(obj, field), ) for relobj in m2m_iter: handle_m2m(relobj) self.xml.endElement("field") def _start_relational_field(self, field): """Output the <field> element for relational fields.""" self.indent(2) self.xml.startElement( "field", { "name": field.name, "rel": field.remote_field.__class__.__name__, "to": str(field.remote_field.model._meta), }, ) class Deserializer(base.Deserializer): """Deserialize XML.""" def __init__( self, stream_or_string, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options, ): super().__init__(stream_or_string, **options) self.handle_forward_references = options.pop("handle_forward_references", False) self.event_stream = pulldom.parse(self.stream, self._make_parser()) self.db = using self.ignore = ignorenonexistent def _make_parser(self): """Create a hardened XML parser (no custom/external entities).""" return DefusedExpatParser() def __next__(self): for event, node in self.event_stream: if event == "START_ELEMENT" and node.nodeName == "object": with fast_cache_clearing(): self.event_stream.expandNode(node) return self._handle_object(node) raise StopIteration def _handle_object(self, node): """Convert an <object> node to a DeserializedObject.""" # Look up the model using the model loading mechanism. If this fails, # bail. Model = self._get_model_from_node(node, "model") # Start building a data dictionary from the object. data = {} if node.hasAttribute("pk"): data[Model._meta.pk.attname] = Model._meta.pk.to_python( node.getAttribute("pk") ) # Also start building a dict of m2m data (this is saved as # {m2m_accessor_attribute : [list_of_related_objects]}) m2m_data = {} deferred_fields = {} field_names = {f.name for f in Model._meta.get_fields()} # Deserialize each field. for field_node in node.getElementsByTagName("field"): # If the field is missing the name attribute, bail (are you # sensing a pattern here?) field_name = field_node.getAttribute("name") if not field_name: raise base.DeserializationError( "<field> node is missing the 'name' attribute" ) # Get the field from the Model. This will raise a # FieldDoesNotExist if, well, the field doesn't exist, which will # be propagated correctly unless ignorenonexistent=True is used. if self.ignore and field_name not in field_names: continue field = Model._meta.get_field(field_name) # As is usually the case, relation fields get the special # treatment. if field.remote_field and isinstance( field.remote_field, models.ManyToManyRel ): value = self._handle_m2m_field_node(field_node, field) if value == base.DEFER_FIELD: deferred_fields[field] = [ [ ( None if nat_node.getElementsByTagName("None") else getInnerText(nat_node).strip() ) for nat_node in obj_node.getElementsByTagName("natural") ] for obj_node in field_node.getElementsByTagName("object") ] else: m2m_data[field.name] = value elif field.remote_field and isinstance( field.remote_field, models.ManyToOneRel ): value = self._handle_fk_field_node(field_node, field) if value == base.DEFER_FIELD: deferred_fields[field] = [ ( None if k.getElementsByTagName("None") else getInnerText(k).strip() ) for k in field_node.getElementsByTagName("natural") ] else: data[field.attname] = value else: if field_node.getElementsByTagName("None"): value = None else: value = field.to_python(getInnerText(field_node).strip()) # Load value since JSONField.to_python() outputs strings. if field.get_internal_type() == "JSONField": value = json.loads(value, cls=field.decoder) data[field.name] = value obj = base.build_instance(Model, data, self.db) # Return a DeserializedObject so that the m2m data has a place to live. return base.DeserializedObject(obj, m2m_data, deferred_fields) def _handle_fk_field_node(self, node, field): """ Handle a <field> node for a ForeignKey """ # Check if there is a child node named 'None', returning None if so. natural_keys = node.getElementsByTagName("natural") if node.getElementsByTagName("None") and not natural_keys: return None else: model = field.remote_field.model if hasattr(model._default_manager, "get_by_natural_key"): if natural_keys: # If there are 'natural' subelements, it must be a natural # key field_value = [] for k in natural_keys: if k.getElementsByTagName("None"): field_value.append(None) else: field_value.append(getInnerText(k).strip()) try: obj = model._default_manager.db_manager( self.db ).get_by_natural_key(*field_value) except ObjectDoesNotExist: if self.handle_forward_references: return base.DEFER_FIELD else: raise obj_pk = getattr(obj, field.remote_field.field_name) # If this is a natural foreign key to an object that # has a FK/O2O as the foreign key, use the FK value if field.remote_field.model._meta.pk.remote_field: obj_pk = obj_pk.pk else: # Otherwise, treat like a normal PK field_value = getInnerText(node).strip() obj_pk = model._meta.get_field( field.remote_field.field_name ).to_python(field_value) return obj_pk else: field_value = getInnerText(node).strip() return model._meta.get_field(field.remote_field.field_name).to_python( field_value ) def _handle_m2m_field_node(self, node, field): """ Handle a <field> node for a ManyToManyField. """ model = field.remote_field.model default_manager = model._default_manager if hasattr(default_manager, "get_by_natural_key"): def m2m_convert(n): keys = n.getElementsByTagName("natural") if keys: # If there are 'natural' subelements, it must be a natural # key field_value = [] for k in keys: if k.getElementsByTagName("None"): field_value.append(None) else: field_value.append(getInnerText(k).strip()) obj_pk = ( default_manager.db_manager(self.db) .get_by_natural_key(*field_value) .pk ) else: # Otherwise, treat like a normal PK value. obj_pk = model._meta.pk.to_python(n.getAttribute("pk")) return obj_pk else: def m2m_convert(n): return model._meta.pk.to_python(n.getAttribute("pk")) values = [] try: for c in node.getElementsByTagName("object"): values.append(m2m_convert(c)) except Exception as e: if isinstance(e, ObjectDoesNotExist) and self.handle_forward_references: return base.DEFER_FIELD else: raise base.M2MDeserializationError(e, c) else: return values def _get_model_from_node(self, node, attr): """ Look up a model from a <object model=...> or a <field rel=... to=...> node. """ model_identifier = node.getAttribute(attr) if not model_identifier: raise base.DeserializationError( "<%s> node is missing the required '%s' attribute" % (node.nodeName, attr) ) try: return apps.get_model(model_identifier) except (LookupError, TypeError): raise base.DeserializationError( "<%s> node has invalid model identifier: '%s'" % (node.nodeName, model_identifier) ) def getInnerText(node): """Get the inner text of a DOM node and any children one level deep.""" # inspired by # https://mail.python.org/pipermail/xml-sig/2005-March/011022.html return "".join( [ element.data for child in node.childNodes for element in (child, *child.childNodes) if element.nodeType in (element.TEXT_NODE, element.CDATA_SECTION_NODE) ] ) # Below code based on Christian Heimes' defusedxml class DefusedExpatParser(_ExpatParser): """ An expat parser hardened against XML bomb attacks. Forbid DTDs, external entity references """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.setFeature(handler.feature_external_ges, False) self.setFeature(handler.feature_external_pes, False) def start_doctype_decl(self, name, sysid, pubid, has_internal_subset): raise DTDForbidden(name, sysid, pubid) def entity_decl( self, name, is_parameter_entity, value, base, sysid, pubid, notation_name ): raise EntitiesForbidden(name, value, base, sysid, pubid, notation_name) def unparsed_entity_decl(self, name, base, sysid, pubid, notation_name): # expat 1.2 raise EntitiesForbidden(name, None, base, sysid, pubid, notation_name) def external_entity_ref_handler(self, context, base, sysid, pubid): raise ExternalReferenceForbidden(context, base, sysid, pubid) def reset(self): _ExpatParser.reset(self) parser = self._parser parser.StartDoctypeDeclHandler = self.start_doctype_decl parser.EntityDeclHandler = self.entity_decl parser.UnparsedEntityDeclHandler = self.unparsed_entity_decl parser.ExternalEntityRefHandler = self.external_entity_ref_handler class DefusedXmlException(ValueError): """Base exception.""" def __repr__(self): return str(self) class DTDForbidden(DefusedXmlException): """Document type definition is forbidden.""" def __init__(self, name, sysid, pubid): super().__init__() self.name = name self.sysid = sysid self.pubid = pubid def __str__(self): tpl = "DTDForbidden(name='{}', system_id={!r}, public_id={!r})" return tpl.format(self.name, self.sysid, self.pubid) class EntitiesForbidden(DefusedXmlException): """Entity definition is forbidden.""" def __init__(self, name, value, base, sysid, pubid, notation_name): super().__init__() self.name = name self.value = value self.base = base self.sysid = sysid self.pubid = pubid self.notation_name = notation_name def __str__(self): tpl = "EntitiesForbidden(name='{}', system_id={!r}, public_id={!r})" return tpl.format(self.name, self.sysid, self.pubid) class ExternalReferenceForbidden(DefusedXmlException): """Resolving an external reference is forbidden.""" def __init__(self, context, base, sysid, pubid): super().__init__() self.context = context self.base = base self.sysid = sysid self.pubid = pubid def __str__(self): tpl = "ExternalReferenceForbidden(system_id='{}', public_id={})" return tpl.format(self.sysid, self.pubid)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/serializers/pyyaml.py
django/core/serializers/pyyaml.py
""" YAML serializer. Requires PyYaml (https://pyyaml.org/), but that's checked for in __init__. """ import collections import datetime import decimal import yaml from django.core.serializers.base import DeserializationError from django.core.serializers.python import Deserializer as PythonDeserializer from django.core.serializers.python import Serializer as PythonSerializer # Use the C (faster) implementation if possible try: from yaml import CSafeDumper as SafeDumper from yaml import CSafeLoader as SafeLoader except ImportError: from yaml import SafeDumper, SafeLoader class DjangoSafeDumper(SafeDumper): def represent_decimal(self, data): return self.represent_scalar("tag:yaml.org,2002:str", str(data)) def represent_ordered_dict(self, data): return self.represent_mapping("tag:yaml.org,2002:map", data.items()) DjangoSafeDumper.add_representer(decimal.Decimal, DjangoSafeDumper.represent_decimal) DjangoSafeDumper.add_representer( collections.OrderedDict, DjangoSafeDumper.represent_ordered_dict ) # Workaround to represent dictionaries in insertion order. # See https://github.com/yaml/pyyaml/pull/143. DjangoSafeDumper.add_representer(dict, DjangoSafeDumper.represent_ordered_dict) class Serializer(PythonSerializer): """Convert a queryset to YAML.""" internal_use_only = False def _value_from_field(self, obj, field): # A nasty special case: base YAML doesn't support serialization of time # types (as opposed to dates or datetimes, which it does support). # Since we want to use the "safe" serializer for better # interoperability, we need to do something with those pesky times. # Converting 'em to strings isn't perfect, but it's better than a # "!!python/time" type which would halt deserialization under any other # language. value = super()._value_from_field(obj, field) if isinstance(value, datetime.time): value = str(value) return value def end_serialization(self): self.options.setdefault("allow_unicode", True) yaml.dump(self.objects, self.stream, Dumper=DjangoSafeDumper, **self.options) def getvalue(self): # Grandparent super return super(PythonSerializer, self).getvalue() class Deserializer(PythonDeserializer): """Deserialize a stream or string of YAML data.""" def __init__(self, stream_or_string, **options): stream = stream_or_string if isinstance(stream_or_string, bytes): stream = stream_or_string.decode() try: objects = yaml.load(stream, Loader=SafeLoader) except Exception as exc: raise DeserializationError() from exc super().__init__(objects, **options) def _handle_object(self, obj): try: yield from super()._handle_object(obj) except (GeneratorExit, DeserializationError): raise except Exception as exc: raise DeserializationError(f"Error deserializing object: {exc}") from exc
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/message.py
django/core/mail/message.py
import email.message import email.policy import mimetypes import warnings from collections import namedtuple from datetime import datetime, timezone from email import charset as Charset from email import generator from email.errors import HeaderParseError from email.header import Header from email.headerregistry import Address, AddressHeader, parser from email.mime.base import MIMEBase from email.mime.message import MIMEMessage from email.mime.multipart import MIMEMultipart from email.mime.text import MIMEText from email.utils import formataddr, getaddresses, make_msgid from io import BytesIO, StringIO from pathlib import Path from django.conf import settings from django.core.mail.utils import DNS_NAME from django.utils.deprecation import RemovedInDjango70Warning, deprecate_posargs from django.utils.encoding import force_bytes, force_str, punycode from django.utils.timezone import get_current_timezone # RemovedInDjango70Warning. # Don't BASE64-encode UTF-8 messages so that we avoid unwanted attention from # some spam filters. utf8_charset = Charset.Charset("utf-8") utf8_charset.body_encoding = None # Python defaults to BASE64 utf8_charset_qp = Charset.Charset("utf-8") utf8_charset_qp.body_encoding = Charset.QP # Default MIME type to use on attachments (if it is not explicitly given # and cannot be guessed). DEFAULT_ATTACHMENT_MIME_TYPE = "application/octet-stream" # RemovedInDjango70Warning. RFC5322_EMAIL_LINE_LENGTH_LIMIT = 998 # RemovedInDjango70Warning. # BadHeaderError must be ValueError (not subclass it), so that existing code # with `except BadHeaderError` will catch the ValueError that Python's modern # email API raises for headers containing CR or NL. BadHeaderError = ValueError # RemovedInDjango70Warning. # Header names that contain structured address data (RFC 5322). ADDRESS_HEADERS = { "from", "sender", "reply-to", "to", "cc", "bcc", "resent-from", "resent-sender", "resent-to", "resent-cc", "resent-bcc", } # RemovedInDjango70Warning. def forbid_multi_line_headers(name, val, encoding): """Forbid multi-line headers to prevent header injection.""" warnings.warn( "The internal API forbid_multi_line_headers() is deprecated." " Python's modern email API (with email.message.EmailMessage or" " email.policy.default) will reject multi-line headers.", RemovedInDjango70Warning, ) encoding = encoding or settings.DEFAULT_CHARSET val = str(val) # val may be lazy if "\n" in val or "\r" in val: raise BadHeaderError( "Header values can't contain newlines (got %r for header %r)" % (val, name) ) try: val.encode("ascii") except UnicodeEncodeError: if name.lower() in ADDRESS_HEADERS: val = ", ".join( sanitize_address(addr, encoding) for addr in getaddresses((val,)) ) else: val = Header(val, encoding).encode() else: if name.lower() == "subject": val = Header(val).encode() return name, val # RemovedInDjango70Warning. def sanitize_address(addr, encoding): """ Format a pair of (name, address) or an email address string. """ warnings.warn( "The internal API sanitize_address() is deprecated." " Python's modern email API (with email.message.EmailMessage or" " email.policy.default) will handle most required validation and" " encoding. Use Python's email.headerregistry.Address to construct" " formatted addresses from component parts.", RemovedInDjango70Warning, ) address = None if not isinstance(addr, tuple): addr = force_str(addr) try: token, rest = parser.get_mailbox(addr) except (HeaderParseError, ValueError, IndexError): raise ValueError('Invalid address "%s"' % addr) else: if rest: # The entire email address must be parsed. raise ValueError( 'Invalid address; only %s could be parsed from "%s"' % (token, addr) ) nm = token.display_name or "" localpart = token.local_part domain = token.domain or "" else: nm, address = addr if "@" not in address: raise ValueError(f'Invalid address "{address}"') localpart, domain = address.rsplit("@", 1) address_parts = nm + localpart + domain if "\n" in address_parts or "\r" in address_parts: raise ValueError("Invalid address; address parts cannot contain newlines.") # Avoid UTF-8 encode, if it's possible. try: nm.encode("ascii") nm = Header(nm).encode() except UnicodeEncodeError: nm = Header(nm, encoding).encode() try: localpart.encode("ascii") except UnicodeEncodeError: localpart = Header(localpart, encoding).encode() domain = punycode(domain) parsed_address = Address(username=localpart, domain=domain) return formataddr((nm, parsed_address.addr_spec)) # RemovedInDjango70Warning. class MIMEMixin: def as_string(self, unixfrom=False, linesep="\n"): """Return the entire formatted message as a string. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_string() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = StringIO() g = generator.Generator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue() def as_bytes(self, unixfrom=False, linesep="\n"): """Return the entire formatted message as bytes. Optional `unixfrom' when True, means include the Unix From_ envelope header. This overrides the default as_bytes() implementation to not mangle lines that begin with 'From '. See bug #13433 for details. """ fp = BytesIO() g = generator.BytesGenerator(fp, mangle_from_=False) g.flatten(self, unixfrom=unixfrom, linesep=linesep) return fp.getvalue() # RemovedInDjango70Warning. class SafeMIMEMessage(MIMEMixin, MIMEMessage): def __setitem__(self, name, val): # Per RFC 2046 Section 5.2.1, message/rfc822 attachment headers must be # ASCII. name, val = forbid_multi_line_headers(name, val, "ascii") MIMEMessage.__setitem__(self, name, val) # RemovedInDjango70Warning. class SafeMIMEText(MIMEMixin, MIMEText): def __init__(self, _text, _subtype="plain", _charset=None): self.encoding = _charset MIMEText.__init__(self, _text, _subtype=_subtype, _charset=_charset) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEText.__setitem__(self, name, val) def set_payload(self, payload, charset=None): if charset == "utf-8" and not isinstance(charset, Charset.Charset): has_long_lines = any( len(line.encode(errors="surrogateescape")) > RFC5322_EMAIL_LINE_LENGTH_LIMIT for line in payload.splitlines() ) # Quoted-Printable encoding has the side effect of shortening long # lines, if any (#22561). charset = utf8_charset_qp if has_long_lines else utf8_charset MIMEText.set_payload(self, payload, charset=charset) # RemovedInDjango70Warning. class SafeMIMEMultipart(MIMEMixin, MIMEMultipart): def __init__( self, _subtype="mixed", boundary=None, _subparts=None, encoding=None, **_params ): self.encoding = encoding MIMEMultipart.__init__(self, _subtype, boundary, _subparts, **_params) def __setitem__(self, name, val): name, val = forbid_multi_line_headers(name, val, self.encoding) MIMEMultipart.__setitem__(self, name, val) EmailAlternative = namedtuple("EmailAlternative", ["content", "mimetype"]) EmailAttachment = namedtuple("EmailAttachment", ["filename", "content", "mimetype"]) class EmailMessage: """A container for email information.""" content_subtype = "plain" # Undocumented charset to use for text/* message bodies and attachments. # If None, defaults to settings.DEFAULT_CHARSET. encoding = None @deprecate_posargs( RemovedInDjango70Warning, [ "bcc", "connection", "attachments", "headers", "cc", "reply_to", ], ) def __init__( self, subject="", body="", from_email=None, to=None, *, bcc=None, connection=None, attachments=None, headers=None, cc=None, reply_to=None, ): """ Initialize a single email message (which can be sent to multiple recipients). """ if to: if isinstance(to, str): raise TypeError('"to" argument must be a list or tuple') self.to = list(to) else: self.to = [] if cc: if isinstance(cc, str): raise TypeError('"cc" argument must be a list or tuple') self.cc = list(cc) else: self.cc = [] if bcc: if isinstance(bcc, str): raise TypeError('"bcc" argument must be a list or tuple') self.bcc = list(bcc) else: self.bcc = [] if reply_to: if isinstance(reply_to, str): raise TypeError('"reply_to" argument must be a list or tuple') self.reply_to = list(reply_to) else: self.reply_to = [] self.from_email = from_email or settings.DEFAULT_FROM_EMAIL self.subject = subject self.body = body or "" self.attachments = [] if attachments: for attachment in attachments: if isinstance(attachment, email.message.MIMEPart): self.attach(attachment) elif isinstance(attachment, MIMEBase): # RemovedInDjango70Warning. self.attach(attachment) else: self.attach(*attachment) self.extra_headers = headers or {} self.connection = connection def get_connection(self, fail_silently=False): from django.core.mail import get_connection if not self.connection: self.connection = get_connection(fail_silently=fail_silently) return self.connection def message(self, *, policy=email.policy.default): msg = email.message.EmailMessage(policy=policy) self._add_bodies(msg) self._add_attachments(msg) msg["Subject"] = str(self.subject) msg["From"] = str(self.extra_headers.get("From", self.from_email)) self._set_list_header_if_not_empty(msg, "To", self.to) self._set_list_header_if_not_empty(msg, "Cc", self.cc) self._set_list_header_if_not_empty(msg, "Reply-To", self.reply_to) # Email header names are case-insensitive (RFC 2045), so we have to # accommodate that when doing comparisons. header_names = [key.lower() for key in self.extra_headers] if "date" not in header_names: if settings.EMAIL_USE_LOCALTIME: tz = get_current_timezone() else: tz = timezone.utc msg["Date"] = datetime.now(tz) if "message-id" not in header_names: # Use cached DNS_NAME for performance msg["Message-ID"] = make_msgid(domain=DNS_NAME) for name, value in self.extra_headers.items(): # Avoid headers handled above. if name.lower() not in {"from", "to", "cc", "reply-to"}: msg[name] = force_str(value, strings_only=True) self._idna_encode_address_header_domains(msg) return msg def recipients(self): """ Return a list of all recipients of the email (includes direct addressees as well as Cc and Bcc entries). """ return [email for email in (self.to + self.cc + self.bcc) if email] def send(self, fail_silently=False): """Send the email message.""" if not self.recipients(): # Don't bother creating the network connection if there's nobody to # send to. return 0 return self.get_connection(fail_silently).send_messages([self]) def attach(self, filename=None, content=None, mimetype=None): """ Attach a file with the given filename and content. The filename can be omitted and the mimetype is guessed, if not provided. If the first parameter is a MIMEBase subclass, insert it directly into the resulting message attachments. For a text/* mimetype (guessed or specified), when a bytes object is specified as content, decode it as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ if isinstance(filename, email.message.MIMEPart): if content is not None or mimetype is not None: raise ValueError( "content and mimetype must not be given when a MIMEPart " "instance is provided." ) self.attachments.append(filename) elif isinstance(filename, MIMEBase): warnings.warn( "MIMEBase attachments are deprecated." " Use an email.message.MIMEPart instead.", RemovedInDjango70Warning, ) if content is not None or mimetype is not None: raise ValueError( "content and mimetype must not be given when a MIMEBase " "instance is provided." ) self.attachments.append(filename) elif content is None: raise ValueError("content must be provided.") else: mimetype = ( mimetype or mimetypes.guess_type(filename)[0] or DEFAULT_ATTACHMENT_MIME_TYPE ) basetype, subtype = mimetype.split("/", 1) if basetype == "text": if isinstance(content, bytes): try: content = content.decode() except UnicodeDecodeError: # If mimetype suggests the file is text but it's # actually binary, read() raises a UnicodeDecodeError. mimetype = DEFAULT_ATTACHMENT_MIME_TYPE self.attachments.append(EmailAttachment(filename, content, mimetype)) def attach_file(self, path, mimetype=None): """ Attach a file from the filesystem. Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified and cannot be guessed. For a text/* mimetype (guessed or specified), decode the file's content as UTF-8. If that fails, set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content. """ path = Path(path) with path.open("rb") as file: content = file.read() self.attach(path.name, content, mimetype) def _add_bodies(self, msg): if self.body or not self.attachments: encoding = self.encoding or settings.DEFAULT_CHARSET body = force_str( self.body or "", encoding=encoding, errors="surrogateescape" ) msg.set_content(body, subtype=self.content_subtype, charset=encoding) def _add_attachments(self, msg): if self.attachments: if hasattr(self, "mixed_subtype"): # RemovedInDjango70Warning. raise AttributeError( "EmailMessage no longer supports the" " undocumented `mixed_subtype` attribute" ) msg.make_mixed() for attachment in self.attachments: if isinstance(attachment, email.message.MIMEPart): msg.attach(attachment) elif isinstance(attachment, MIMEBase): # RemovedInDjango70Warning. msg.attach(attachment) else: self._add_attachment(msg, *attachment) def _add_attachment(self, msg, filename, content, mimetype): encoding = self.encoding or settings.DEFAULT_CHARSET maintype, subtype = mimetype.split("/", 1) if maintype == "text" and isinstance(content, bytes): # This duplicates logic from EmailMessage.attach() to properly # handle EmailMessage.attachments not created through attach(). try: content = content.decode() except UnicodeDecodeError: mimetype = DEFAULT_ATTACHMENT_MIME_TYPE maintype, subtype = mimetype.split("/", 1) # See email.contentmanager.set_content() docs for the cases here. if maintype == "text": # For text/*, content must be str, and maintype cannot be provided. msg.add_attachment( content, subtype=subtype, filename=filename, charset=encoding ) elif maintype == "message": # For message/*, content must be email.message.EmailMessage (or # legacy email.message.Message), and maintype cannot be provided. if isinstance(content, EmailMessage): # Django EmailMessage. content = content.message(policy=msg.policy) elif not isinstance( content, (email.message.EmailMessage, email.message.Message) ): content = email.message_from_bytes( force_bytes(content), policy=msg.policy ) msg.add_attachment(content, subtype=subtype, filename=filename) else: # For all other types, content must be bytes-like, and both # maintype and subtype must be provided. if not isinstance(content, (bytes, bytearray, memoryview)): content = force_bytes(content) msg.add_attachment( content, maintype=maintype, subtype=subtype, filename=filename, ) def _set_list_header_if_not_empty(self, msg, header, values): """ Set msg's header, either from self.extra_headers, if present, or from the values argument if not empty. """ try: msg[header] = self.extra_headers[header] except KeyError: if values: msg[header] = ", ".join(str(v) for v in values) def _idna_encode_address_header_domains(self, msg): """ If msg.policy does not permit utf8 in headers, IDNA encode all non-ASCII domains in its address headers. """ # Avoids a problem where Python's email incorrectly converts non-ASCII # domains to RFC 2047 encoded-words: # https://github.com/python/cpython/issues/83938. # This applies to the domain only, not to the localpart (username). # There is no RFC that permits any 7-bit encoding for non-ASCII # characters before the '@'. if not getattr(msg.policy, "utf8", False): # Not using SMTPUTF8, so apply IDNA encoding in all address # headers. IDNA encoding does not alter domains that are already # ASCII. for field, value in msg.items(): if isinstance(value, AddressHeader) and any( not addr.domain.isascii() for addr in value.addresses ): msg.replace_header( field, [ Address( display_name=addr.display_name, username=addr.username, domain=punycode(addr.domain), ) for addr in value.addresses ], ) class EmailMultiAlternatives(EmailMessage): """ A version of EmailMessage that makes it easy to send multipart/alternative messages. For example, including text and HTML versions of the text is made easier. """ @deprecate_posargs( RemovedInDjango70Warning, [ "bcc", "connection", "attachments", "headers", "alternatives", "cc", "reply_to", ], ) def __init__( self, subject="", body="", from_email=None, to=None, *, bcc=None, connection=None, attachments=None, headers=None, alternatives=None, cc=None, reply_to=None, ): """ Initialize a single email message (which can be sent to multiple recipients). """ super().__init__( subject, body, from_email, to, bcc=bcc, connection=connection, attachments=attachments, headers=headers, cc=cc, reply_to=reply_to, ) self.alternatives = [ EmailAlternative(*alternative) for alternative in (alternatives or []) ] def attach_alternative(self, content, mimetype): """Attach an alternative content representation.""" if content is None or mimetype is None: raise ValueError("Both content and mimetype must be provided.") self.alternatives.append(EmailAlternative(content, mimetype)) def _add_bodies(self, msg): if self.body or not self.alternatives: super()._add_bodies(msg) if self.alternatives: if hasattr(self, "alternative_subtype"): # RemovedInDjango70Warning. raise AttributeError( "EmailMultiAlternatives no longer supports the" " undocumented `alternative_subtype` attribute" ) msg.make_alternative() encoding = self.encoding or settings.DEFAULT_CHARSET for alternative in self.alternatives: maintype, subtype = alternative.mimetype.split("/", 1) content = alternative.content if maintype == "text": if isinstance(content, bytes): content = content.decode() msg.add_alternative(content, subtype=subtype, charset=encoding) else: content = force_bytes(content, encoding=encoding, strings_only=True) msg.add_alternative(content, maintype=maintype, subtype=subtype) return msg def body_contains(self, text): """ Checks that ``text`` occurs in the email body and in all attached MIME type text/* alternatives. """ if text not in self.body: return False for content, mimetype in self.alternatives: if mimetype.startswith("text/") and text not in content: return False return True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/utils.py
django/core/mail/utils.py
""" Email message and email sending related helper functions. """ import socket from django.utils.encoding import punycode # Cache the hostname, but do it lazily: socket.getfqdn() can take a couple of # seconds, which slows down the restart of the server. class CachedDnsName: def __str__(self): return self.get_fqdn() def get_fqdn(self): if not hasattr(self, "_fqdn"): self._fqdn = punycode(socket.getfqdn()) return self._fqdn DNS_NAME = CachedDnsName()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/__init__.py
django/core/mail/__init__.py
""" Tools for sending email. """ import warnings from django.conf import settings from django.core.exceptions import ImproperlyConfigured # Imported for backwards compatibility and for the sake # of a cleaner namespace. These symbols used to be in # django/core/mail.py before the introduction of email # backends and the subsequent reorganization (See #10355) from django.core.mail.message import ( DEFAULT_ATTACHMENT_MIME_TYPE, EmailAlternative, EmailAttachment, EmailMessage, EmailMultiAlternatives, forbid_multi_line_headers, make_msgid, ) from django.core.mail.utils import DNS_NAME, CachedDnsName from django.utils.deprecation import RemovedInDjango70Warning, deprecate_posargs from django.utils.functional import Promise from django.utils.module_loading import import_string __all__ = [ "CachedDnsName", "DNS_NAME", "EmailMessage", "EmailMultiAlternatives", "DEFAULT_ATTACHMENT_MIME_TYPE", "make_msgid", "get_connection", "send_mail", "send_mass_mail", "mail_admins", "mail_managers", "EmailAlternative", "EmailAttachment", # RemovedInDjango70Warning: When the deprecation ends, remove the last # entries. "BadHeaderError", "SafeMIMEText", "SafeMIMEMultipart", "forbid_multi_line_headers", ] @deprecate_posargs(RemovedInDjango70Warning, ["fail_silently"]) def get_connection(backend=None, *, fail_silently=False, **kwds): """Load an email backend and return an instance of it. If backend is None (default), use settings.EMAIL_BACKEND. Both fail_silently and other keyword arguments are used in the constructor of the backend. """ klass = import_string(backend or settings.EMAIL_BACKEND) return klass(fail_silently=fail_silently, **kwds) @deprecate_posargs( RemovedInDjango70Warning, [ "fail_silently", "auth_user", "auth_password", "connection", "html_message", ], ) def send_mail( subject, message, from_email, recipient_list, *, fail_silently=False, auth_user=None, auth_password=None, connection=None, html_message=None, ): """ Easy wrapper for sending a single message to a recipient list. All members of the recipient list will see the other recipients in the 'To' field. If from_email is None, use the DEFAULT_FROM_EMAIL setting. If auth_user is None, use the EMAIL_HOST_USER setting. If auth_password is None, use the EMAIL_HOST_PASSWORD setting. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently, ) mail = EmailMultiAlternatives( subject, message, from_email, recipient_list, connection=connection ) if html_message: mail.attach_alternative(html_message, "text/html") return mail.send() @deprecate_posargs( RemovedInDjango70Warning, [ "fail_silently", "auth_user", "auth_password", "connection", ], ) def send_mass_mail( datatuple, *, fail_silently=False, auth_user=None, auth_password=None, connection=None, ): """ Given a datatuple of (subject, message, from_email, recipient_list), send each message to each recipient list. Return the number of emails sent. If from_email is None, use the DEFAULT_FROM_EMAIL setting. If auth_user and auth_password are set, use them to log in. If auth_user is None, use the EMAIL_HOST_USER setting. If auth_password is None, use the EMAIL_HOST_PASSWORD setting. Note: The API for this method is frozen. New code wanting to extend the functionality should use the EmailMessage class directly. """ connection = connection or get_connection( username=auth_user, password=auth_password, fail_silently=fail_silently, ) messages = [ EmailMessage(subject, message, sender, recipient, connection=connection) for subject, message, sender, recipient in datatuple ] return connection.send_messages(messages) def _send_server_message( *, setting_name, subject, message, html_message=None, fail_silently=False, connection=None, ): recipients = getattr(settings, setting_name) if not recipients: return # RemovedInDjango70Warning. if all(isinstance(a, (list, tuple)) and len(a) == 2 for a in recipients): warnings.warn( f"Using (name, address) pairs in the {setting_name} setting is deprecated." " Replace with a list of email address strings.", RemovedInDjango70Warning, stacklevel=2, ) recipients = [a[1] for a in recipients] if not isinstance(recipients, (list, tuple)) or not all( isinstance(address, (str, Promise)) for address in recipients ): raise ImproperlyConfigured( f"The {setting_name} setting must be a list of email address strings." ) mail = EmailMultiAlternatives( subject="%s%s" % (settings.EMAIL_SUBJECT_PREFIX, subject), body=message, from_email=settings.SERVER_EMAIL, to=recipients, connection=connection, ) if html_message: mail.attach_alternative(html_message, "text/html") mail.send(fail_silently=fail_silently) @deprecate_posargs( RemovedInDjango70Warning, ["fail_silently", "connection", "html_message"] ) def mail_admins( subject, message, *, fail_silently=False, connection=None, html_message=None ): """Send a message to the admins, as defined by the ADMINS setting.""" _send_server_message( setting_name="ADMINS", subject=subject, message=message, html_message=html_message, fail_silently=fail_silently, connection=connection, ) @deprecate_posargs( RemovedInDjango70Warning, ["fail_silently", "connection", "html_message"] ) def mail_managers( subject, message, *, fail_silently=False, connection=None, html_message=None ): """Send a message to the managers, as defined by the MANAGERS setting.""" _send_server_message( setting_name="MANAGERS", subject=subject, message=message, html_message=html_message, fail_silently=fail_silently, connection=connection, ) # RemovedInDjango70Warning. _deprecate_on_import = { "BadHeaderError": "BadHeaderError is deprecated. Replace with ValueError.", "SafeMIMEText": ( "SafeMIMEText is deprecated. The return value" " of EmailMessage.message() is an email.message.EmailMessage." ), "SafeMIMEMultipart": ( "SafeMIMEMultipart is deprecated. The return value" " of EmailMessage.message() is an email.message.EmailMessage." ), } # RemovedInDjango70Warning. def __getattr__(name): try: msg = _deprecate_on_import[name] except KeyError: raise AttributeError(f"module {__name__!r} has no attribute {name!r}") from None else: # Issue deprecation warnings at time of import. from django.core.mail import message warnings.warn(msg, category=RemovedInDjango70Warning) return getattr(message, name)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/dummy.py
django/core/mail/backends/dummy.py
""" Dummy email backend that does nothing. """ from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def send_messages(self, email_messages): return len(list(email_messages))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/locmem.py
django/core/mail/backends/locmem.py
""" Backend for test environment. """ import copy from django.core import mail from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): """ An email backend for use during test sessions. The test connection stores email messages in a dummy outbox, rather than sending them out on the wire. The dummy outbox is accessible through the outbox instance attribute. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if not hasattr(mail, "outbox"): mail.outbox = [] def send_messages(self, messages): """Redirect messages to the dummy outbox""" msg_count = 0 for message in messages: # .message() triggers header validation message.message() mail.outbox.append(copy.deepcopy(message)) msg_count += 1 return msg_count
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/console.py
django/core/mail/backends/console.py
""" Email backend that writes messages to console instead of sending them. """ import sys import threading from django.core.mail.backends.base import BaseEmailBackend class EmailBackend(BaseEmailBackend): def __init__(self, *args, **kwargs): self.stream = kwargs.pop("stream", sys.stdout) self._lock = threading.RLock() super().__init__(*args, **kwargs) def write_message(self, message): msg = message.message() msg_data = msg.as_bytes() charset = ( msg.get_charset().get_output_charset() if msg.get_charset() else "utf-8" ) msg_data = msg_data.decode(charset) self.stream.write("%s\n" % msg_data) self.stream.write("-" * 79) self.stream.write("\n") def send_messages(self, email_messages): """Write all messages to the stream in a thread-safe way.""" if not email_messages: return msg_count = 0 with self._lock: try: stream_created = self.open() for message in email_messages: self.write_message(message) self.stream.flush() # flush after each message msg_count += 1 if stream_created: self.close() except Exception: if not self.fail_silently: raise return msg_count
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/__init__.py
django/core/mail/backends/__init__.py
# Mail backends shipped with Django.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/filebased.py
django/core/mail/backends/filebased.py
"""Email backend that writes messages to a file.""" import datetime import os from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend class EmailBackend(ConsoleEmailBackend): def __init__(self, *args, file_path=None, **kwargs): self._fname = None if file_path is not None: self.file_path = file_path else: self.file_path = getattr(settings, "EMAIL_FILE_PATH", None) self.file_path = os.path.abspath(self.file_path) try: os.makedirs(self.file_path, exist_ok=True) except FileExistsError: raise ImproperlyConfigured( "Path for saving email messages exists, but is not a directory: %s" % self.file_path ) except OSError as err: raise ImproperlyConfigured( "Could not create directory for saving email messages: %s (%s)" % (self.file_path, err) ) # Make sure that self.file_path is writable. if not os.access(self.file_path, os.W_OK): raise ImproperlyConfigured( "Could not write to directory: %s" % self.file_path ) # Finally, call super(). # Since we're using the console-based backend as a base, # force the stream to be None, so we don't default to stdout kwargs["stream"] = None super().__init__(*args, **kwargs) def write_message(self, message): self.stream.write(message.message().as_bytes() + b"\n") self.stream.write(b"-" * 79) self.stream.write(b"\n") def _get_filename(self): """Return a unique file name.""" if self._fname is None: timestamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S") fname = "%s-%s.log" % (timestamp, abs(id(self))) self._fname = os.path.join(self.file_path, fname) return self._fname def open(self): if self.stream is None: self.stream = open(self._get_filename(), "ab") return True return False def close(self): try: if self.stream is not None: self.stream.close() finally: self.stream = None
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/smtp.py
django/core/mail/backends/smtp.py
"""SMTP email backend class.""" import email.policy import smtplib import ssl import threading from email.headerregistry import Address, AddressHeader from django.conf import settings from django.core.mail.backends.base import BaseEmailBackend from django.core.mail.utils import DNS_NAME from django.utils.encoding import force_str, punycode from django.utils.functional import cached_property class EmailBackend(BaseEmailBackend): """ A wrapper that manages the SMTP network connection. """ def __init__( self, host=None, port=None, username=None, password=None, use_tls=None, fail_silently=False, use_ssl=None, timeout=None, ssl_keyfile=None, ssl_certfile=None, **kwargs, ): super().__init__(fail_silently=fail_silently) self.host = host or settings.EMAIL_HOST self.port = port or settings.EMAIL_PORT self.username = settings.EMAIL_HOST_USER if username is None else username self.password = settings.EMAIL_HOST_PASSWORD if password is None else password self.use_tls = settings.EMAIL_USE_TLS if use_tls is None else use_tls self.use_ssl = settings.EMAIL_USE_SSL if use_ssl is None else use_ssl self.timeout = settings.EMAIL_TIMEOUT if timeout is None else timeout self.ssl_keyfile = ( settings.EMAIL_SSL_KEYFILE if ssl_keyfile is None else ssl_keyfile ) self.ssl_certfile = ( settings.EMAIL_SSL_CERTFILE if ssl_certfile is None else ssl_certfile ) if self.use_ssl and self.use_tls: raise ValueError( "EMAIL_USE_TLS/EMAIL_USE_SSL are mutually exclusive, so only set " "one of those settings to True." ) self.connection = None self._lock = threading.RLock() @property def connection_class(self): return smtplib.SMTP_SSL if self.use_ssl else smtplib.SMTP @cached_property def ssl_context(self): if self.ssl_certfile or self.ssl_keyfile: ssl_context = ssl.SSLContext(protocol=ssl.PROTOCOL_TLS_CLIENT) ssl_context.load_cert_chain(self.ssl_certfile, self.ssl_keyfile) return ssl_context else: return ssl.create_default_context() def open(self): """ Ensure an open connection to the email server. Return whether or not a new connection was required (True or False) or None if an exception passed silently. """ if self.connection: # Nothing to do if the connection is already open. return False # If local_hostname is not specified, socket.getfqdn() gets used. # For performance, we use the cached FQDN for local_hostname. connection_params = {"local_hostname": DNS_NAME.get_fqdn()} if self.timeout is not None: connection_params["timeout"] = self.timeout if self.use_ssl: connection_params["context"] = self.ssl_context try: self.connection = self.connection_class( self.host, self.port, **connection_params ) # TLS/SSL are mutually exclusive, so only attempt TLS over # non-secure connections. if not self.use_ssl and self.use_tls: self.connection.starttls(context=self.ssl_context) if self.username and self.password: self.connection.login(self.username, self.password) return True except OSError: if not self.fail_silently: raise def close(self): """Close the connection to the email server.""" if self.connection is None: return try: try: self.connection.quit() except (ssl.SSLError, smtplib.SMTPServerDisconnected): # This happens when calling quit() on a TLS connection # sometimes, or when the connection was already disconnected # by the server. self.connection.close() except smtplib.SMTPException: if self.fail_silently: return raise finally: self.connection = None def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ if not email_messages: return 0 with self._lock: new_conn_created = self.open() if not self.connection or new_conn_created is None: # We failed silently on open(). # Trying to send would be pointless. return 0 num_sent = 0 try: for message in email_messages: sent = self._send(message) if sent: num_sent += 1 finally: if new_conn_created: self.close() return num_sent def _send(self, email_message): """A helper method that does the actual sending.""" if not email_message.recipients(): return False from_email = self.prep_address(email_message.from_email) recipients = [self.prep_address(addr) for addr in email_message.recipients()] message = email_message.message(policy=email.policy.SMTP) try: self.connection.sendmail(from_email, recipients, message.as_bytes()) except smtplib.SMTPException: if not self.fail_silently: raise return False return True def prep_address(self, address, force_ascii=True): """ Return the addr-spec portion of an email address. Raises ValueError for invalid addresses, including CR/NL injection. If force_ascii is True, apply IDNA encoding to non-ASCII domains, and raise ValueError for non-ASCII local-parts (which can't be encoded). Otherwise, leave Unicode characters unencoded (e.g., for sending with SMTPUTF8). """ address = force_str(address) parsed = AddressHeader.value_parser(address) defects = set(str(defect) for defect in parsed.all_defects) # Django allows local mailboxes like "From: webmaster" (#15042). defects.discard("addr-spec local part with no domain") if not force_ascii: # Non-ASCII local-part is valid with SMTPUTF8. Remove once # https://github.com/python/cpython/issues/81074 is fixed. defects.discard("local-part contains non-ASCII characters)") if defects: raise ValueError(f"Invalid address {address!r}: {'; '.join(defects)}") mailboxes = parsed.all_mailboxes if len(mailboxes) != 1: raise ValueError(f"Invalid address {address!r}: must be a single address") mailbox = mailboxes[0] if force_ascii and mailbox.domain and not mailbox.domain.isascii(): # Re-compose an addr-spec with the IDNA encoded domain. domain = punycode(mailbox.domain) return str(Address(username=mailbox.local_part, domain=domain)) else: return mailbox.addr_spec
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/mail/backends/base.py
django/core/mail/backends/base.py
"""Base email backend class.""" class BaseEmailBackend: """ Base class for email backend implementations. Subclasses must at least overwrite send_messages(). open() and close() can be called indirectly by using a backend object as a context manager: with backend as connection: # do something with connection pass """ def __init__(self, fail_silently=False, **kwargs): self.fail_silently = fail_silently def open(self): """ Open a network connection. This method can be overwritten by backend implementations to open a network connection. It's up to the backend implementation to track the status of a network connection if it's needed by the backend. This method can be called by applications to force a single network connection to be used when sending mails. See the send_messages() method of the SMTP backend for a reference implementation. The default implementation does nothing. """ pass def close(self): """Close a network connection.""" pass def __enter__(self): try: self.open() except Exception: self.close() raise return self def __exit__(self, exc_type, exc_value, traceback): self.close() def send_messages(self, email_messages): """ Send one or more EmailMessage objects and return the number of email messages sent. """ raise NotImplementedError( "subclasses of BaseEmailBackend must override send_messages() method" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/utils.py
django/core/cache/utils.py
from hashlib import md5 TEMPLATE_FRAGMENT_KEY_TEMPLATE = "template.cache.%s.%s" def make_template_fragment_key(fragment_name, vary_on=None): hasher = md5(usedforsecurity=False) if vary_on is not None: for arg in vary_on: hasher.update(str(arg).encode()) hasher.update(b":") return TEMPLATE_FRAGMENT_KEY_TEMPLATE % (fragment_name, hasher.hexdigest())
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/__init__.py
django/core/cache/__init__.py
""" Caching framework. This package defines set of cache backends that all conform to a simple API. In a nutshell, a cache is a set of values -- which can be any object that may be pickled -- identified by string keys. For the complete API, see the abstract BaseCache class in django.core.cache.backends.base. Client code should use the `cache` variable defined here to access the default cache backend and look up non-default cache backends in the `caches` dict-like object. See docs/topics/cache.txt for information on the public API. """ from django.core import signals from django.core.cache.backends.base import ( BaseCache, CacheKeyWarning, InvalidCacheBackendError, InvalidCacheKey, ) from django.utils.connection import BaseConnectionHandler, ConnectionProxy from django.utils.module_loading import import_string __all__ = [ "cache", "caches", "DEFAULT_CACHE_ALIAS", "InvalidCacheBackendError", "CacheKeyWarning", "BaseCache", "InvalidCacheKey", ] DEFAULT_CACHE_ALIAS = "default" class CacheHandler(BaseConnectionHandler): settings_name = "CACHES" exception_class = InvalidCacheBackendError def create_connection(self, alias): params = self.settings[alias].copy() backend = params.pop("BACKEND") location = params.pop("LOCATION", "") try: backend_cls = import_string(backend) except ImportError as e: raise InvalidCacheBackendError( "Could not find backend '%s': %s" % (backend, e) ) from e return backend_cls(location, params) caches = CacheHandler() cache = ConnectionProxy(caches, DEFAULT_CACHE_ALIAS) def close_caches(**kwargs): # Some caches need to do a cleanup at the end of a request cycle. If not # implemented in a particular backend cache.close() is a no-op. caches.close_all() signals.request_finished.connect(close_caches)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/dummy.py
django/core/cache/backends/dummy.py
"Dummy cache backend" from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache class DummyCache(BaseCache): def __init__(self, host, *args, **kwargs): super().__init__(*args, **kwargs) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): self.make_and_validate_key(key, version=version) return True def get(self, key, default=None, version=None): self.make_and_validate_key(key, version=version) return default def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): self.make_and_validate_key(key, version=version) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): self.make_and_validate_key(key, version=version) return False def delete(self, key, version=None): self.make_and_validate_key(key, version=version) return False def has_key(self, key, version=None): self.make_and_validate_key(key, version=version) return False def clear(self): pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/db.py
django/core/cache/backends/db.py
"Database cache backend." import base64 import pickle from datetime import UTC, datetime from django.conf import settings from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.db import DatabaseError, connections, models, router, transaction from django.utils.timezone import now as tz_now class Options: """A class that will quack like a Django model _meta class. This allows cache operations to be controlled by the router """ def __init__(self, table): self.db_table = table self.app_label = "django_cache" self.model_name = "cacheentry" self.verbose_name = "cache entry" self.verbose_name_plural = "cache entries" self.object_name = "CacheEntry" self.abstract = False self.managed = True self.proxy = False self.swapped = False class BaseDatabaseCache(BaseCache): def __init__(self, table, params): super().__init__(params) self._table = table class CacheEntry: _meta = Options(table) self.cache_model_class = CacheEntry class DatabaseCache(BaseDatabaseCache): # This class uses cursors provided by the database connection. This means # it reads expiration values as aware or naive datetimes, depending on the # value of USE_TZ and whether the database supports time zones. The ORM's # conversion and adaptation infrastructure is then used to avoid comparing # aware and naive datetimes accidentally. pickle_protocol = pickle.HIGHEST_PROTOCOL def get(self, key, default=None, version=None): return self.get_many([key], version).get(key, default) def get_many(self, keys, version=None): if not keys: return {} key_map = { self.make_and_validate_key(key, version=version): key for key in keys } db = router.db_for_read(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name table = quote_name(self._table) with connection.cursor() as cursor: cursor.execute( "SELECT %s, %s, %s FROM %s WHERE %s IN (%s)" % ( quote_name("cache_key"), quote_name("value"), quote_name("expires"), table, quote_name("cache_key"), ", ".join(["%s"] * len(key_map)), ), list(key_map), ) rows = cursor.fetchall() result = {} expired_keys = [] expression = models.Expression(output_field=models.DateTimeField()) converters = connection.ops.get_db_converters( expression ) + expression.get_db_converters(connection) for key, value, expires in rows: for converter in converters: expires = converter(expires, expression, connection) if expires < tz_now(): expired_keys.append(key) else: value = connection.ops.process_clob(value) value = pickle.loads(base64.b64decode(value.encode())) result[key_map.get(key)] = value self._base_delete_many(expired_keys) return result def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) self._base_set("set", key, value, timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._base_set("add", key, value, timeout) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._base_set("touch", key, None, timeout) def _base_set(self, mode, key, value, timeout=DEFAULT_TIMEOUT): timeout = self.get_backend_timeout(timeout) db = router.db_for_write(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name table = quote_name(self._table) with connection.cursor() as cursor: cursor.execute("SELECT COUNT(*) FROM %s" % table) num = cursor.fetchone()[0] now = tz_now() now = now.replace(microsecond=0) if timeout is None: exp = datetime.max else: tz = UTC if settings.USE_TZ else None exp = datetime.fromtimestamp(timeout, tz=tz) exp = exp.replace(microsecond=0) if num > self._max_entries: self._cull(db, cursor, now, num) pickled = pickle.dumps(value, self.pickle_protocol) # The DB column is expecting a string, so make sure the value is a # string, not bytes. Refs #19274. b64encoded = base64.b64encode(pickled).decode("latin1") try: # Note: typecasting for datetimes is needed by some 3rd party # database backends. All core backends work without # typecasting, so be careful about changes here - test suite # will NOT pick regressions. with transaction.atomic(using=db): cursor.execute( "SELECT %s, %s FROM %s WHERE %s = %%s" % ( quote_name("cache_key"), quote_name("expires"), table, quote_name("cache_key"), ), [key], ) result = cursor.fetchone() if result: current_expires = result[1] expression = models.Expression( output_field=models.DateTimeField() ) for converter in connection.ops.get_db_converters( expression ) + expression.get_db_converters(connection): current_expires = converter( current_expires, expression, connection ) exp = connection.ops.adapt_datetimefield_value(exp) if result and mode == "touch": cursor.execute( "UPDATE %s SET %s = %%s WHERE %s = %%s" % (table, quote_name("expires"), quote_name("cache_key")), [exp, key], ) elif result and ( mode == "set" or (mode == "add" and current_expires < now) ): cursor.execute( "UPDATE %s SET %s = %%s, %s = %%s WHERE %s = %%s" % ( table, quote_name("value"), quote_name("expires"), quote_name("cache_key"), ), [b64encoded, exp, key], ) elif mode != "touch": cursor.execute( "INSERT INTO %s (%s, %s, %s) VALUES (%%s, %%s, %%s)" % ( table, quote_name("cache_key"), quote_name("value"), quote_name("expires"), ), [key, b64encoded, exp], ) else: return False # touch failed. except DatabaseError: # To be threadsafe, updates/inserts are allowed to fail # silently return False else: return True def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) return self._base_delete_many([key]) def delete_many(self, keys, version=None): keys = [self.make_and_validate_key(key, version=version) for key in keys] self._base_delete_many(keys) def _base_delete_many(self, keys): if not keys: return False db = router.db_for_write(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name table = quote_name(self._table) with connection.cursor() as cursor: cursor.execute( "DELETE FROM %s WHERE %s IN (%s)" % ( table, quote_name("cache_key"), ", ".join(["%s"] * len(keys)), ), keys, ) return bool(cursor.rowcount) def has_key(self, key, version=None): key = self.make_and_validate_key(key, version=version) db = router.db_for_read(self.cache_model_class) connection = connections[db] quote_name = connection.ops.quote_name now = tz_now().replace(microsecond=0, tzinfo=None) with connection.cursor() as cursor: cursor.execute( "SELECT %s FROM %s WHERE %s = %%s and %s > %%s" % ( quote_name("cache_key"), quote_name(self._table), quote_name("cache_key"), quote_name("expires"), ), [key, connection.ops.adapt_datetimefield_value(now)], ) return cursor.fetchone() is not None def _cull(self, db, cursor, now, num): if self._cull_frequency == 0: self.clear() else: connection = connections[db] table = connection.ops.quote_name(self._table) cursor.execute( "DELETE FROM %s WHERE %s < %%s" % ( table, connection.ops.quote_name("expires"), ), [connection.ops.adapt_datetimefield_value(now)], ) deleted_count = cursor.rowcount remaining_num = num - deleted_count if remaining_num > self._max_entries: cull_num = remaining_num // self._cull_frequency cursor.execute( connection.ops.cache_key_culling_sql() % table, [cull_num] ) last_cache_key = cursor.fetchone() if last_cache_key: cursor.execute( "DELETE FROM %s WHERE %s < %%s" % ( table, connection.ops.quote_name("cache_key"), ), [last_cache_key[0]], ) def clear(self): db = router.db_for_write(self.cache_model_class) connection = connections[db] table = connection.ops.quote_name(self._table) with connection.cursor() as cursor: cursor.execute("DELETE FROM %s" % table)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/locmem.py
django/core/cache/backends/locmem.py
"Thread-safe in-memory cache backend." import pickle import time from collections import OrderedDict from threading import Lock from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache # Global in-memory store of cache data. Keyed by name, to provide # multiple named local memory caches. _caches = {} _expire_info = {} _locks = {} class LocMemCache(BaseCache): pickle_protocol = pickle.HIGHEST_PROTOCOL def __init__(self, name, params): super().__init__(params) self._cache = _caches.setdefault(name, OrderedDict()) self._expire_info = _expire_info.setdefault(name, {}) self._lock = _locks.setdefault(name, Lock()) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) pickled = pickle.dumps(value, self.pickle_protocol) with self._lock: if self._has_expired(key): self._set(key, pickled, timeout) return True return False def get(self, key, default=None, version=None): key = self.make_and_validate_key(key, version=version) with self._lock: if self._has_expired(key): self._delete(key) return default pickled = self._cache[key] self._cache.move_to_end(key, last=False) return pickle.loads(pickled) def _set(self, key, value, timeout=DEFAULT_TIMEOUT): if len(self._cache) >= self._max_entries: self._cull() self._cache[key] = value self._cache.move_to_end(key, last=False) self._expire_info[key] = self.get_backend_timeout(timeout) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) pickled = pickle.dumps(value, self.pickle_protocol) with self._lock: self._set(key, pickled, timeout) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) with self._lock: if self._has_expired(key): return False self._expire_info[key] = self.get_backend_timeout(timeout) return True def incr(self, key, delta=1, version=None): key = self.make_and_validate_key(key, version=version) with self._lock: if self._has_expired(key): self._delete(key) raise ValueError("Key '%s' not found" % key) pickled = self._cache[key] value = pickle.loads(pickled) new_value = value + delta pickled = pickle.dumps(new_value, self.pickle_protocol) self._cache[key] = pickled self._cache.move_to_end(key, last=False) return new_value def has_key(self, key, version=None): key = self.make_and_validate_key(key, version=version) with self._lock: if self._has_expired(key): self._delete(key) return False return True def _has_expired(self, key): exp = self._expire_info.get(key, -1) return exp is not None and exp <= time.time() def _cull(self): if self._cull_frequency == 0: self._cache.clear() self._expire_info.clear() else: count = len(self._cache) // self._cull_frequency for i in range(count): key, _ = self._cache.popitem() del self._expire_info[key] def _delete(self, key): try: del self._cache[key] del self._expire_info[key] except KeyError: return False return True def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) with self._lock: return self._delete(key) def clear(self): with self._lock: self._cache.clear() self._expire_info.clear()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/redis.py
django/core/cache/backends/redis.py
"""Redis cache backend.""" import pickle import random import re from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.utils.functional import cached_property from django.utils.module_loading import import_string class RedisSerializer: def __init__(self, protocol=None): self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol def dumps(self, obj): # For better incr() and decr() atomicity, don't pickle integers. # Using type() rather than isinstance() matches only integers and not # subclasses like bool. if type(obj) is int: return obj return pickle.dumps(obj, self.protocol) def loads(self, data): try: return int(data) except ValueError: return pickle.loads(data) class RedisCacheClient: def __init__( self, servers, serializer=None, pool_class=None, parser_class=None, **options, ): import redis self._lib = redis self._servers = servers self._pools = {} self._client = self._lib.Redis if isinstance(pool_class, str): pool_class = import_string(pool_class) self._pool_class = pool_class or self._lib.ConnectionPool if isinstance(serializer, str): serializer = import_string(serializer) if callable(serializer): serializer = serializer() self._serializer = serializer or RedisSerializer() if isinstance(parser_class, str): parser_class = import_string(parser_class) parser_class = parser_class or self._lib.connection.DefaultParser self._pool_options = {"parser_class": parser_class, **options} def _get_connection_pool_index(self, write): # Write to the first server. Read from other servers if there are more, # otherwise read from the first server. if write or len(self._servers) == 1: return 0 return random.randint(1, len(self._servers) - 1) def _get_connection_pool(self, write): index = self._get_connection_pool_index(write) if index not in self._pools: self._pools[index] = self._pool_class.from_url( self._servers[index], **self._pool_options, ) return self._pools[index] def get_client(self, key=None, *, write=False): # key is used so that the method signature remains the same and custom # cache client can be implemented which might require the key to select # the server, e.g. sharding. pool = self._get_connection_pool(write) return self._client(connection_pool=pool) def add(self, key, value, timeout): client = self.get_client(key, write=True) value = self._serializer.dumps(value) if timeout == 0: if ret := bool(client.set(key, value, nx=True)): client.delete(key) return ret else: return bool(client.set(key, value, ex=timeout, nx=True)) def get(self, key, default): client = self.get_client(key) value = client.get(key) return default if value is None else self._serializer.loads(value) def set(self, key, value, timeout): client = self.get_client(key, write=True) value = self._serializer.dumps(value) if timeout == 0: client.delete(key) else: client.set(key, value, ex=timeout) def touch(self, key, timeout): client = self.get_client(key, write=True) if timeout is None: return bool(client.persist(key)) else: return bool(client.expire(key, timeout)) def delete(self, key): client = self.get_client(key, write=True) return bool(client.delete(key)) def get_many(self, keys): client = self.get_client(None) ret = client.mget(keys) return { k: self._serializer.loads(v) for k, v in zip(keys, ret) if v is not None } def has_key(self, key): client = self.get_client(key) return bool(client.exists(key)) def incr(self, key, delta): client = self.get_client(key, write=True) if not client.exists(key): raise ValueError("Key '%s' not found." % key) return client.incr(key, delta) def set_many(self, data, timeout): client = self.get_client(None, write=True) pipeline = client.pipeline() pipeline.mset({k: self._serializer.dumps(v) for k, v in data.items()}) if timeout is not None: # Setting timeout for each key as redis does not support timeout # with mset(). for key in data: pipeline.expire(key, timeout) pipeline.execute() def delete_many(self, keys): client = self.get_client(None, write=True) client.delete(*keys) def clear(self): client = self.get_client(None, write=True) return bool(client.flushdb()) class RedisCache(BaseCache): def __init__(self, server, params): super().__init__(params) if isinstance(server, str): self._servers = re.split("[;,]", server) else: self._servers = server self._class = RedisCacheClient self._options = params.get("OPTIONS", {}) @cached_property def _cache(self): return self._class(self._servers, **self._options) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout # The key will be made persistent if None used as a timeout. # Non-positive values will cause the key to be deleted. return None if timeout is None else max(0, int(timeout)) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.get(key, default) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) self._cache.set(key, value, self.get_backend_timeout(timeout)) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.touch(key, self.get_backend_timeout(timeout)) def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.delete(key) def get_many(self, keys, version=None): key_map = { self.make_and_validate_key(key, version=version): key for key in keys } ret = self._cache.get_many(key_map.keys()) return {key_map[k]: v for k, v in ret.items()} def has_key(self, key, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.has_key(key) def incr(self, key, delta=1, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.incr(key, delta) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): if not data: return [] safe_data = {} for key, value in data.items(): key = self.make_and_validate_key(key, version=version) safe_data[key] = value self._cache.set_many(safe_data, self.get_backend_timeout(timeout)) return [] def delete_many(self, keys, version=None): if not keys: return safe_keys = [self.make_and_validate_key(key, version=version) for key in keys] self._cache.delete_many(safe_keys) def clear(self): return self._cache.clear()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/memcached.py
django/core/cache/backends/memcached.py
"Memcached cache backend" import re import time from django.core.cache.backends.base import ( DEFAULT_TIMEOUT, BaseCache, InvalidCacheKey, memcache_key_warnings, ) from django.utils.functional import cached_property class BaseMemcachedCache(BaseCache): def __init__(self, server, params, library, value_not_found_exception): super().__init__(params) if isinstance(server, str): self._servers = re.split("[;,]", server) else: self._servers = server # Exception type raised by the underlying client library for a # nonexistent key. self.LibraryValueNotFoundException = value_not_found_exception self._lib = library self._class = library.Client self._options = params.get("OPTIONS") or {} @property def client_servers(self): return self._servers @cached_property def _cache(self): """ Implement transparent thread-safe access to a memcached client. """ return self._class(self.client_servers, **self._options) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Memcached deals with long (> 30 days) timeouts in a special way. Call this function to obtain a safe value for your timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout if timeout is None: # Using 0 in memcache sets a non-expiring timeout. return 0 elif int(timeout) == 0: # Other cache backends treat 0 as set-and-expire. To achieve this # in memcache backends, a negative timeout must be passed. timeout = -1 if timeout > 2592000: # 60*60*24*30, 30 days # See: # https://github.com/memcached/memcached/wiki/Programming#expiration # "Expiration times can be set from 0, meaning "never expire", to # 30 days. Any time higher than 30 days is interpreted as a Unix # timestamp date. If you want to expire an object on January 1st of # next year, this is how you do that." # # This means that we have to switch to absolute timestamps. timeout += int(time.time()) return int(timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.add(key, value, self.get_backend_timeout(timeout)) def get(self, key, default=None, version=None): key = self.make_and_validate_key(key, version=version) return self._cache.get(key, default) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) if not self._cache.set(key, value, self.get_backend_timeout(timeout)): # Make sure the key doesn't keep its old value in case of failure # to set (memcached's 1MB limit). self._cache.delete(key) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) return bool(self._cache.touch(key, self.get_backend_timeout(timeout))) def delete(self, key, version=None): key = self.make_and_validate_key(key, version=version) return bool(self._cache.delete(key)) def get_many(self, keys, version=None): key_map = { self.make_and_validate_key(key, version=version): key for key in keys } ret = self._cache.get_multi(key_map.keys()) return {key_map[k]: v for k, v in ret.items()} def close(self, **kwargs): # Many clients don't clean up connections properly. self._cache.disconnect_all() def incr(self, key, delta=1, version=None): key = self.make_and_validate_key(key, version=version) try: # Memcached doesn't support negative delta. if delta < 0: val = self._cache.decr(key, -delta) else: val = self._cache.incr(key, delta) # Normalize an exception raised by the underlying client library to # ValueError in the event of a nonexistent key when calling # incr()/decr(). except self.LibraryValueNotFoundException: val = None if val is None: raise ValueError("Key '%s' not found" % key) return val def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): safe_data = {} original_keys = {} for key, value in data.items(): safe_key = self.make_and_validate_key(key, version=version) safe_data[safe_key] = value original_keys[safe_key] = key failed_keys = self._cache.set_multi( safe_data, self.get_backend_timeout(timeout) ) return [original_keys[k] for k in failed_keys] def delete_many(self, keys, version=None): keys = [self.make_and_validate_key(key, version=version) for key in keys] self._cache.delete_multi(keys) def clear(self): self._cache.flush_all() def validate_key(self, key): for warning in memcache_key_warnings(key): raise InvalidCacheKey(warning) class PyLibMCCache(BaseMemcachedCache): "An implementation of a cache binding using pylibmc" def __init__(self, server, params): import pylibmc super().__init__( server, params, library=pylibmc, value_not_found_exception=pylibmc.NotFound ) @property def client_servers(self): output = [] for server in self._servers: output.append(server.removeprefix("unix:")) return output def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): key = self.make_and_validate_key(key, version=version) if timeout == 0: return self._cache.delete(key) return self._cache.touch(key, self.get_backend_timeout(timeout)) def close(self, **kwargs): # libmemcached manages its own connections. Don't call disconnect_all() # as it resets the failover state and creates unnecessary reconnects. pass class PyMemcacheCache(BaseMemcachedCache): """An implementation of a cache binding using pymemcache.""" def __init__(self, server, params): import pymemcache.serde super().__init__( server, params, library=pymemcache, value_not_found_exception=KeyError ) self._class = self._lib.HashClient self._options = { "allow_unicode_keys": True, "default_noreply": False, "serde": pymemcache.serde.pickle_serde, **self._options, }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/__init__.py
django/core/cache/backends/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/filebased.py
django/core/cache/backends/filebased.py
"File-based cache backend" import glob import os import pickle import random import tempfile import time import zlib from hashlib import md5 from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache from django.core.files import locks from django.core.files.move import file_move_safe class FileBasedCache(BaseCache): cache_suffix = ".djcache" pickle_protocol = pickle.HIGHEST_PROTOCOL def __init__(self, dir, params): super().__init__(params) self._dir = os.path.abspath(dir) self._createdir() def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): if self.has_key(key, version): return False self.set(key, value, timeout, version) return True def get(self, key, default=None, version=None): fname = self._key_to_file(key, version) try: with open(fname, "rb") as f: if not self._is_expired(f): return pickle.loads(zlib.decompress(f.read())) except FileNotFoundError: pass return default def _write_content(self, file, timeout, value): expiry = self.get_backend_timeout(timeout) file.write(pickle.dumps(expiry, self.pickle_protocol)) file.write(zlib.compress(pickle.dumps(value, self.pickle_protocol))) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): self._createdir() # Cache dir can be deleted at any time. fname = self._key_to_file(key, version) self._cull() # make some room if necessary fd, tmp_path = tempfile.mkstemp(dir=self._dir) renamed = False try: with open(fd, "wb") as f: self._write_content(f, timeout, value) file_move_safe(tmp_path, fname, allow_overwrite=True) renamed = True finally: if not renamed: os.remove(tmp_path) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): try: with open(self._key_to_file(key, version), "r+b") as f: try: locks.lock(f, locks.LOCK_EX) if self._is_expired(f): return False else: previous_value = pickle.loads(zlib.decompress(f.read())) f.seek(0) self._write_content(f, timeout, previous_value) return True finally: locks.unlock(f) except FileNotFoundError: return False def delete(self, key, version=None): return self._delete(self._key_to_file(key, version)) def _delete(self, fname): if not fname.startswith(self._dir) or not os.path.exists(fname): return False try: os.remove(fname) except FileNotFoundError: # The file may have been removed by another process. return False return True def has_key(self, key, version=None): fname = self._key_to_file(key, version) try: with open(fname, "rb") as f: return not self._is_expired(f) except FileNotFoundError: return False def _cull(self): """ Remove random cache entries if max_entries is reached at a ratio of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means that the entire cache will be purged. """ filelist = self._list_cache_files() num_entries = len(filelist) if num_entries < self._max_entries: return # return early if no culling is required if self._cull_frequency == 0: return self.clear() # Clear the cache when CULL_FREQUENCY = 0 # Delete a random selection of entries filelist = random.sample(filelist, int(num_entries / self._cull_frequency)) for fname in filelist: self._delete(fname) def _createdir(self): # Set the umask because os.makedirs() doesn't apply the "mode" argument # to intermediate-level directories. old_umask = os.umask(0o077) try: os.makedirs(self._dir, 0o700, exist_ok=True) finally: os.umask(old_umask) def _key_to_file(self, key, version=None): """ Convert a key into a cache file path. Basically this is the root cache path joined with the md5sum of the key and a suffix. """ key = self.make_and_validate_key(key, version=version) return os.path.join( self._dir, "".join( [ md5(key.encode(), usedforsecurity=False).hexdigest(), self.cache_suffix, ] ), ) def clear(self): """ Remove all the cache files. """ for fname in self._list_cache_files(): self._delete(fname) def _is_expired(self, f): """ Take an open cache file `f` and delete it if it's expired. """ try: exp = pickle.load(f) except EOFError: exp = 0 # An empty file is considered expired. if exp is not None and exp < time.time(): f.close() # On Windows a file has to be closed before deleting self._delete(f.name) return True return False def _list_cache_files(self): """ Get a list of paths to all the cache files. These are all the files in the root cache dir that end on the cache_suffix. """ return [ os.path.join(self._dir, fname) for fname in glob.glob(f"*{self.cache_suffix}", root_dir=self._dir) ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/cache/backends/base.py
django/core/cache/backends/base.py
"Base Cache class." import time import warnings from asgiref.sync import sync_to_async from django.core.exceptions import ImproperlyConfigured from django.utils.module_loading import import_string from django.utils.regex_helper import _lazy_re_compile class InvalidCacheBackendError(ImproperlyConfigured): pass class CacheKeyWarning(RuntimeWarning): pass class InvalidCacheKey(ValueError): pass # Stub class to ensure not passing in a `timeout` argument results in # the default timeout DEFAULT_TIMEOUT = object() # Memcached does not accept keys longer than this. MEMCACHE_MAX_KEY_LENGTH = 250 def default_key_func(key, key_prefix, version): """ Default function to generate keys. Construct the key used by all other methods. By default, prepend the `key_prefix`. KEY_FUNCTION can be used to specify an alternate function with custom key making behavior. """ return "%s:%s:%s" % (key_prefix, version, key) def get_key_func(key_func): """ Function to decide which key function to use. Default to ``default_key_func``. """ if key_func is not None: if callable(key_func): return key_func else: return import_string(key_func) return default_key_func class BaseCache: _missing_key = object() def __init__(self, params): timeout = params.get("timeout", params.get("TIMEOUT", 300)) if timeout is not None: try: timeout = int(timeout) except (ValueError, TypeError): timeout = 300 self.default_timeout = timeout options = params.get("OPTIONS", {}) max_entries = params.get("max_entries", options.get("MAX_ENTRIES", 300)) try: self._max_entries = int(max_entries) except (ValueError, TypeError): self._max_entries = 300 cull_frequency = params.get("cull_frequency", options.get("CULL_FREQUENCY", 3)) try: self._cull_frequency = int(cull_frequency) except (ValueError, TypeError): self._cull_frequency = 3 self.key_prefix = params.get("KEY_PREFIX", "") self.version = params.get("VERSION", 1) self.key_func = get_key_func(params.get("KEY_FUNCTION")) def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT): """ Return the timeout value usable by this backend based upon the provided timeout. """ if timeout == DEFAULT_TIMEOUT: timeout = self.default_timeout elif timeout == 0: # ticket 21147 - avoid time.time() related precision issues timeout = -1 return None if timeout is None else time.time() + timeout def make_key(self, key, version=None): """ Construct the key used by all other methods. By default, use the key_func to generate a key (which, by default, prepends the `key_prefix' and 'version'). A different key function can be provided at the time of cache construction; alternatively, you can subclass the cache backend to provide custom key making behavior. """ if version is None: version = self.version return self.key_func(key, self.key_prefix, version) def validate_key(self, key): """ Warn about keys that would not be portable to the memcached backend. This encourages (but does not force) writing backend-portable cache code. """ for warning in memcache_key_warnings(key): warnings.warn(warning, CacheKeyWarning) def make_and_validate_key(self, key, version=None): """Helper to make and validate keys.""" key = self.make_key(key, version=version) self.validate_key(key) return key def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache if the key does not already exist. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return True if the value was stored, False otherwise. """ raise NotImplementedError( "subclasses of BaseCache must provide an add() method" ) async def aadd(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): return await sync_to_async(self.add, thread_sensitive=True)( key, value, timeout, version ) def get(self, key, default=None, version=None): """ Fetch a given key from the cache. If the key does not exist, return default, which itself defaults to None. """ raise NotImplementedError("subclasses of BaseCache must provide a get() method") async def aget(self, key, default=None, version=None): return await sync_to_async(self.get, thread_sensitive=True)( key, default, version ) def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): """ Set a value in the cache. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. """ raise NotImplementedError("subclasses of BaseCache must provide a set() method") async def aset(self, key, value, timeout=DEFAULT_TIMEOUT, version=None): return await sync_to_async(self.set, thread_sensitive=True)( key, value, timeout, version ) def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None): """ Update the key's expiry time using timeout. Return True if successful or False if the key does not exist. """ raise NotImplementedError( "subclasses of BaseCache must provide a touch() method" ) async def atouch(self, key, timeout=DEFAULT_TIMEOUT, version=None): return await sync_to_async(self.touch, thread_sensitive=True)( key, timeout, version ) def delete(self, key, version=None): """ Delete a key from the cache and return whether it succeeded, failing silently. """ raise NotImplementedError( "subclasses of BaseCache must provide a delete() method" ) async def adelete(self, key, version=None): return await sync_to_async(self.delete, thread_sensitive=True)(key, version) def get_many(self, keys, version=None): """ Fetch a bunch of keys from the cache. For certain backends (memcached, pgsql) this can be *much* faster when fetching multiple values. Return a dict mapping each key in keys to its value. If the given key is missing, it will be missing from the response dict. """ d = {} for k in keys: val = self.get(k, self._missing_key, version=version) if val is not self._missing_key: d[k] = val return d async def aget_many(self, keys, version=None): """See get_many().""" if self.get_many.__func__ is not BaseCache.get_many: return await sync_to_async(self.get_many, thread_sensitive=True)( keys, version=version ) d = {} for k in keys: val = await self.aget(k, self._missing_key, version=version) if val is not self._missing_key: d[k] = val return d def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): """ Fetch a given key from the cache. If the key does not exist, add the key and set it to the default value. The default value can also be any callable. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. Return the value of the key stored or retrieved. """ val = self.get(key, self._missing_key, version=version) if val is self._missing_key: if callable(default): default = default() self.add(key, default, timeout=timeout, version=version) # Fetch the value again to avoid a race condition if another caller # added a value between the first get() and the add() above. return self.get(key, default, version=version) return val async def aget_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None): """See get_or_set().""" if self.get_or_set.__func__ is not BaseCache.get_or_set: return await sync_to_async(self.get_or_set, thread_sensitive=True)( key, default, timeout=timeout, version=version ) val = await self.aget(key, self._missing_key, version=version) if val is self._missing_key: if callable(default): default = default() await self.aadd(key, default, timeout=timeout, version=version) # Fetch the value again to avoid a race condition if another caller # added a value between the first aget() and the aadd() above. return await self.aget(key, default, version=version) return val def has_key(self, key, version=None): """ Return True if the key is in the cache and has not expired. """ return ( self.get(key, self._missing_key, version=version) is not self._missing_key ) async def ahas_key(self, key, version=None): if self.has_key.__func__ is not BaseCache.has_key: return await sync_to_async(self.has_key, thread_sensitive=True)( key, version=version ) return ( await self.aget(key, self._missing_key, version=version) is not self._missing_key ) def incr(self, key, delta=1, version=None): """ Add delta to value in the cache. If the key does not exist, raise a ValueError exception. """ value = self.get(key, self._missing_key, version=version) if value is self._missing_key: raise ValueError("Key '%s' not found" % key) new_value = value + delta self.set(key, new_value, version=version) return new_value async def aincr(self, key, delta=1, version=None): """See incr().""" if self.incr.__func__ is not BaseCache.incr: return await sync_to_async(self.incr, thread_sensitive=True)( key, delta=delta, version=version ) value = await self.aget(key, self._missing_key, version=version) if value is self._missing_key: raise ValueError("Key '%s' not found" % key) new_value = value + delta await self.aset(key, new_value, version=version) return new_value def decr(self, key, delta=1, version=None): """ Subtract delta from value in the cache. If the key does not exist, raise a ValueError exception. """ return self.incr(key, -delta, version=version) async def adecr(self, key, delta=1, version=None): return await self.aincr(key, -delta, version=version) def __contains__(self, key): """ Return True if the key is in the cache and has not expired. """ # This is a separate method, rather than just a copy of has_key(), # so that it always has the same functionality as has_key(), even # if a subclass overrides it. return self.has_key(key) def set_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): """ Set a bunch of values in the cache at once from a dict of key/value pairs. For certain backends (memcached), this is much more efficient than calling set() multiple times. If timeout is given, use that timeout for the key; otherwise use the default cache timeout. On backends that support it, return a list of keys that failed insertion, or an empty list if all keys were inserted successfully. """ for key, value in data.items(): self.set(key, value, timeout=timeout, version=version) return [] async def aset_many(self, data, timeout=DEFAULT_TIMEOUT, version=None): if self.set_many.__func__ is not BaseCache.set_many: return await sync_to_async(self.set_many, thread_sensitive=True)( data, timeout=timeout, version=version ) for key, value in data.items(): await self.aset(key, value, timeout=timeout, version=version) return [] def delete_many(self, keys, version=None): """ Delete a bunch of values in the cache at once. For certain backends (memcached), this is much more efficient than calling delete() multiple times. """ for key in keys: self.delete(key, version=version) async def adelete_many(self, keys, version=None): if self.delete_many.__func__ is not BaseCache.delete_many: return await sync_to_async(self.delete_many, thread_sensitive=True)( keys, version=version ) for key in keys: await self.adelete(key, version=version) def clear(self): """Remove *all* values from the cache at once.""" raise NotImplementedError( "subclasses of BaseCache must provide a clear() method" ) async def aclear(self): return await sync_to_async(self.clear, thread_sensitive=True)() def incr_version(self, key, delta=1, version=None): """ Add delta to the cache version for the supplied key. Return the new version. """ if version is None: version = self.version value = self.get(key, self._missing_key, version=version) if value is self._missing_key: raise ValueError("Key '%s' not found" % key) self.set(key, value, version=version + delta) self.delete(key, version=version) return version + delta async def aincr_version(self, key, delta=1, version=None): """See incr_version().""" if self.incr_version.__func__ is not BaseCache.incr_version: return await sync_to_async(self.incr_version, thread_sensitive=True)( key, delta=delta, version=version ) if version is None: version = self.version value = await self.aget(key, self._missing_key, version=version) if value is self._missing_key: raise ValueError("Key '%s' not found" % key) await self.aset(key, value, version=version + delta) await self.adelete(key, version=version) return version + delta def decr_version(self, key, delta=1, version=None): """ Subtract delta from the cache version for the supplied key. Return the new version. """ return self.incr_version(key, -delta, version) async def adecr_version(self, key, delta=1, version=None): return await self.aincr_version(key, -delta, version) def close(self, **kwargs): """Close the cache connection""" pass async def aclose(self, **kwargs): return await sync_to_async(self.close, thread_sensitive=True)(**kwargs) memcached_error_chars_re = _lazy_re_compile(r"[\x00-\x20\x7f]") def memcache_key_warnings(key): if len(key) > MEMCACHE_MAX_KEY_LENGTH: yield ( "Cache key will cause errors if used with memcached: %r " "(longer than %s)" % (key, MEMCACHE_MAX_KEY_LENGTH) ) if memcached_error_chars_re.search(key): yield ( "Cache key contains characters that will cause errors if used with " f"memcached: {key!r}" )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/utils.py
django/core/files/utils.py
import os import pathlib from django.core.exceptions import SuspiciousFileOperation def validate_file_name(name, allow_relative_path=False): # Remove potentially dangerous names if os.path.basename(name) in {"", ".", ".."}: raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) if allow_relative_path: # Ensure that name can be treated as a pure posix path, i.e. Unix # style (with forward slashes). path = pathlib.PurePosixPath(str(name).replace("\\", "/")) if path.is_absolute() or ".." in path.parts: raise SuspiciousFileOperation( "Detected path traversal attempt in '%s'" % name ) elif name != os.path.basename(name): raise SuspiciousFileOperation("File name '%s' includes path elements" % name) return name class FileProxyMixin: """ A mixin class used to forward file methods to an underlying file object. The internal file object has to be called "file":: class FileProxy(FileProxyMixin): def __init__(self, file): self.file = file """ encoding = property(lambda self: self.file.encoding) fileno = property(lambda self: self.file.fileno) flush = property(lambda self: self.file.flush) isatty = property(lambda self: self.file.isatty) newlines = property(lambda self: self.file.newlines) read = property(lambda self: self.file.read) readinto = property(lambda self: self.file.readinto) readline = property(lambda self: self.file.readline) readlines = property(lambda self: self.file.readlines) seek = property(lambda self: self.file.seek) tell = property(lambda self: self.file.tell) truncate = property(lambda self: self.file.truncate) write = property(lambda self: self.file.write) writelines = property(lambda self: self.file.writelines) @property def closed(self): return not self.file or self.file.closed def readable(self): if self.closed: return False if hasattr(self.file, "readable"): return self.file.readable() return True def writable(self): if self.closed: return False if hasattr(self.file, "writable"): return self.file.writable() return "w" in getattr(self.file, "mode", "") def seekable(self): if self.closed: return False if hasattr(self.file, "seekable"): return self.file.seekable() return True def __iter__(self): return iter(self.file)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/move.py
django/core/files/move.py
""" Move a file in the safest way possible:: >>> from django.core.files.move import file_move_safe >>> file_move_safe("/tmp/old_file", "/tmp/new_file") """ import os from shutil import copymode, copystat from django.core.files import locks __all__ = ["file_move_safe"] def file_move_safe( old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False ): """ Move a file from one location to another in the safest way possible. First, try ``os.rename``, which is simple but will break across filesystems. If that fails, stream manually from one file to another in pure Python. If the destination file exists and ``allow_overwrite`` is ``False``, raise ``FileExistsError``. """ # There's no reason to move if we don't have to. try: if os.path.samefile(old_file_name, new_file_name): return except OSError: pass if not allow_overwrite and os.access(new_file_name, os.F_OK): raise FileExistsError( f"Destination file {new_file_name} exists and allow_overwrite is False." ) try: os.rename(old_file_name, new_file_name) return except OSError: # OSError happens with os.rename() if moving to another filesystem or # when moving opened files on certain operating systems. pass # first open the old file, so that it won't go away with open(old_file_name, "rb") as old_file: # now open the new file, not forgetting allow_overwrite fd = os.open( new_file_name, ( os.O_WRONLY | os.O_CREAT | getattr(os, "O_BINARY", 0) | (os.O_EXCL if not allow_overwrite else 0) | os.O_TRUNC ), ) try: locks.lock(fd, locks.LOCK_EX) current_chunk = None while current_chunk != b"": current_chunk = old_file.read(chunk_size) os.write(fd, current_chunk) finally: locks.unlock(fd) os.close(fd) try: copystat(old_file_name, new_file_name) except PermissionError: # Certain filesystems (e.g. CIFS) fail to copy the file's metadata if # the type of the destination filesystem isn't the same as the source # filesystem. This also happens with some SELinux-enabled systems. # Ignore that, but try to set basic permissions. try: copymode(old_file_name, new_file_name) except PermissionError: pass try: os.remove(old_file_name) except PermissionError as e: # Certain operating systems (Cygwin and Windows) # fail when deleting opened files, ignore it. (For the # systems where this happens, temporary files will be auto-deleted # on close anyway.) if getattr(e, "winerror", 0) != 32: raise
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/__init__.py
django/core/files/__init__.py
from django.core.files.base import File __all__ = ["File"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/images.py
django/core/files/images.py
""" Utility functions for handling images. Requires Pillow as you might imagine. """ import struct import zlib from django.core.files import File class ImageFile(File): """ A mixin for use alongside django.core.files.base.File, which provides additional features for dealing with images. """ @property def width(self): return self._get_image_dimensions()[0] @property def height(self): return self._get_image_dimensions()[1] def _get_image_dimensions(self): if not hasattr(self, "_dimensions_cache"): close = self.closed self.open() self._dimensions_cache = get_image_dimensions(self, close=close) return self._dimensions_cache def get_image_dimensions(file_or_path, close=False): """ Return the (width, height) of an image, given an open file or a path. Set 'close' to True to close the file at the end if it is initially in an open state. """ from PIL import ImageFile as PillowImageFile p = PillowImageFile.Parser() if hasattr(file_or_path, "read"): file = file_or_path file_pos = file.tell() file.seek(0) else: try: file = open(file_or_path, "rb") except OSError: return (None, None) close = True try: # Most of the time Pillow only needs a small chunk to parse the image # and get the dimensions, but with some TIFF files Pillow needs to # parse the whole file. chunk_size = 1024 while 1: data = file.read(chunk_size) if not data: break try: p.feed(data) except zlib.error as e: # ignore zlib complaining on truncated stream, just feed more # data to parser (ticket #19457). if e.args[0].startswith("Error -5"): pass else: raise except struct.error: # Ignore PIL failing on a too short buffer when reads return # less bytes than expected. Skip and feed more data to the # parser (ticket #24544). pass except RuntimeError: # e.g. "RuntimeError: could not create decoder object" for # WebP files. A different chunk_size may work. pass if p.image: return p.image.size chunk_size *= 2 return (None, None) finally: if close: file.close() else: file.seek(file_pos)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/locks.py
django/core/files/locks.py
""" Portable file locking utilities. Based partially on an example by Jonathan Feignberg in the Python Cookbook [1] (licensed under the Python Software License) and a ctypes port by Anatoly Techtonik for Roundup [2] (license [3]). [1] https://code.activestate.com/recipes/65203/ [2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py # NOQA [3] https://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt Example Usage:: >>> from django.core.files import locks >>> with open('./file', 'wb') as f: ... locks.lock(f, locks.LOCK_EX) ... f.write('Django') """ import os __all__ = ("LOCK_EX", "LOCK_SH", "LOCK_NB", "lock", "unlock") def _fd(f): """Get a filedescriptor from something which could be a file or an fd.""" return f.fileno() if hasattr(f, "fileno") else f if os.name == "nt": import msvcrt from ctypes import ( POINTER, Structure, Union, WinDLL, byref, c_int64, c_ulong, c_void_p, sizeof, ) from ctypes.wintypes import BOOL, DWORD, HANDLE LOCK_SH = 0 # the default LOCK_NB = 0x1 # LOCKFILE_FAIL_IMMEDIATELY LOCK_EX = 0x2 # LOCKFILE_EXCLUSIVE_LOCK # --- Adapted from the pyserial project --- # detect size of ULONG_PTR if sizeof(c_ulong) != sizeof(c_void_p): ULONG_PTR = c_int64 else: ULONG_PTR = c_ulong PVOID = c_void_p # --- Union inside Structure by stackoverflow:3480240 --- class _OFFSET(Structure): _fields_ = [("Offset", DWORD), ("OffsetHigh", DWORD)] class _OFFSET_UNION(Union): _anonymous_ = ["_offset"] _fields_ = [("_offset", _OFFSET), ("Pointer", PVOID)] class OVERLAPPED(Structure): _anonymous_ = ["_offset_union"] _fields_ = [ ("Internal", ULONG_PTR), ("InternalHigh", ULONG_PTR), ("_offset_union", _OFFSET_UNION), ("hEvent", HANDLE), ] LPOVERLAPPED = POINTER(OVERLAPPED) # --- Define function prototypes for extra safety --- kernel32 = WinDLL("kernel32") LockFileEx = kernel32.LockFileEx LockFileEx.restype = BOOL LockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, DWORD, LPOVERLAPPED] UnlockFileEx = kernel32.UnlockFileEx UnlockFileEx.restype = BOOL UnlockFileEx.argtypes = [HANDLE, DWORD, DWORD, DWORD, LPOVERLAPPED] def lock(f, flags): hfile = msvcrt.get_osfhandle(_fd(f)) overlapped = OVERLAPPED() ret = LockFileEx(hfile, flags, 0, 0, 0xFFFF0000, byref(overlapped)) return bool(ret) def unlock(f): hfile = msvcrt.get_osfhandle(_fd(f)) overlapped = OVERLAPPED() ret = UnlockFileEx(hfile, 0, 0, 0xFFFF0000, byref(overlapped)) return bool(ret) else: try: import fcntl LOCK_SH = fcntl.LOCK_SH # shared lock LOCK_NB = fcntl.LOCK_NB # non-blocking LOCK_EX = fcntl.LOCK_EX except (ImportError, AttributeError): # File locking is not supported. LOCK_EX = LOCK_SH = LOCK_NB = 0 # Dummy functions that don't do anything. def lock(f, flags): # File is not locked return False def unlock(f): # File is unlocked return True else: def lock(f, flags): try: fcntl.flock(_fd(f), flags) return True except BlockingIOError: return False def unlock(f): fcntl.flock(_fd(f), fcntl.LOCK_UN) return True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/base.py
django/core/files/base.py
import os from io import BytesIO, StringIO, UnsupportedOperation from django.core.files.utils import FileProxyMixin from django.utils.functional import cached_property class File(FileProxyMixin): DEFAULT_CHUNK_SIZE = 64 * 2**10 def __init__(self, file, name=None): self.file = file if name is None: name = getattr(file, "name", None) self.name = name if hasattr(file, "mode"): self.mode = file.mode def __str__(self): return self.name or "" def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self or "None") def __bool__(self): return bool(self.name) def __len__(self): return self.size @cached_property def size(self): if hasattr(self.file, "size"): return self.file.size if hasattr(self.file, "name"): try: return os.path.getsize(self.file.name) except (OSError, TypeError): pass if hasattr(self.file, "tell") and hasattr(self.file, "seek"): pos = self.file.tell() self.file.seek(0, os.SEEK_END) size = self.file.tell() self.file.seek(pos) return size raise AttributeError("Unable to determine the file's size.") def chunks(self, chunk_size=None): """ Read the file and yield chunks of ``chunk_size`` bytes (defaults to ``File.DEFAULT_CHUNK_SIZE``). """ chunk_size = chunk_size or self.DEFAULT_CHUNK_SIZE try: self.seek(0) except (AttributeError, UnsupportedOperation): pass while True: data = self.read(chunk_size) if not data: break yield data def multiple_chunks(self, chunk_size=None): """ Return ``True`` if you can expect multiple chunks. NB: If a particular file representation is in memory, subclasses should always return ``False`` -- there's no good reason to read from memory in chunks. """ return self.size > (chunk_size or self.DEFAULT_CHUNK_SIZE) def __iter__(self): # Iterate over this file-like object by newlines buffer_ = [] for chunk in self.chunks(): for line in chunk.splitlines(True): if buffer_: if endswith_cr(buffer_[-1]) and not equals_lf(line): # Line split after a \r newline; yield buffer_. yield type(buffer_[0])().join(buffer_) # Continue with line. buffer_ = [] else: # Line either split without a newline (line # continues after buffer_) or with \r\n # newline (line == b'\n'). buffer_.append(line) if not buffer_: # If this is the end of a \n or \r\n line, yield. if endswith_lf(line): yield line else: buffer_.append(line) elif endswith_lf(line): yield type(buffer_[0])().join(buffer_) buffer_ = [] if buffer_: yield type(buffer_[0])().join(buffer_) def __enter__(self): return self def __exit__(self, exc_type, exc_value, tb): self.close() def open(self, mode=None, *args, **kwargs): if not self.closed: self.seek(0) elif self.name and os.path.exists(self.name): self.file = open(self.name, mode or self.mode, *args, **kwargs) else: raise ValueError("The file cannot be reopened.") return self def close(self): self.file.close() class ContentFile(File): """ A File-like object that takes just raw content, rather than an actual file. """ def __init__(self, content, name=None): stream_class = StringIO if isinstance(content, str) else BytesIO super().__init__(stream_class(content), name=name) self.size = len(content) def __str__(self): return "Raw content" def __bool__(self): return True def open(self, mode=None): self.seek(0) return self def close(self): pass def write(self, data): self.__dict__.pop("size", None) # Clear the computed size. return self.file.write(data) def endswith_cr(line): """Return True if line (a text or bytestring) ends with '\r'.""" return line.endswith("\r" if isinstance(line, str) else b"\r") def endswith_lf(line): """Return True if line (a text or bytestring) ends with '\n'.""" return line.endswith("\n" if isinstance(line, str) else b"\n") def equals_lf(line): """Return True if line (a text or bytestring) equals '\n'.""" return line == ("\n" if isinstance(line, str) else b"\n")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/uploadhandler.py
django/core/files/uploadhandler.py
""" Base file upload handler classes, and the built-in concrete subclasses """ import os from io import BytesIO from django.conf import settings from django.core.files.uploadedfile import InMemoryUploadedFile, TemporaryUploadedFile from django.utils.module_loading import import_string __all__ = [ "UploadFileException", "StopUpload", "SkipFile", "FileUploadHandler", "TemporaryFileUploadHandler", "MemoryFileUploadHandler", "load_handler", "StopFutureHandlers", ] class UploadFileException(Exception): """ Any error having to do with uploading files. """ pass class StopUpload(UploadFileException): """ This exception is raised when an upload must abort. """ def __init__(self, connection_reset=False): """ If ``connection_reset`` is ``True``, Django knows will halt the upload without consuming the rest of the upload. This will cause the browser to show a "connection reset" error. """ self.connection_reset = connection_reset def __str__(self): if self.connection_reset: return "StopUpload: Halt current upload." else: return "StopUpload: Consume request data, then halt." class SkipFile(UploadFileException): """ This exception is raised by an upload handler that wants to skip a given file. """ pass class StopFutureHandlers(UploadFileException): """ Upload handlers that have handled a file and do not want future handlers to run should raise this exception instead of returning None. """ pass class FileUploadHandler: """ Base class for streaming upload handlers. """ chunk_size = 64 * 2**10 # : The default chunk size is 64 KB. def __init__(self, request=None): self.file_name = None self.content_type = None self.content_length = None self.charset = None self.content_type_extra = None self.request = request def handle_raw_input( self, input_data, META, content_length, boundary, encoding=None ): """ Handle the raw input from the client. Parameters: :input_data: An object that supports reading via .read(). :META: ``request.META``. :content_length: The (integer) value of the Content-Length header from the client. :boundary: The boundary from the Content-Type header. Be sure to prepend two '--'. """ pass def new_file( self, field_name, file_name, content_type, content_length, charset=None, content_type_extra=None, ): """ Signal that a new file has been started. Warning: As with any data from the client, you should not trust content_length (and sometimes won't even get it). """ self.field_name = field_name self.file_name = file_name self.content_type = content_type self.content_length = content_length self.charset = charset self.content_type_extra = content_type_extra def receive_data_chunk(self, raw_data, start): """ Receive data from the streamed upload parser. ``start`` is the position in the file of the chunk. """ raise NotImplementedError( "subclasses of FileUploadHandler must provide a receive_data_chunk() method" ) def file_complete(self, file_size): """ Signal that a file has completed. File size corresponds to the actual size accumulated by all the chunks. Subclasses should return a valid ``UploadedFile`` object. """ raise NotImplementedError( "subclasses of FileUploadHandler must provide a file_complete() method" ) def upload_complete(self): """ Signal that the upload is complete. Subclasses should perform cleanup that is necessary for this handler. """ pass def upload_interrupted(self): """ Signal that the upload was interrupted. Subclasses should perform cleanup that is necessary for this handler. """ pass class TemporaryFileUploadHandler(FileUploadHandler): """ Upload handler that streams data into a temporary file. """ def new_file(self, *args, **kwargs): """ Create the file object to append to as data is coming in. """ super().new_file(*args, **kwargs) self.file = TemporaryUploadedFile( self.file_name, self.content_type, 0, self.charset, self.content_type_extra ) def receive_data_chunk(self, raw_data, start): self.file.write(raw_data) def file_complete(self, file_size): self.file.seek(0) self.file.size = file_size return self.file def upload_interrupted(self): if hasattr(self, "file"): temp_location = self.file.temporary_file_path() try: self.file.close() os.remove(temp_location) except FileNotFoundError: pass class MemoryFileUploadHandler(FileUploadHandler): """ File upload handler to stream uploads into memory (used for small files). """ def handle_raw_input( self, input_data, META, content_length, boundary, encoding=None ): """ Use the content_length to signal whether or not this handler should be used. """ # Check the content-length header to see if we should # If the post is too large, we cannot use the Memory handler. self.activated = content_length <= settings.FILE_UPLOAD_MAX_MEMORY_SIZE def new_file(self, *args, **kwargs): super().new_file(*args, **kwargs) if self.activated: self.file = BytesIO() raise StopFutureHandlers() def receive_data_chunk(self, raw_data, start): """Add the data to the BytesIO file.""" if self.activated: self.file.write(raw_data) else: return raw_data def file_complete(self, file_size): """Return a file object if this handler is activated.""" if not self.activated: return self.file.seek(0) return InMemoryUploadedFile( file=self.file, field_name=self.field_name, name=self.file_name, content_type=self.content_type, size=file_size, charset=self.charset, content_type_extra=self.content_type_extra, ) def load_handler(path, *args, **kwargs): """ Given a path to a handler, return an instance of that handler. E.g.:: >>> from django.http import HttpRequest >>> request = HttpRequest() >>> load_handler( ... 'django.core.files.uploadhandler.TemporaryFileUploadHandler', ... request, ... ) <TemporaryFileUploadHandler object at 0x...> """ return import_string(path)(*args, **kwargs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/core/files/temp.py
django/core/files/temp.py
""" The temp module provides a NamedTemporaryFile that can be reopened in the same process on any platform. Most platforms use the standard Python tempfile.NamedTemporaryFile class, but Windows users are given a custom class. This is needed because the Python implementation of NamedTemporaryFile uses the O_TEMPORARY flag under Windows, which prevents the file from being reopened if the same flag is not provided [1][2]. Note that this does not address the more general issue of opening a file for writing and reading in multiple processes in a manner that works across platforms. The custom version of NamedTemporaryFile doesn't support the same keyword arguments available in tempfile.NamedTemporaryFile. 1: https://mail.python.org/pipermail/python-list/2005-December/336955.html 2: https://bugs.python.org/issue14243 """ import os import tempfile from django.core.files.utils import FileProxyMixin __all__ = ( "NamedTemporaryFile", "gettempdir", ) if os.name == "nt": class TemporaryFile(FileProxyMixin): """ Temporary file object constructor that supports reopening of the temporary file in Windows. Unlike tempfile.NamedTemporaryFile from the standard library, __init__() doesn't support the 'delete', 'buffering', 'encoding', or 'newline' keyword arguments. """ def __init__(self, mode="w+b", bufsize=-1, suffix="", prefix="", dir=None): fd, name = tempfile.mkstemp(suffix=suffix, prefix=prefix, dir=dir) self.name = name self.file = os.fdopen(fd, mode, bufsize) self.close_called = False # Because close can be called during shutdown # we need to cache os.unlink and access it # as self.unlink only unlink = os.unlink def close(self): if not self.close_called: self.close_called = True try: self.file.close() except OSError: pass try: self.unlink(self.name) except OSError: pass def __del__(self): self.close() def __enter__(self): self.file.__enter__() return self def __exit__(self, exc, value, tb): self.file.__exit__(exc, value, tb) NamedTemporaryFile = TemporaryFile else: NamedTemporaryFile = tempfile.NamedTemporaryFile gettempdir = tempfile.gettempdir
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false