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/db/backends/sqlite3/schema.py
django/db/backends/sqlite3/schema.py
import copy from decimal import Decimal from django.apps.registry import Apps from django.db import NotSupportedError from django.db.backends.base.schema import BaseDatabaseSchemaEditor from django.db.backends.ddl_references import Statement from django.db.backends.utils import strip_quotes from django.db.models import CompositePrimaryKey, UniqueConstraint class DatabaseSchemaEditor(BaseDatabaseSchemaEditor): sql_delete_table = "DROP TABLE %(table)s" sql_create_fk = None sql_create_inline_fk = ( "REFERENCES %(to_table)s (%(to_column)s)%(on_delete_db)s DEFERRABLE INITIALLY " "DEFERRED" ) sql_create_column_inline_fk = sql_create_inline_fk sql_create_unique = "CREATE UNIQUE INDEX %(name)s ON %(table)s (%(columns)s)" sql_delete_unique = "DROP INDEX %(name)s" sql_alter_table_comment = None sql_alter_column_comment = None def __enter__(self): # Some SQLite schema alterations need foreign key constraints to be # disabled. Enforce it here for the duration of the schema edition. if not self.connection.disable_constraint_checking(): raise NotSupportedError( "SQLite schema editor cannot be used while foreign key " "constraint checks are enabled. Make sure to disable them " "before entering a transaction.atomic() context because " "SQLite does not support disabling them in the middle of " "a multi-statement transaction." ) return super().__enter__() def __exit__(self, exc_type, exc_value, traceback): self.connection.check_constraints() super().__exit__(exc_type, exc_value, traceback) self.connection.enable_constraint_checking() def quote_value(self, value): # The backend "mostly works" without this function and there are use # cases for compiling Python without the sqlite3 libraries (e.g. # security hardening). try: import sqlite3 value = sqlite3.adapt(value) except ImportError: pass except sqlite3.ProgrammingError: pass # Manual emulation of SQLite parameter quoting if isinstance(value, bool): return str(int(value)) elif isinstance(value, (Decimal, float, int)): return str(value) elif isinstance(value, str): return "'%s'" % value.replace("'", "''") elif value is None: return "NULL" elif isinstance(value, (bytes, bytearray, memoryview)): # Bytes are only allowed for BLOB fields, encoded as string # literals containing hexadecimal data and preceded by a single "X" # character. return "X'%s'" % value.hex() else: raise ValueError( "Cannot quote parameter value %r of type %s" % (value, type(value)) ) def prepare_default(self, value): return self.quote_value(value) def _remake_table( self, model, create_field=None, delete_field=None, alter_fields=None ): """ Shortcut to transform a model from old_model into new_model This follows the correct procedure to perform non-rename or column addition operations based on SQLite's documentation https://www.sqlite.org/lang_altertable.html#caution The essential steps are: 1. Create a table with the updated definition called "new__app_model" 2. Copy the data from the existing "app_model" table to the new table 3. Drop the "app_model" table 4. Rename the "new__app_model" table to "app_model" 5. Restore any index of the previous "app_model" table. """ # Self-referential fields must be recreated rather than copied from # the old model to ensure their remote_field.field_name doesn't refer # to an altered field. def is_self_referential(f): return f.is_relation and f.remote_field.model is model # Work out the new fields dict / mapping body = { f.name: f.clone() if is_self_referential(f) else f for f in model._meta.local_concrete_fields } # Since CompositePrimaryKey is not a concrete field (column is None), # it's not copied by default. pk = model._meta.pk if isinstance(pk, CompositePrimaryKey): body[pk.name] = pk.clone() # Since mapping might mix column names and default values, # its values must be already quoted. mapping = { f.column: self.quote_name(f.column) for f in model._meta.local_concrete_fields if f.generated is False } # This maps field names (not columns) for things like unique_together rename_mapping = {} # If any of the new or altered fields is introducing a new PK, # remove the old one restore_pk_field = None alter_fields = alter_fields or [] if getattr(create_field, "primary_key", False) or any( getattr(new_field, "primary_key", False) for _, new_field in alter_fields ): for name, field in list(body.items()): if field.primary_key and not any( # Do not remove the old primary key when an altered field # that introduces a primary key is the same field. name == new_field.name for _, new_field in alter_fields ): field.primary_key = False restore_pk_field = field if field.auto_created: del body[name] del mapping[field.column] # Add in any created fields if create_field: body[create_field.name] = create_field # Choose a default and insert it into the copy map if ( not create_field.has_db_default() and not create_field.generated and create_field.concrete ): mapping[create_field.column] = self.prepare_default( self.effective_default(create_field) ) # Add in any altered fields for alter_field in alter_fields: old_field, new_field = alter_field body.pop(old_field.name, None) mapping.pop(old_field.column, None) body[new_field.name] = new_field rename_mapping[old_field.name] = new_field.name if new_field.generated: continue if old_field.null and not new_field.null: if not new_field.has_db_default(): default = self.prepare_default(self.effective_default(new_field)) else: default, _ = self.db_default_sql(new_field) case_sql = "coalesce(%(col)s, %(default)s)" % { "col": self.quote_name(old_field.column), "default": default, } mapping[new_field.column] = case_sql else: mapping[new_field.column] = self.quote_name(old_field.column) # Remove any deleted fields if delete_field: del body[delete_field.name] mapping.pop(delete_field.column, None) # Remove any implicit M2M tables if ( delete_field.many_to_many and delete_field.remote_field.through._meta.auto_created ): return self.delete_model(delete_field.remote_field.through) # Work inside a new app registry apps = Apps() # Work out the new value of unique_together, taking renames into # account unique_together = [ [rename_mapping.get(n, n) for n in unique] for unique in model._meta.unique_together ] indexes = model._meta.indexes if delete_field: indexes = [ index for index in indexes if delete_field.name not in index.fields ] constraints = list(model._meta.constraints) # Provide isolated instances of the fields to the new model body so # that the existing model's internals aren't interfered with when # the dummy model is constructed. body_copy = copy.deepcopy(body) # Construct a new model with the new fields to allow self referential # primary key to resolve to. This model won't ever be materialized as a # table and solely exists for foreign key reference resolution # purposes. This wouldn't be required if the schema editor was # operating on model states instead of rendered models. meta_contents = { "app_label": model._meta.app_label, "db_table": model._meta.db_table, "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ type(model._meta.object_name, model.__bases__, body_copy) # Construct a model with a renamed table name. body_copy = copy.deepcopy(body) meta_contents = { "app_label": model._meta.app_label, "db_table": "new__%s" % strip_quotes(model._meta.db_table), "unique_together": unique_together, "indexes": indexes, "constraints": constraints, "apps": apps, } meta = type("Meta", (), meta_contents) body_copy["Meta"] = meta body_copy["__module__"] = model.__module__ new_model = type("New%s" % model._meta.object_name, model.__bases__, body_copy) # Remove the automatically recreated default primary key, if it has # been deleted. if delete_field and delete_field.attname == new_model._meta.pk.attname: auto_pk = new_model._meta.pk delattr(new_model, auto_pk.attname) new_model._meta.local_fields.remove(auto_pk) new_model.pk = None # Create a new table with the updated schema. self.create_model(new_model) # Copy data from the old table into the new table self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_model._meta.db_table), ", ".join(self.quote_name(x) for x in mapping), ", ".join(mapping.values()), self.quote_name(model._meta.db_table), ) ) # Delete the old table to make way for the new self.delete_model(model, handle_autom2m=False) # Rename the new table to take way for the old self.alter_db_table( new_model, new_model._meta.db_table, model._meta.db_table, ) # Run deferred SQL on correct table for sql in self.deferred_sql: self.execute(sql) self.deferred_sql = [] # Fix any PK-removed field if restore_pk_field: restore_pk_field.primary_key = True def delete_model(self, model, handle_autom2m=True): if handle_autom2m: super().delete_model(model) else: # Delete the table (and only that) self.execute( self.sql_delete_table % { "table": self.quote_name(model._meta.db_table), } ) # Remove all deferred statements referencing the deleted table. for sql in list(self.deferred_sql): if isinstance(sql, Statement) and sql.references_table( model._meta.db_table ): self.deferred_sql.remove(sql) def add_field(self, model, field): """Create a field on a model.""" from django.db.models.expressions import Value # Special-case implicit M2M tables. if field.many_to_many and field.remote_field.through._meta.auto_created: self.create_model(field.remote_field.through) elif isinstance(field, CompositePrimaryKey): # If a CompositePrimaryKey field was added, the existing primary # key field had to be altered too, resulting in an AddField, # AlterField migration. The table cannot be re-created on AddField, # it would result in a duplicate primary key error. return elif ( # Primary keys and unique fields are not supported in ALTER TABLE # ADD COLUMN. field.primary_key or field.unique or not field.null # Fields with default values cannot by handled by ALTER TABLE ADD # COLUMN statement because DROP DEFAULT is not supported in # ALTER TABLE. or self.effective_default(field) is not None # Fields with non-constant defaults cannot by handled by ALTER # TABLE ADD COLUMN statement. or (field.has_db_default() and not isinstance(field.db_default, Value)) ): self._remake_table(model, create_field=field) else: super().add_field(model, field) def remove_field(self, model, field): """ Remove a field from a model. Usually involves deleting a column, but for M2Ms may involve deleting a table. """ # M2M fields are a special case if field.many_to_many: # For implicit M2M tables, delete the auto-created table if field.remote_field.through._meta.auto_created: self.delete_model(field.remote_field.through) # For explicit "through" M2M fields, do nothing elif ( # Primary keys, unique fields, indexed fields, and foreign keys are # not supported in ALTER TABLE DROP COLUMN. not field.primary_key and not field.unique and not field.db_index and not (field.remote_field and field.db_constraint) ): super().remove_field(model, field) # For everything else, remake. else: # It might not actually have a column behind it if field.db_parameters(connection=self.connection)["type"] is None: return self._remake_table(model, delete_field=field) def _alter_field( self, model, old_field, new_field, old_type, new_type, old_db_params, new_db_params, strict=False, ): """Perform a "physical" (non-ManyToMany) field update.""" # Use "ALTER TABLE ... RENAME COLUMN" if only the column name # changed and there aren't any constraints. if ( old_field.column != new_field.column and self.column_sql(model, old_field) == self.column_sql(model, new_field) and not ( old_field.remote_field and old_field.db_constraint or new_field.remote_field and new_field.db_constraint ) ): return self.execute( self._rename_field_sql( model._meta.db_table, old_field, new_field, new_type ) ) # Alter by remaking table self._remake_table(model, alter_fields=[(old_field, new_field)]) # Rebuild tables with FKs pointing to this field. old_collation = old_db_params.get("collation") new_collation = new_db_params.get("collation") if new_field.unique and ( old_type != new_type or old_collation != new_collation ): related_models = set() opts = new_field.model._meta for remote_field in opts.related_objects: # Ignore self-relationship since the table was already rebuilt. if remote_field.related_model == model: continue if not remote_field.many_to_many: if remote_field.field_name == new_field.name: related_models.add(remote_field.related_model) elif new_field.primary_key and remote_field.through._meta.auto_created: related_models.add(remote_field.through) if new_field.primary_key: for many_to_many in opts.many_to_many: # Ignore self-relationship since the table was already # rebuilt. if many_to_many.related_model == model: continue if many_to_many.remote_field.through._meta.auto_created: related_models.add(many_to_many.remote_field.through) for related_model in related_models: self._remake_table(related_model) def _alter_many_to_many(self, model, old_field, new_field, strict): """Alter M2Ms to repoint their to= endpoints.""" if ( old_field.remote_field.through._meta.db_table == new_field.remote_field.through._meta.db_table ): # The field name didn't change, but some options did, so we have to # propagate this altering. self._remake_table( old_field.remote_field.through, alter_fields=[ ( # The field that points to the target model is needed, # so that table can be remade with the new m2m field - # this is m2m_reverse_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_reverse_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_reverse_field_name() ), ), ( # The field that points to the model itself is needed, # so that table can be remade with the new self field - # this is m2m_field_name(). old_field.remote_field.through._meta.get_field( old_field.m2m_field_name() ), new_field.remote_field.through._meta.get_field( new_field.m2m_field_name() ), ), ], ) return # Make a new through table self.create_model(new_field.remote_field.through) # Copy the data across self.execute( "INSERT INTO %s (%s) SELECT %s FROM %s" % ( self.quote_name(new_field.remote_field.through._meta.db_table), ", ".join( [ "id", new_field.m2m_column_name(), new_field.m2m_reverse_name(), ] ), ", ".join( [ "id", old_field.m2m_column_name(), old_field.m2m_reverse_name(), ] ), self.quote_name(old_field.remote_field.through._meta.db_table), ) ) # Delete the old through table self.delete_model(old_field.remote_field.through) def add_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().add_constraint(model, constraint) else: self._remake_table(model) def remove_constraint(self, model, constraint): if isinstance(constraint, UniqueConstraint) and ( constraint.condition or constraint.contains_expressions or constraint.include or constraint.deferrable ): super().remove_constraint(model, constraint) else: self._remake_table(model) def _collate_sql(self, collation): return "COLLATE " + collation
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/creation.py
django/db/backends/sqlite3/creation.py
import multiprocessing import os import shutil import sqlite3 import sys from pathlib import Path from django.db import NotSupportedError from django.db.backends.base.creation import BaseDatabaseCreation class DatabaseCreation(BaseDatabaseCreation): @staticmethod def is_in_memory_db(database_name): return not isinstance(database_name, Path) and ( database_name == ":memory:" or "mode=memory" in database_name ) def _get_test_db_name(self): test_database_name = self.connection.settings_dict["TEST"]["NAME"] or ":memory:" if test_database_name == ":memory:": return "file:memorydb_%s?mode=memory&cache=shared" % self.connection.alias return test_database_name def _create_test_db(self, verbosity, autoclobber, keepdb=False): test_database_name = self._get_test_db_name() if keepdb: return test_database_name if not self.is_in_memory_db(test_database_name): # Erase the old test database if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % (self._get_database_display_str(verbosity, test_database_name),) ) if os.access(test_database_name, os.F_OK): if not autoclobber: confirm = input( "Type 'yes' if you would like to try deleting the test " "database '%s', or 'no' to cancel: " % test_database_name ) if autoclobber or confirm == "yes": try: os.remove(test_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) else: self.log("Tests cancelled.") sys.exit(1) return test_database_name def get_test_db_clone_settings(self, suffix): orig_settings_dict = self.connection.settings_dict source_database_name = orig_settings_dict["NAME"] or ":memory:" if not self.is_in_memory_db(source_database_name): root, ext = os.path.splitext(source_database_name) return {**orig_settings_dict, "NAME": f"{root}_{suffix}{ext}"} start_method = multiprocessing.get_start_method() if start_method == "fork": return orig_settings_dict if start_method in {"forkserver", "spawn"}: return { **orig_settings_dict, "NAME": f"{self.connection.alias}_{suffix}.sqlite3", } raise NotSupportedError( f"Cloning with start method {start_method!r} is not supported." ) def _clone_test_db(self, suffix, verbosity, keepdb=False): source_database_name = self.connection.settings_dict["NAME"] target_database_name = self.get_test_db_clone_settings(suffix)["NAME"] if not self.is_in_memory_db(source_database_name): # Erase the old test database if os.access(target_database_name, os.F_OK): if keepdb: return if verbosity >= 1: self.log( "Destroying old test database for alias %s..." % ( self._get_database_display_str( verbosity, target_database_name ), ) ) try: os.remove(target_database_name) except Exception as e: self.log("Got an error deleting the old test database: %s" % e) sys.exit(2) try: shutil.copy(source_database_name, target_database_name) except Exception as e: self.log("Got an error cloning the test database: %s" % e) sys.exit(2) # Forking automatically makes a copy of an in-memory database. # Forkserver and spawn require migrating to disk which will be # re-opened in setup_worker_connection. elif multiprocessing.get_start_method() in {"forkserver", "spawn"}: ondisk_db = sqlite3.connect(target_database_name, uri=True) self.connection.connection.backup(ondisk_db) ondisk_db.close() def _destroy_test_db(self, test_database_name, verbosity): if test_database_name and not self.is_in_memory_db(test_database_name): # Remove the SQLite database file os.remove(test_database_name) def test_db_signature(self): """ Return a tuple that uniquely identifies a test database. This takes into account the special cases of ":memory:" and "" for SQLite since the databases will be distinct despite having the same TEST NAME. See https://www.sqlite.org/inmemorydb.html """ test_database_name = self._get_test_db_name() sig = [self.connection.settings_dict["NAME"]] if self.is_in_memory_db(test_database_name): sig.append(self.connection.alias) else: sig.append(test_database_name) return tuple(sig) def setup_worker_connection(self, _worker_id): settings_dict = self.get_test_db_clone_settings(_worker_id) # connection.settings_dict must be updated in place for changes to be # reflected in django.db.connections. Otherwise new threads would # connect to the default database instead of the appropriate clone. start_method = multiprocessing.get_start_method() if start_method == "fork": # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.close() elif start_method in {"forkserver", "spawn"}: alias = self.connection.alias connection_str = ( f"file:memorydb_{alias}_{_worker_id}?mode=memory&cache=shared" ) source_db = self.connection.Database.connect( f"file:{alias}_{_worker_id}.sqlite3?mode=ro", uri=True ) target_db = sqlite3.connect(connection_str, uri=True) source_db.backup(target_db) source_db.close() # Update settings_dict in place. self.connection.settings_dict.update(settings_dict) self.connection.settings_dict["NAME"] = connection_str # Re-open connection to in-memory database before closing copy # connection. self.connection.connect() target_db.close()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/introspection.py
django/db/backends/sqlite3/introspection.py
from collections import namedtuple import sqlparse from django.db import DatabaseError from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.introspection import FieldInfo as BaseFieldInfo from django.db.backends.base.introspection import TableInfo from django.db.models import Index from django.utils.regex_helper import _lazy_re_compile FieldInfo = namedtuple( "FieldInfo", [*BaseFieldInfo._fields, "pk", "has_json_constraint"] ) field_size_re = _lazy_re_compile(r"^\s*(?:var)?char\s*\(\s*(\d+)\s*\)\s*$") def get_field_size(name): """Extract the size number from a "varchar(11)" type name""" m = field_size_re.search(name) return int(m[1]) if m else None # This light wrapper "fakes" a dictionary interface, because some SQLite data # types include variables in them -- e.g. "varchar(30)" -- and can't be matched # as a simple dictionary lookup. class FlexibleFieldLookupDict: # Maps SQL types to Django Field types. Some of the SQL types have multiple # entries here because SQLite allows for anything and doesn't normalize the # field type; it uses whatever was given. base_data_types_reverse = { "bool": "BooleanField", "boolean": "BooleanField", "smallint": "SmallIntegerField", "smallint unsigned": "PositiveSmallIntegerField", "smallinteger": "SmallIntegerField", "int": "IntegerField", "integer": "IntegerField", "bigint": "BigIntegerField", "integer unsigned": "PositiveIntegerField", "bigint unsigned": "PositiveBigIntegerField", "decimal": "DecimalField", "real": "FloatField", "text": "TextField", "char": "CharField", "varchar": "CharField", "blob": "BinaryField", "date": "DateField", "datetime": "DateTimeField", "time": "TimeField", } def __getitem__(self, key): key = key.lower().split("(", 1)[0].strip() return self.base_data_types_reverse[key] class DatabaseIntrospection(BaseDatabaseIntrospection): data_types_reverse = FlexibleFieldLookupDict() def get_field_type(self, data_type, description): field_type = super().get_field_type(data_type, description) if description.pk and field_type in { "BigIntegerField", "IntegerField", "SmallIntegerField", }: # No support for BigAutoField or SmallAutoField as SQLite treats # all integer primary keys as signed 64-bit integers. return "AutoField" if description.has_json_constraint: return "JSONField" return field_type def get_table_list(self, cursor): """Return a list of table and view names in the current database.""" # Skip the sqlite_sequence system table used for autoincrement key # generation. cursor.execute( """ SELECT name, type FROM sqlite_master WHERE type in ('table', 'view') AND NOT name='sqlite_sequence' ORDER BY name""" ) return [TableInfo(row[0], row[1][0]) for row in cursor.fetchall()] def get_table_description(self, cursor, table_name): """ Return a description of the table with the DB-API cursor.description interface. """ cursor.execute( "PRAGMA table_xinfo(%s)" % self.connection.ops.quote_name(table_name) ) table_info = cursor.fetchall() if not table_info: raise DatabaseError(f"Table {table_name} does not exist (empty pragma).") collations = self._get_column_collations(cursor, table_name) json_columns = set() if self.connection.features.can_introspect_json_field: for line in table_info: column = line[1] json_constraint_sql = '%%json_valid("%s")%%' % column has_json_constraint = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s AND sql LIKE %s """, [table_name, json_constraint_sql], ).fetchone() if has_json_constraint: json_columns.add(column) table_description = [ FieldInfo( name, data_type, get_field_size(data_type), None, None, None, not notnull, default, collations.get(name), bool(pk), name in json_columns, ) for cid, name, data_type, notnull, default, pk, hidden in table_info if hidden in [ 0, # Normal column. 2, # Virtual generated column. 3, # Stored generated column. ] ] # If the primary key is composed of multiple columns they should not # be individually marked as pk. primary_key = [ index for index, field_info in enumerate(table_description) if field_info.pk ] if len(primary_key) > 1: for index in primary_key: table_description[index] = table_description[index]._replace(pk=False) return table_description def get_sequences(self, cursor, table_name, table_fields=()): pk_col = self.get_primary_key_column(cursor, table_name) return [{"table": table_name, "column": pk_col}] def get_relations(self, cursor, table_name): """ Return a dictionary of {column_name: (ref_column_name, ref_table_name, db_on_delete)} representing all foreign keys in the given table. """ cursor.execute( "PRAGMA foreign_key_list(%s)" % self.connection.ops.quote_name(table_name) ) return { column_name: ( ref_column_name, ref_table_name, self.on_delete_types.get(on_delete), ) for ( _, _, ref_table_name, column_name, ref_column_name, _, on_delete, *_, ) in cursor.fetchall() } def get_primary_key_columns(self, cursor, table_name): cursor.execute( "PRAGMA table_info(%s)" % self.connection.ops.quote_name(table_name) ) return [name for _, name, *_, pk in cursor.fetchall() if pk] def _parse_column_or_constraint_definition(self, tokens, columns): token = None is_constraint_definition = None field_name = None constraint_name = None unique = False unique_columns = [] check = False check_columns = [] braces_deep = 0 for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): braces_deep += 1 elif token.match(sqlparse.tokens.Punctuation, ")"): braces_deep -= 1 if braces_deep < 0: # End of columns and constraints for table definition. break elif braces_deep == 0 and token.match(sqlparse.tokens.Punctuation, ","): # End of current column or constraint definition. break # Detect column or constraint definition by first token. if is_constraint_definition is None: is_constraint_definition = token.match( sqlparse.tokens.Keyword, "CONSTRAINT" ) if is_constraint_definition: continue if is_constraint_definition: # Detect constraint name by second token. if constraint_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): constraint_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: constraint_name = token.value[1:-1] # Start constraint columns parsing after UNIQUE keyword. if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique = True unique_braces_deep = braces_deep elif unique: if unique_braces_deep == braces_deep: if unique_columns: # Stop constraint parsing. unique = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): unique_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: unique_columns.append(token.value[1:-1]) else: # Detect field name by first token. if field_name is None: if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): field_name = token.value elif token.ttype == sqlparse.tokens.Literal.String.Symbol: field_name = token.value[1:-1] if token.match(sqlparse.tokens.Keyword, "UNIQUE"): unique_columns = [field_name] # Start constraint columns parsing after CHECK keyword. if token.match(sqlparse.tokens.Keyword, "CHECK"): check = True check_braces_deep = braces_deep elif check: if check_braces_deep == braces_deep: if check_columns: # Stop constraint parsing. check = False continue if token.ttype in (sqlparse.tokens.Name, sqlparse.tokens.Keyword): if token.value in columns: check_columns.append(token.value) elif token.ttype == sqlparse.tokens.Literal.String.Symbol: if token.value[1:-1] in columns: check_columns.append(token.value[1:-1]) unique_constraint = ( { "unique": True, "columns": unique_columns, "primary_key": False, "foreign_key": None, "check": False, "index": False, } if unique_columns else None ) check_constraint = ( { "check": True, "columns": check_columns, "primary_key": False, "unique": False, "foreign_key": None, "index": False, } if check_columns else None ) return constraint_name, unique_constraint, check_constraint, token def _parse_table_constraints(self, sql, columns): # Check constraint parsing is based of SQLite syntax diagram. # https://www.sqlite.org/syntaxdiagrams.html#table-constraint statement = sqlparse.parse(sql)[0] constraints = {} unnamed_constrains_index = 0 tokens = (token for token in statement.flatten() if not token.is_whitespace) # Go to columns and constraint definition for token in tokens: if token.match(sqlparse.tokens.Punctuation, "("): break # Parse columns and constraint definition while True: ( constraint_name, unique, check, end_token, ) = self._parse_column_or_constraint_definition(tokens, columns) if unique: if constraint_name: constraints[constraint_name] = unique else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = unique if check: if constraint_name: constraints[constraint_name] = check else: unnamed_constrains_index += 1 constraints[ "__unnamed_constraint_%s__" % unnamed_constrains_index ] = check if end_token.match(sqlparse.tokens.Punctuation, ")"): break return constraints def get_constraints(self, cursor, table_name): """ Retrieve any constraints or keys (unique, pk, fk, check, index) across one or more columns. """ constraints = {} # Find inline check constraints. try: table_schema = cursor.execute( "SELECT sql FROM sqlite_master WHERE type='table' and name=%s", [table_name], ).fetchone()[0] except TypeError: # table_name is a view. pass else: columns = { info.name for info in self.get_table_description(cursor, table_name) } constraints.update(self._parse_table_constraints(table_schema, columns)) # Get the index info cursor.execute( "PRAGMA index_list(%s)" % self.connection.ops.quote_name(table_name) ) for row in cursor.fetchall(): # Discard last 2 columns. number, index, unique = row[:3] cursor.execute( "SELECT sql FROM sqlite_master WHERE type='index' AND name=%s", [index], ) # There's at most one row. (sql,) = cursor.fetchone() or (None,) # Inline constraints are already detected in # _parse_table_constraints(). The reasons to avoid fetching inline # constraints from `PRAGMA index_list` are: # - Inline constraints can have a different name and information # than what `PRAGMA index_list` gives. # - Not all inline constraints may appear in `PRAGMA index_list`. if not sql: # An inline constraint continue # Get the index info for that index cursor.execute( "PRAGMA index_info(%s)" % self.connection.ops.quote_name(index) ) for index_rank, column_rank, column in cursor.fetchall(): if index not in constraints: constraints[index] = { "columns": [], "primary_key": False, "unique": bool(unique), "foreign_key": None, "check": False, "index": True, } constraints[index]["columns"].append(column) # Add type and column orders for indexes if constraints[index]["index"]: # SQLite doesn't support any index type other than b-tree constraints[index]["type"] = Index.suffix orders = self._get_index_columns_orders(sql) if orders is not None: constraints[index]["orders"] = orders # Get the PK pk_columns = self.get_primary_key_columns(cursor, table_name) if pk_columns: # SQLite doesn't actually give a name to the PK constraint, # so we invent one. This is fine, as the SQLite backend never # deletes PK constraints by name, as you can't delete constraints # in SQLite; we remake the table with a new PK instead. constraints["__primary__"] = { "columns": pk_columns, "primary_key": True, "unique": False, # It's not actually a unique constraint. "foreign_key": None, "check": False, "index": False, } relations = enumerate(self.get_relations(cursor, table_name).items()) constraints.update( { f"fk_{index}": { "columns": [column_name], "primary_key": False, "unique": False, "foreign_key": (ref_table_name, ref_column_name), "check": False, "index": False, } for index, ( column_name, (ref_column_name, ref_table_name, _), ) in relations } ) return constraints def _get_index_columns_orders(self, sql): tokens = sqlparse.parse(sql)[0] for token in tokens: if isinstance(token, sqlparse.sql.Parenthesis): columns = str(token).strip("()").split(", ") return ["DESC" if info.endswith("DESC") else "ASC" for info in columns] return None def _get_column_collations(self, cursor, table_name): row = cursor.execute( """ SELECT sql FROM sqlite_master WHERE type = 'table' AND name = %s """, [table_name], ).fetchone() if not row: return {} sql = row[0] columns = str(sqlparse.parse(sql)[0][-1]).strip("()").split(", ") collations = {} for column in columns: tokens = column[1:].split() column_name = tokens[0].strip('"') for index, token in enumerate(tokens): if token == "COLLATE": collation = tokens[index + 1] break else: collation = None collations[column_name] = collation return collations
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/__init__.py
django/db/backends/sqlite3/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/base.py
django/db/backends/sqlite3/base.py
""" SQLite backend for the sqlite3 module in the standard library. """ import datetime import decimal import warnings from collections.abc import Mapping from itertools import chain, tee from sqlite3 import dbapi2 as Database from django.core.exceptions import ImproperlyConfigured from django.db import IntegrityError from django.db.backends.base.base import BaseDatabaseWrapper from django.utils.asyncio import async_unsafe from django.utils.dateparse import parse_date, parse_datetime, parse_time from django.utils.regex_helper import _lazy_re_compile from ._functions import register as register_functions from .client import DatabaseClient from .creation import DatabaseCreation from .features import DatabaseFeatures from .introspection import DatabaseIntrospection from .operations import DatabaseOperations from .schema import DatabaseSchemaEditor def decoder(conv_func): """ Convert bytestrings from Python's sqlite3 interface to a regular string. """ return lambda s: conv_func(s.decode()) def adapt_date(val): return val.isoformat() def adapt_datetime(val): return val.isoformat(" ") def _get_varchar_column(data): if data["max_length"] is None: return "varchar" return "varchar(%(max_length)s)" % data Database.register_converter("bool", b"1".__eq__) Database.register_converter("date", decoder(parse_date)) Database.register_converter("time", decoder(parse_time)) Database.register_converter("datetime", decoder(parse_datetime)) Database.register_converter("timestamp", decoder(parse_datetime)) Database.register_adapter(decimal.Decimal, str) Database.register_adapter(datetime.date, adapt_date) Database.register_adapter(datetime.datetime, adapt_datetime) class DatabaseWrapper(BaseDatabaseWrapper): vendor = "sqlite" display_name = "SQLite" # SQLite doesn't actually support most of these types, but it "does the # right thing" given more verbose field definitions, so leave them as is so # that schema inspection is more useful. data_types = { "AutoField": "integer", "BigAutoField": "integer", "BinaryField": "BLOB", "BooleanField": "bool", "CharField": _get_varchar_column, "DateField": "date", "DateTimeField": "datetime", "DecimalField": "decimal", "DurationField": "bigint", "FileField": "varchar(%(max_length)s)", "FilePathField": "varchar(%(max_length)s)", "FloatField": "real", "IntegerField": "integer", "BigIntegerField": "bigint", "IPAddressField": "char(15)", "GenericIPAddressField": "char(39)", "JSONField": "text", "PositiveBigIntegerField": "bigint unsigned", "PositiveIntegerField": "integer unsigned", "PositiveSmallIntegerField": "smallint unsigned", "SlugField": "varchar(%(max_length)s)", "SmallAutoField": "integer", "SmallIntegerField": "smallint", "TextField": "text", "TimeField": "time", "UUIDField": "char(32)", } data_type_check_constraints = { "PositiveBigIntegerField": '"%(column)s" >= 0', "JSONField": '(JSON_VALID("%(column)s") OR "%(column)s" IS NULL)', "PositiveIntegerField": '"%(column)s" >= 0', "PositiveSmallIntegerField": '"%(column)s" >= 0', } data_types_suffix = { "AutoField": "AUTOINCREMENT", "BigAutoField": "AUTOINCREMENT", "SmallAutoField": "AUTOINCREMENT", } # SQLite requires LIKE statements to include an ESCAPE clause if the value # being escaped has a percent or underscore in it. # See https://www.sqlite.org/lang_expr.html for an explanation. operators = { "exact": "= %s", "iexact": "LIKE %s ESCAPE '\\'", "contains": "LIKE %s ESCAPE '\\'", "icontains": "LIKE %s ESCAPE '\\'", "regex": "REGEXP %s", "iregex": "REGEXP '(?i)' || %s", "gt": "> %s", "gte": ">= %s", "lt": "< %s", "lte": "<= %s", "startswith": "LIKE %s ESCAPE '\\'", "endswith": "LIKE %s ESCAPE '\\'", "istartswith": "LIKE %s ESCAPE '\\'", "iendswith": "LIKE %s ESCAPE '\\'", } # The patterns below are used to generate SQL pattern lookup clauses when # the right-hand side of the lookup isn't a raw string (it might be an # expression or the result of a bilateral transformation). In those cases, # special characters for LIKE operators (e.g. \, *, _) should be escaped on # database side. # # Note: we use str.format() here for readability as '%' is used as a # wildcard for the LIKE operator. pattern_esc = r"REPLACE(REPLACE(REPLACE({}, '\', '\\'), '%%', '\%%'), '_', '\_')" pattern_ops = { "contains": r"LIKE '%%' || {} || '%%' ESCAPE '\'", "icontains": r"LIKE '%%' || UPPER({}) || '%%' ESCAPE '\'", "startswith": r"LIKE {} || '%%' ESCAPE '\'", "istartswith": r"LIKE UPPER({}) || '%%' ESCAPE '\'", "endswith": r"LIKE '%%' || {} ESCAPE '\'", "iendswith": r"LIKE '%%' || UPPER({}) ESCAPE '\'", } transaction_modes = frozenset(["DEFERRED", "EXCLUSIVE", "IMMEDIATE"]) Database = Database SchemaEditorClass = DatabaseSchemaEditor # Classes instantiated in __init__(). client_class = DatabaseClient creation_class = DatabaseCreation features_class = DatabaseFeatures introspection_class = DatabaseIntrospection ops_class = DatabaseOperations def get_connection_params(self): settings_dict = self.settings_dict if not settings_dict["NAME"]: raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the NAME value." ) kwargs = { "database": settings_dict["NAME"], "detect_types": Database.PARSE_DECLTYPES | Database.PARSE_COLNAMES, **settings_dict["OPTIONS"], } # Always allow the underlying SQLite connection to be shareable # between multiple threads. The safe-guarding will be handled at a # higher level by the `BaseDatabaseWrapper.allow_thread_sharing` # property. This is necessary as the shareability is disabled by # default in sqlite3 and it cannot be changed once a connection is # opened. if "check_same_thread" in kwargs and kwargs["check_same_thread"]: warnings.warn( "The `check_same_thread` option was provided and set to " "True. It will be overridden with False. Use the " "`DatabaseWrapper.allow_thread_sharing` property instead " "for controlling thread shareability.", RuntimeWarning, ) kwargs.update({"check_same_thread": False, "uri": True}) transaction_mode = kwargs.pop("transaction_mode", None) if ( transaction_mode is not None and transaction_mode.upper() not in self.transaction_modes ): allowed_transaction_modes = ", ".join( [f"{mode!r}" for mode in sorted(self.transaction_modes)] ) raise ImproperlyConfigured( f"settings.DATABASES[{self.alias!r}]['OPTIONS']['transaction_mode'] " f"is improperly configured to '{transaction_mode}'. Use one of " f"{allowed_transaction_modes}, or None." ) self.transaction_mode = transaction_mode.upper() if transaction_mode else None init_command = kwargs.pop("init_command", "") self.init_commands = init_command.split(";") return kwargs def get_database_version(self): return self.Database.sqlite_version_info @async_unsafe def get_new_connection(self, conn_params): conn = Database.connect(**conn_params) register_functions(conn) conn.execute("PRAGMA foreign_keys = ON") # The macOS bundled SQLite defaults legacy_alter_table ON, which # prevents atomic table renames. conn.execute("PRAGMA legacy_alter_table = OFF") for init_command in self.init_commands: if init_command := init_command.strip(): conn.execute(init_command) return conn def create_cursor(self, name=None): return self.connection.cursor(factory=SQLiteCursorWrapper) @async_unsafe def close(self): self.validate_thread_sharing() # If database is in memory, closing the connection destroys the # database. To prevent accidental data loss, ignore close requests on # an in-memory db. if not self.is_in_memory_db(): BaseDatabaseWrapper.close(self) def _savepoint_allowed(self): # When 'isolation_level' is not None, sqlite3 commits before each # savepoint; it's a bug. When it is None, savepoints don't make sense # because autocommit is enabled. The only exception is inside 'atomic' # blocks. To work around that bug, on SQLite, 'atomic' starts a # transaction explicitly rather than simply disable autocommit. return self.in_atomic_block def _set_autocommit(self, autocommit): if autocommit: level = None else: # sqlite3's internal default is ''. It's different from None. # See Modules/_sqlite/connection.c. level = "" # 'isolation_level' is a misleading API. # SQLite always runs at the SERIALIZABLE isolation level. with self.wrap_database_errors: self.connection.isolation_level = level def disable_constraint_checking(self): with self.cursor() as cursor: cursor.execute("PRAGMA foreign_keys = OFF") # Foreign key constraints cannot be turned off while in a multi- # statement transaction. Fetch the current state of the pragma # to determine if constraints are effectively disabled. enabled = cursor.execute("PRAGMA foreign_keys").fetchone()[0] return not bool(enabled) def enable_constraint_checking(self): with self.cursor() as cursor: cursor.execute("PRAGMA foreign_keys = ON") def check_constraints(self, table_names=None): """ Check each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered while constraint checks were off. """ with self.cursor() as cursor: if table_names is None: violations = cursor.execute("PRAGMA foreign_key_check").fetchall() else: violations = chain.from_iterable( cursor.execute( "PRAGMA foreign_key_check(%s)" % self.ops.quote_name(table_name) ).fetchall() for table_name in table_names ) # See https://www.sqlite.org/pragma.html#pragma_foreign_key_check for ( table_name, rowid, referenced_table_name, foreign_key_index, ) in violations: foreign_key = cursor.execute( "PRAGMA foreign_key_list(%s)" % self.ops.quote_name(table_name) ).fetchall()[foreign_key_index] column_name, referenced_column_name = foreign_key[3:5] primary_key_column_name = self.introspection.get_primary_key_column( cursor, table_name ) primary_key_value, bad_value = cursor.execute( "SELECT %s, %s FROM %s WHERE rowid = %%s" % ( self.ops.quote_name(primary_key_column_name), self.ops.quote_name(column_name), self.ops.quote_name(table_name), ), (rowid,), ).fetchone() raise IntegrityError( "The row in table '%s' with primary key '%s' has an " "invalid foreign key: %s.%s contains a value '%s' that " "does not have a corresponding value in %s.%s." % ( table_name, primary_key_value, table_name, column_name, bad_value, referenced_table_name, referenced_column_name, ) ) def is_usable(self): return True def _start_transaction_under_autocommit(self): """ Start a transaction explicitly in autocommit mode. Staying in autocommit mode works around a bug of sqlite3 that breaks savepoints when autocommit is disabled. """ if self.transaction_mode is None: self.cursor().execute("BEGIN") else: self.cursor().execute(f"BEGIN {self.transaction_mode}") def is_in_memory_db(self): return self.creation.is_in_memory_db(self.settings_dict["NAME"]) FORMAT_QMARK_REGEX = _lazy_re_compile(r"(?<!%)%s") class SQLiteCursorWrapper(Database.Cursor): """ Django uses the "format" and "pyformat" styles, but Python's sqlite3 module supports neither of these styles. This wrapper performs the following conversions: - "format" style to "qmark" style - "pyformat" style to "named" style In both cases, if you want to use a literal "%s", you'll need to use "%%s". """ def execute(self, query, params=None): if params is None: return super().execute(query) # Extract names if params is a mapping, i.e. "pyformat" style is used. param_names = list(params) if isinstance(params, Mapping) else None query = self.convert_query(query, param_names=param_names) return super().execute(query, params) def executemany(self, query, param_list): # Extract names if params is a mapping, i.e. "pyformat" style is used. # Peek carefully as a generator can be passed instead of a list/tuple. peekable, param_list = tee(iter(param_list)) if (params := next(peekable, None)) and isinstance(params, Mapping): param_names = list(params) else: param_names = None query = self.convert_query(query, param_names=param_names) return super().executemany(query, param_list) def convert_query(self, query, *, param_names=None): if param_names is None: # Convert from "format" style to "qmark" style. return FORMAT_QMARK_REGEX.sub("?", query).replace("%%", "%") else: # Convert from "pyformat" style to "named" style. return query % {name: f":{name}" for name in param_names}
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/_functions.py
django/db/backends/sqlite3/_functions.py
""" Implementations of SQL functions for SQLite. """ import functools import random import statistics import zoneinfo from datetime import timedelta from hashlib import md5, sha1, sha224, sha256, sha384, sha512 from math import ( acos, asin, atan, atan2, ceil, cos, degrees, exp, floor, fmod, log, pi, radians, sin, sqrt, tan, ) from re import search as re_search from uuid import uuid4 from django.db.backends.utils import ( split_tzname_delta, typecast_time, typecast_timestamp, ) from django.utils import timezone from django.utils.duration import duration_microseconds from django.utils.version import PY314 if PY314: from uuid import uuid7 def register(connection): create_deterministic_function = functools.partial( connection.create_function, deterministic=True, ) create_deterministic_function("django_date_extract", 2, _sqlite_datetime_extract) create_deterministic_function("django_date_trunc", 4, _sqlite_date_trunc) create_deterministic_function( "django_datetime_cast_date", 3, _sqlite_datetime_cast_date ) create_deterministic_function( "django_datetime_cast_time", 3, _sqlite_datetime_cast_time ) create_deterministic_function( "django_datetime_extract", 4, _sqlite_datetime_extract ) create_deterministic_function("django_datetime_trunc", 4, _sqlite_datetime_trunc) create_deterministic_function("django_time_extract", 2, _sqlite_time_extract) create_deterministic_function("django_time_trunc", 4, _sqlite_time_trunc) create_deterministic_function("django_time_diff", 2, _sqlite_time_diff) create_deterministic_function("django_timestamp_diff", 2, _sqlite_timestamp_diff) create_deterministic_function("django_format_dtdelta", 3, _sqlite_format_dtdelta) create_deterministic_function("regexp", 2, _sqlite_regexp) create_deterministic_function("BITXOR", 2, _sqlite_bitxor) create_deterministic_function("COT", 1, _sqlite_cot) create_deterministic_function("LPAD", 3, _sqlite_lpad) create_deterministic_function("MD5", 1, _sqlite_md5) create_deterministic_function("REPEAT", 2, _sqlite_repeat) create_deterministic_function("REVERSE", 1, _sqlite_reverse) create_deterministic_function("RPAD", 3, _sqlite_rpad) create_deterministic_function("SHA1", 1, _sqlite_sha1) create_deterministic_function("SHA224", 1, _sqlite_sha224) create_deterministic_function("SHA256", 1, _sqlite_sha256) create_deterministic_function("SHA384", 1, _sqlite_sha384) create_deterministic_function("SHA512", 1, _sqlite_sha512) create_deterministic_function("SIGN", 1, _sqlite_sign) # Don't use the built-in RANDOM() function because it returns a value # in the range [-1 * 2^63, 2^63 - 1] instead of [0, 1). connection.create_function("RAND", 0, random.random) connection.create_aggregate("STDDEV_POP", 1, StdDevPop) connection.create_aggregate("STDDEV_SAMP", 1, StdDevSamp) connection.create_aggregate("VAR_POP", 1, VarPop) connection.create_aggregate("VAR_SAMP", 1, VarSamp) connection.create_aggregate("ANY_VALUE", 1, AnyValue) connection.create_function("UUIDV4", 0, _sqlite_uuid4) if PY314: connection.create_function("UUIDV7", 0, _sqlite_uuid7) # Some math functions are enabled by default in SQLite 3.35+. sql = "select sqlite_compileoption_used('ENABLE_MATH_FUNCTIONS')" if not connection.execute(sql).fetchone()[0]: create_deterministic_function("ACOS", 1, _sqlite_acos) create_deterministic_function("ASIN", 1, _sqlite_asin) create_deterministic_function("ATAN", 1, _sqlite_atan) create_deterministic_function("ATAN2", 2, _sqlite_atan2) create_deterministic_function("CEILING", 1, _sqlite_ceiling) create_deterministic_function("COS", 1, _sqlite_cos) create_deterministic_function("DEGREES", 1, _sqlite_degrees) create_deterministic_function("EXP", 1, _sqlite_exp) create_deterministic_function("FLOOR", 1, _sqlite_floor) create_deterministic_function("LN", 1, _sqlite_ln) create_deterministic_function("LOG", 2, _sqlite_log) create_deterministic_function("MOD", 2, _sqlite_mod) create_deterministic_function("PI", 0, _sqlite_pi) create_deterministic_function("POWER", 2, _sqlite_power) create_deterministic_function("RADIANS", 1, _sqlite_radians) create_deterministic_function("SIN", 1, _sqlite_sin) create_deterministic_function("SQRT", 1, _sqlite_sqrt) create_deterministic_function("TAN", 1, _sqlite_tan) def _sqlite_datetime_parse(dt, tzname=None, conn_tzname=None): if dt is None: return None try: dt = typecast_timestamp(dt) except (TypeError, ValueError): return None if conn_tzname: dt = dt.replace(tzinfo=zoneinfo.ZoneInfo(conn_tzname)) if tzname is not None and tzname != conn_tzname: tzname, sign, offset = split_tzname_delta(tzname) if offset: hours, minutes = offset.split(":") offset_delta = timedelta(hours=int(hours), minutes=int(minutes)) dt += offset_delta if sign == "+" else -offset_delta # The tzname may originally be just the offset e.g. "+3:00", # which becomes an empty string after splitting the sign and offset. # In this case, use the conn_tzname as fallback. dt = timezone.localtime(dt, zoneinfo.ZoneInfo(tzname or conn_tzname)) return dt def _sqlite_date_trunc(lookup_type, dt, tzname, conn_tzname): dt = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt is None: return None if lookup_type == "year": return f"{dt.year:04d}-01-01" elif lookup_type == "quarter": month_in_quarter = dt.month - (dt.month - 1) % 3 return f"{dt.year:04d}-{month_in_quarter:02d}-01" elif lookup_type == "month": return f"{dt.year:04d}-{dt.month:02d}-01" elif lookup_type == "week": dt -= timedelta(days=dt.weekday()) return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}" elif lookup_type == "day": return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}" raise ValueError(f"Unsupported lookup type: {lookup_type!r}") def _sqlite_time_trunc(lookup_type, dt, tzname, conn_tzname): if dt is None: return None dt_parsed = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt_parsed is None: try: dt = typecast_time(dt) except (ValueError, TypeError): return None else: dt = dt_parsed if lookup_type == "hour": return f"{dt.hour:02d}:00:00" elif lookup_type == "minute": return f"{dt.hour:02d}:{dt.minute:02d}:00" elif lookup_type == "second": return f"{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}" raise ValueError(f"Unsupported lookup type: {lookup_type!r}") def _sqlite_datetime_cast_date(dt, tzname, conn_tzname): dt = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt is None: return None return dt.date().isoformat() def _sqlite_datetime_cast_time(dt, tzname, conn_tzname): dt = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt is None: return None return dt.time().isoformat() def _sqlite_datetime_extract(lookup_type, dt, tzname=None, conn_tzname=None): dt = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt is None: return None if lookup_type == "week_day": return (dt.isoweekday() % 7) + 1 elif lookup_type == "iso_week_day": return dt.isoweekday() elif lookup_type == "week": return dt.isocalendar().week elif lookup_type == "quarter": return ceil(dt.month / 3) elif lookup_type == "iso_year": return dt.isocalendar().year else: return getattr(dt, lookup_type) def _sqlite_datetime_trunc(lookup_type, dt, tzname, conn_tzname): dt = _sqlite_datetime_parse(dt, tzname, conn_tzname) if dt is None: return None if lookup_type == "year": return f"{dt.year:04d}-01-01 00:00:00" elif lookup_type == "quarter": month_in_quarter = dt.month - (dt.month - 1) % 3 return f"{dt.year:04d}-{month_in_quarter:02d}-01 00:00:00" elif lookup_type == "month": return f"{dt.year:04d}-{dt.month:02d}-01 00:00:00" elif lookup_type == "week": dt -= timedelta(days=dt.weekday()) return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00" elif lookup_type == "day": return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} 00:00:00" elif lookup_type == "hour": return f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} {dt.hour:02d}:00:00" elif lookup_type == "minute": return ( f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} " f"{dt.hour:02d}:{dt.minute:02d}:00" ) elif lookup_type == "second": return ( f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d} " f"{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}" ) raise ValueError(f"Unsupported lookup type: {lookup_type!r}") def _sqlite_time_extract(lookup_type, dt): if dt is None: return None try: dt = typecast_time(dt) except (ValueError, TypeError): return None return getattr(dt, lookup_type) def _sqlite_prepare_dtdelta_param(conn, param): if conn in ["+", "-"]: if isinstance(param, int): return timedelta(0, 0, param) else: return typecast_timestamp(param) return param def _sqlite_format_dtdelta(connector, lhs, rhs): """ LHS and RHS can be either: - An integer number of microseconds - A string representing a datetime - A scalar value, e.g. float """ if connector is None or lhs is None or rhs is None: return None connector = connector.strip() try: real_lhs = _sqlite_prepare_dtdelta_param(connector, lhs) real_rhs = _sqlite_prepare_dtdelta_param(connector, rhs) except (ValueError, TypeError): return None if connector == "+": # typecast_timestamp() returns a date or a datetime without timezone. # It will be formatted as "%Y-%m-%d" or "%Y-%m-%d %H:%M:%S[.%f]" out = str(real_lhs + real_rhs) elif connector == "-": out = str(real_lhs - real_rhs) elif connector == "*": out = real_lhs * real_rhs else: out = real_lhs / real_rhs return out def _sqlite_time_diff(lhs, rhs): if lhs is None or rhs is None: return None left = typecast_time(lhs) right = typecast_time(rhs) return ( (left.hour * 60 * 60 * 1000000) + (left.minute * 60 * 1000000) + (left.second * 1000000) + (left.microsecond) - (right.hour * 60 * 60 * 1000000) - (right.minute * 60 * 1000000) - (right.second * 1000000) - (right.microsecond) ) def _sqlite_timestamp_diff(lhs, rhs): if lhs is None or rhs is None: return None left = typecast_timestamp(lhs) right = typecast_timestamp(rhs) return duration_microseconds(left - right) def _sqlite_regexp(pattern, string): if pattern is None or string is None: return None if not isinstance(string, str): string = str(string) return bool(re_search(pattern, string)) def _sqlite_acos(x): if x is None: return None return acos(x) def _sqlite_asin(x): if x is None: return None return asin(x) def _sqlite_atan(x): if x is None: return None return atan(x) def _sqlite_atan2(y, x): if y is None or x is None: return None return atan2(y, x) def _sqlite_bitxor(x, y): if x is None or y is None: return None return x ^ y def _sqlite_ceiling(x): if x is None: return None return ceil(x) def _sqlite_cos(x): if x is None: return None return cos(x) def _sqlite_cot(x): if x is None: return None return 1 / tan(x) def _sqlite_degrees(x): if x is None: return None return degrees(x) def _sqlite_exp(x): if x is None: return None return exp(x) def _sqlite_floor(x): if x is None: return None return floor(x) def _sqlite_ln(x): if x is None: return None return log(x) def _sqlite_log(base, x): if base is None or x is None: return None # Arguments reversed to match SQL standard. return log(x, base) def _sqlite_lpad(text, length, fill_text): if text is None or length is None or fill_text is None: return None delta = length - len(text) if delta <= 0: return text[:length] return (fill_text * length)[:delta] + text def _sqlite_md5(text): if text is None: return None return md5(text.encode()).hexdigest() def _sqlite_mod(x, y): if x is None or y is None: return None return fmod(x, y) def _sqlite_pi(): return pi def _sqlite_power(x, y): if x is None or y is None: return None return x**y def _sqlite_radians(x): if x is None: return None return radians(x) def _sqlite_repeat(text, count): if text is None or count is None: return None return text * count def _sqlite_reverse(text): if text is None: return None return text[::-1] def _sqlite_rpad(text, length, fill_text): if text is None or length is None or fill_text is None: return None return (text + fill_text * length)[:length] def _sqlite_sha1(text): if text is None: return None return sha1(text.encode()).hexdigest() def _sqlite_sha224(text): if text is None: return None return sha224(text.encode()).hexdigest() def _sqlite_sha256(text): if text is None: return None return sha256(text.encode()).hexdigest() def _sqlite_sha384(text): if text is None: return None return sha384(text.encode()).hexdigest() def _sqlite_sha512(text): if text is None: return None return sha512(text.encode()).hexdigest() def _sqlite_sign(x): if x is None: return None return (x > 0) - (x < 0) def _sqlite_sin(x): if x is None: return None return sin(x) def _sqlite_sqrt(x): if x is None: return None return sqrt(x) def _sqlite_tan(x): if x is None: return None return tan(x) def _sqlite_uuid4(): return uuid4().hex def _sqlite_uuid7(): return uuid7().hex class ListAggregate(list): step = list.append class StdDevPop(ListAggregate): finalize = statistics.pstdev class StdDevSamp(ListAggregate): finalize = statistics.stdev class VarPop(ListAggregate): finalize = statistics.pvariance class VarSamp(ListAggregate): finalize = statistics.variance class AnyValue(ListAggregate): def finalize(self): return self[0]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/sqlite3/features.py
django/db/backends/sqlite3/features.py
import operator import sqlite3 from django.db import transaction from django.db.backends.base.features import BaseDatabaseFeatures from django.db.utils import OperationalError from django.utils.functional import cached_property from django.utils.version import PY314 from .base import Database class DatabaseFeatures(BaseDatabaseFeatures): minimum_database_version = (3, 37) test_db_allows_multiple_connections = False supports_unspecified_pk = True supports_timezones = False supports_transactions = True atomic_transactions = False can_rollback_ddl = True can_create_inline_fk = False requires_literal_defaults = True can_clone_databases = True supports_temporal_subtraction = True ignores_table_name_case = True supports_cast_with_precision = False time_cast_precision = 3 can_release_savepoints = True has_case_insensitive_like = True supports_parentheses_in_compound = False can_defer_constraint_checks = True supports_over_clause = True supports_frame_range_fixed_distance = True supports_frame_exclusion = True supports_aggregate_filter_clause = True supports_aggregate_order_by_clause = Database.sqlite_version_info >= (3, 44, 0) supports_aggregate_distinct_multiple_argument = False supports_any_value = True order_by_nulls_first = True supports_json_field_contains = False supports_update_conflicts = True supports_update_conflicts_with_target = True supports_stored_generated_columns = True supports_virtual_generated_columns = True test_collations = { "ci": "nocase", "cs": "binary", "non_default": "nocase", "virtual": "nocase", } django_test_expected_failures = { # The django_format_dtdelta() function doesn't properly handle mixed # Date/DateTime fields and timedeltas. "expressions.tests.FTimeDeltaTests.test_mixed_comparisons1", } insert_test_table_with_defaults = 'INSERT INTO {} ("null") VALUES (1)' supports_default_keyword_in_insert = False supports_unlimited_charfield = True supports_no_precision_decimalfield = True can_return_columns_from_insert = True can_return_rows_from_bulk_insert = True can_return_rows_from_update = True supports_uuid4_function = True @cached_property def supports_uuid7_function(self): return PY314 @cached_property def django_test_skips(self): skips = { "SQLite stores values rounded to 15 significant digits.": { "model_fields.test_decimalfield.DecimalFieldTests." "test_fetch_from_db_without_float_rounding", }, "SQLite naively remakes the table on field alteration.": { "schema.tests.SchemaTests.test_unique_no_unnecessary_fk_drops", "schema.tests.SchemaTests.test_unique_and_reverse_m2m", "schema.tests.SchemaTests." "test_alter_field_default_doesnt_perform_queries", "schema.tests.SchemaTests." "test_rename_column_renames_deferred_sql_references", }, "SQLite doesn't support negative precision for ROUND().": { "db_functions.math.test_round.RoundTests." "test_null_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_decimal_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_float_with_negative_precision", "db_functions.math.test_round.RoundTests." "test_integer_with_negative_precision", }, "The actual query cannot be determined on SQLite": { "backends.base.test_base.ExecuteWrapperTests.test_wrapper_debug", }, } if self.connection.is_in_memory_db(): skips.update( { "the sqlite backend's close() method is a no-op when using an " "in-memory database": { "servers.test_liveserverthread.LiveServerThreadTest." "test_closes_connections", "servers.tests.LiveServerTestCloseConnectionTest." "test_closes_connections", }, "For SQLite in-memory tests, closing the connection destroys " "the database.": { "test_utils.tests.AssertNumQueriesUponConnectionTests." "test_ignores_connection_configuration_queries", }, } ) else: skips.update( { "Only connections to in-memory SQLite databases are passed to the " "server thread.": { "servers.tests.LiveServerInMemoryDatabaseLockTest." "test_in_memory_database_lock", }, "multiprocessing's start method is checked only for in-memory " "SQLite databases": { "backends.sqlite.test_creation.TestDbSignatureTests." "test_get_test_db_clone_settings_not_supported", }, } ) if Database.sqlite_version_info < (3, 47): skips.update( { "SQLite does not parse escaped double quotes in the JSON path " "notation": { "model_fields.test_jsonfield.TestQuerying." "test_lookups_special_chars_double_quotes", }, } ) return skips @cached_property def introspected_field_types(self): return { **super().introspected_field_types, "BigAutoField": "AutoField", "DurationField": "BigIntegerField", "GenericIPAddressField": "CharField", "SmallAutoField": "AutoField", } @property def max_query_params(self): """ SQLite has a variable limit per query. The limit can be changed using the SQLITE_MAX_VARIABLE_NUMBER compile-time option (which defaults to 32766) or lowered per connection at run-time with setlimit(SQLITE_LIMIT_VARIABLE_NUMBER, N). """ self.connection.ensure_connection() return self.connection.connection.getlimit(sqlite3.SQLITE_LIMIT_VARIABLE_NUMBER) @cached_property def supports_json_field(self): with self.connection.cursor() as cursor: try: with transaction.atomic(self.connection.alias): cursor.execute('SELECT JSON(\'{"a": "b"}\')') except OperationalError: return False return True can_introspect_json_field = property(operator.attrgetter("supports_json_field")) has_json_object_function = property(operator.attrgetter("supports_json_field"))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/dummy/__init__.py
django/db/backends/dummy/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/dummy/base.py
django/db/backends/dummy/base.py
""" Dummy database backend for Django. Django uses this if the database ENGINE setting is empty (None or empty string). Each of these API functions, except connection.close(), raise ImproperlyConfigured. """ from django.core.exceptions import ImproperlyConfigured from django.db.backends.base.base import BaseDatabaseWrapper from django.db.backends.base.client import BaseDatabaseClient from django.db.backends.base.creation import BaseDatabaseCreation from django.db.backends.base.introspection import BaseDatabaseIntrospection from django.db.backends.base.operations import BaseDatabaseOperations from django.db.backends.dummy.features import DummyDatabaseFeatures def complain(*args, **kwargs): raise ImproperlyConfigured( "settings.DATABASES is improperly configured. " "Please supply the ENGINE value. Check " "settings documentation for more details." ) def ignore(*args, **kwargs): pass class DatabaseOperations(BaseDatabaseOperations): quote_name = complain class DatabaseClient(BaseDatabaseClient): runshell = complain class DatabaseCreation(BaseDatabaseCreation): create_test_db = ignore destroy_test_db = ignore serialize_db_to_string = ignore class DatabaseIntrospection(BaseDatabaseIntrospection): get_table_list = complain get_table_description = complain get_relations = complain get_indexes = complain class DatabaseWrapper(BaseDatabaseWrapper): operators = {} # Override the base class implementations with null # implementations. Anything that tries to actually # do something raises complain; anything that tries # to rollback or undo something raises ignore. _cursor = complain ensure_connection = complain _commit = complain _rollback = ignore _close = ignore _savepoint = ignore _savepoint_commit = complain _savepoint_rollback = ignore _set_autocommit = complain # Classes instantiated in __init__(). client_class = DatabaseClient creation_class = DatabaseCreation features_class = DummyDatabaseFeatures introspection_class = DatabaseIntrospection ops_class = DatabaseOperations def is_usable(self): return True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/db/backends/dummy/features.py
django/db/backends/dummy/features.py
from django.db.backends.base.features import BaseDatabaseFeatures class DummyDatabaseFeatures(BaseDatabaseFeatures): supports_transactions = False uses_savepoints = False
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/client.py
django/test/client.py
import json import mimetypes import os import sys from collections.abc import Iterable from copy import copy from functools import partial from http import HTTPStatus from importlib import import_module from io import BytesIO, IOBase from urllib.parse import unquote_to_bytes, urljoin, urlsplit from asgiref.sync import sync_to_async from django.conf import settings from django.core.handlers.asgi import ASGIRequest from django.core.handlers.base import BaseHandler from django.core.handlers.wsgi import LimitedStream, WSGIRequest from django.core.serializers.json import DjangoJSONEncoder from django.core.signals import got_request_exception, request_finished, request_started from django.db import close_old_connections from django.http import HttpHeaders, HttpRequest, QueryDict, SimpleCookie from django.test import signals from django.test.utils import ContextList from django.urls import resolve from django.utils.encoding import force_bytes from django.utils.functional import SimpleLazyObject from django.utils.http import urlencode from django.utils.regex_helper import _lazy_re_compile __all__ = ( "AsyncClient", "AsyncRequestFactory", "Client", "RedirectCycleError", "RequestFactory", "encode_file", "encode_multipart", ) BOUNDARY = "BoUnDaRyStRiNg" MULTIPART_CONTENT = "multipart/form-data; boundary=%s" % BOUNDARY CONTENT_TYPE_RE = _lazy_re_compile(r".*; charset=([\w-]+);?") # Structured suffix spec: https://tools.ietf.org/html/rfc6838#section-4.2.8 JSON_CONTENT_TYPE_RE = _lazy_re_compile(r"^application\/(.+\+)?json") REDIRECT_STATUS_CODES = frozenset( [ HTTPStatus.MOVED_PERMANENTLY, HTTPStatus.FOUND, HTTPStatus.SEE_OTHER, HTTPStatus.TEMPORARY_REDIRECT, HTTPStatus.PERMANENT_REDIRECT, ] ) class RedirectCycleError(Exception): """The test client has been asked to follow a redirect loop.""" def __init__(self, message, last_response): super().__init__(message) self.last_response = last_response self.redirect_chain = last_response.redirect_chain class FakePayload(IOBase): """ A wrapper around BytesIO that restricts what can be read since data from the network can't be sought and cannot be read outside of its content length. This makes sure that views can't do anything under the test client that wouldn't work in real life. """ def __init__(self, initial_bytes=None): self.__content = BytesIO() self.__len = 0 self.read_started = False if initial_bytes is not None: self.write(initial_bytes) def __len__(self): return self.__len def read(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.read(size) self.__len -= len(content) return content def readline(self, size=-1, /): if not self.read_started: self.__content.seek(0) self.read_started = True if size == -1 or size is None: size = self.__len assert ( self.__len >= size ), "Cannot read more than the available bytes from the HTTP incoming data." content = self.__content.readline(size) self.__len -= len(content) return content def write(self, b, /): if self.read_started: raise ValueError("Unable to write a payload after it's been read") content = force_bytes(b) self.__content.write(content) self.__len += len(content) def closing_iterator_wrapper(iterable, close): try: yield from iterable finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) async def aclosing_iterator_wrapper(iterable, close): try: async for chunk in iterable: yield chunk finally: request_finished.disconnect(close_old_connections) close() # will fire request_finished request_finished.connect(close_old_connections) def conditional_content_removal(request, response): """ Simulate the behavior of most web servers by removing the content of responses for HEAD requests, 1xx, 204, and 304 responses. Ensure compliance with RFC 9112 Section 6.3. """ if 100 <= response.status_code < 200 or response.status_code in (204, 304): if response.streaming: response.streaming_content = [] else: response.content = b"" if request.method == "HEAD": if response.streaming: response.streaming_content = [] else: response.content = b"" return response class ClientHandler(BaseHandler): """ An HTTP Handler that can be used for testing purposes. Use the WSGI interface to compose requests, but return the raw HttpResponse object with the originating WSGIRequest attached to its ``wsgi_request`` attribute. """ def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) def __call__(self, environ): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware() request_started.disconnect(close_old_connections) request_started.send(sender=self.__class__, environ=environ) request_started.connect(close_old_connections) request = WSGIRequest(environ) # sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably # required for backwards compatibility with external tests against # admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = self.get_response(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating request to the response so that it could be # later retrieved. response.wsgi_request = request # Emulate a WSGI server by calling the close method on completion. if response.streaming: if response.is_async: response.streaming_content = aclosing_iterator_wrapper( response.streaming_content, response.close ) else: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) response.close() # will fire request_finished request_finished.connect(close_old_connections) return response class AsyncClientHandler(BaseHandler): """An async version of ClientHandler.""" def __init__(self, enforce_csrf_checks=True, *args, **kwargs): self.enforce_csrf_checks = enforce_csrf_checks super().__init__(*args, **kwargs) async def __call__(self, scope): # Set up middleware if needed. We couldn't do this earlier, because # settings weren't available. if self._middleware_chain is None: self.load_middleware(is_async=True) # Extract body file from the scope, if provided. if "_body_file" in scope: body_file = scope.pop("_body_file") else: body_file = FakePayload("") request_started.disconnect(close_old_connections) await request_started.asend(sender=self.__class__, scope=scope) request_started.connect(close_old_connections) # Wrap FakePayload body_file to allow large read() in test environment. request = ASGIRequest(scope, LimitedStream(body_file, len(body_file))) # Sneaky little hack so that we can easily get round # CsrfViewMiddleware. This makes life easier, and is probably required # for backwards compatibility with external tests against admin views. request._dont_enforce_csrf_checks = not self.enforce_csrf_checks # Request goes through middleware. response = await self.get_response_async(request) # Simulate behaviors of most web servers. conditional_content_removal(request, response) # Attach the originating ASGI request to the response so that it could # be later retrieved. response.asgi_request = request # Emulate a server by calling the close method on completion. if response.streaming: if response.is_async: response.streaming_content = aclosing_iterator_wrapper( response.streaming_content, response.close ) else: response.streaming_content = closing_iterator_wrapper( response.streaming_content, response.close ) else: request_finished.disconnect(close_old_connections) # Will fire request_finished. await sync_to_async(response.close, thread_sensitive=False)() request_finished.connect(close_old_connections) return response def store_rendered_templates(store, signal, sender, template, context, **kwargs): """ Store templates and contexts that are rendered. The context is copied so that it is an accurate representation at the time of rendering. """ store.setdefault("templates", []).append(template) if "context" not in store: store["context"] = ContextList() store["context"].append(copy(context)) def encode_multipart(boundary, data): """ Encode multipart POST data from a dictionary of form values. The key will be used as the form data name; the value will be transmitted as content. If the value is a file, the contents of the file will be sent as an application/octet-stream; otherwise, str(value) will be sent. """ lines = [] def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # Not by any means perfect, but good enough for our purposes. def is_file(thing): return hasattr(thing, "read") and callable(thing.read) # Each bit of the multipart form data could be either a form value or a # file, or a *list* of form values and/or files. Remember that HTTP field # names can be duplicated! for key, value in data.items(): if value is None: raise TypeError( "Cannot encode None for key '%s' as POST data. Did you mean " "to pass an empty string or omit the value?" % key ) elif is_file(value): lines.extend(encode_file(boundary, key, value)) elif not isinstance(value, str) and isinstance(value, Iterable): for item in value: if is_file(item): lines.extend(encode_file(boundary, key, item)) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", item, ] ) else: lines.extend( to_bytes(val) for val in [ "--%s" % boundary, 'Content-Disposition: form-data; name="%s"' % key, "", value, ] ) lines.extend( [ to_bytes("--%s--" % boundary), b"", ] ) return b"\r\n".join(lines) def encode_file(boundary, key, file): def to_bytes(s): return force_bytes(s, settings.DEFAULT_CHARSET) # file.name might not be a string. For example, it's an int for # tempfile.TemporaryFile(). file_has_string_name = hasattr(file, "name") and isinstance(file.name, str) filename = os.path.basename(file.name) if file_has_string_name else "" if hasattr(file, "content_type"): content_type = file.content_type elif filename: content_type = mimetypes.guess_type(filename)[0] else: content_type = None if content_type is None: content_type = "application/octet-stream" filename = filename or key return [ to_bytes("--%s" % boundary), to_bytes( 'Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename) ), to_bytes("Content-Type: %s" % content_type), b"", to_bytes(file.read()), ] class RequestFactory: """ Class that lets you create mock Request objects for use in testing. Usage: rf = RequestFactory() get_request = rf.get('/hello/') post_request = rf.post('/submit/', {'foo': 'bar'}) Once you have a request object you can pass it to any view function, just as if that view had been hooked up using a URLconf. """ def __init__( self, *, json_encoder=DjangoJSONEncoder, headers=None, query_params=None, **defaults, ): self.json_encoder = json_encoder self.defaults = defaults self.cookies = SimpleCookie() self.errors = BytesIO() if headers: self.defaults.update(HttpHeaders.to_wsgi_names(headers)) if query_params: self.defaults["QUERY_STRING"] = urlencode(query_params, doseq=True) def _base_environ(self, **request): """ The base environment for a request. """ # This is a minimal valid WSGI environ dictionary, plus: # - HTTP_COOKIE: for cookie support, # - REMOTE_ADDR: often useful, see #8551. # See https://www.python.org/dev/peps/pep-3333/#environ-variables return { "HTTP_COOKIE": "; ".join( sorted( "%s=%s" % (morsel.key, morsel.coded_value) for morsel in self.cookies.values() ) ), "PATH_INFO": "/", "REMOTE_ADDR": "127.0.0.1", "REQUEST_METHOD": "GET", "SCRIPT_NAME": "", "SERVER_NAME": "testserver", "SERVER_PORT": "80", "SERVER_PROTOCOL": "HTTP/1.1", "wsgi.version": (1, 0), "wsgi.url_scheme": "http", "wsgi.input": FakePayload(b""), "wsgi.errors": self.errors, "wsgi.multiprocess": True, "wsgi.multithread": False, "wsgi.run_once": False, **self.defaults, **request, } def request(self, **request): "Construct a generic request object." return WSGIRequest(self._base_environ(**request)) def _encode_data(self, data, content_type): if content_type is MULTIPART_CONTENT: return encode_multipart(BOUNDARY, data) else: # Encode the content so that the byte representation is correct. match = CONTENT_TYPE_RE.match(content_type) if match: charset = match[1] else: charset = settings.DEFAULT_CHARSET return force_bytes(data, encoding=charset) def _encode_json(self, data, content_type): """ Return encoded JSON if data is a dict, list, or tuple and content_type is application/json. """ should_encode = JSON_CONTENT_TYPE_RE.match(content_type) and isinstance( data, (dict, list, tuple) ) return json.dumps(data, cls=self.json_encoder) if should_encode else data def _get_path(self, parsed): path = unquote_to_bytes(parsed.path) # Replace the behavior where non-ASCII values in the WSGI environ are # arbitrarily decoded with ISO-8859-1. # Refs comment in `get_bytes_from_wsgi()`. return path.decode("iso-8859-1") def get( self, path, data=None, secure=False, *, headers=None, query_params=None, **extra ): """Construct a GET request.""" if query_params and data: raise ValueError("query_params and data arguments are mutually exclusive.") query_params = data or query_params query_params = {} if query_params is None else query_params return self.generic( "GET", path, secure=secure, headers=headers, query_params=query_params, **extra, ) def post( self, path, data=None, content_type=MULTIPART_CONTENT, secure=False, *, headers=None, query_params=None, **extra, ): """Construct a POST request.""" data = self._encode_json({} if data is None else data, content_type) post_data = self._encode_data(data, content_type) return self.generic( "POST", path, post_data, content_type, secure=secure, headers=headers, query_params=query_params, **extra, ) def head( self, path, data=None, secure=False, *, headers=None, query_params=None, **extra ): """Construct a HEAD request.""" if query_params and data: raise ValueError("query_params and data arguments are mutually exclusive.") query_params = data or query_params query_params = {} if query_params is None else query_params return self.generic( "HEAD", path, secure=secure, headers=headers, query_params=query_params, **extra, ) def trace(self, path, secure=False, *, headers=None, query_params=None, **extra): """Construct a TRACE request.""" return self.generic( "TRACE", path, secure=secure, headers=headers, query_params=query_params, **extra, ) def options( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): "Construct an OPTIONS request." return self.generic( "OPTIONS", path, data, content_type, secure=secure, headers=headers, query_params=query_params, **extra, ) def put( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): """Construct a PUT request.""" data = self._encode_json(data, content_type) return self.generic( "PUT", path, data, content_type, secure=secure, headers=headers, query_params=query_params, **extra, ) def patch( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): """Construct a PATCH request.""" data = self._encode_json(data, content_type) return self.generic( "PATCH", path, data, content_type, secure=secure, headers=headers, query_params=query_params, **extra, ) def delete( self, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): """Construct a DELETE request.""" data = self._encode_json(data, content_type) return self.generic( "DELETE", path, data, content_type, secure=secure, headers=headers, query_params=query_params, **extra, ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlsplit(str(path)) # path can be lazy data = force_bytes(data, settings.DEFAULT_CHARSET) r = { "PATH_INFO": self._get_path(parsed), "REQUEST_METHOD": method, "SERVER_PORT": "443" if secure else "80", "wsgi.url_scheme": "https" if secure else "http", } if data: r.update( { "CONTENT_LENGTH": str(len(data)), "CONTENT_TYPE": content_type, "wsgi.input": FakePayload(data), } ) if headers: extra.update(HttpHeaders.to_wsgi_names(headers)) if query_params: extra["QUERY_STRING"] = urlencode(query_params, doseq=True) r.update(extra) # If QUERY_STRING is absent or empty, extract it from the URL. if not r.get("QUERY_STRING"): # WSGI requires latin-1 encoded strings. See get_path_info(). r["QUERY_STRING"] = parsed.query.encode().decode("iso-8859-1") return self.request(**r) class AsyncRequestFactory(RequestFactory): """ Class that lets you create mock ASGI-like Request objects for use in testing. Usage: rf = AsyncRequestFactory() get_request = rf.get("/hello/") post_request = rf.post("/submit/", {"foo": "bar"}) Once you have a request object you can pass it to any view function, including synchronous ones. The reason we have a separate class here is: a) this makes ASGIRequest subclasses, and b) AsyncClient can subclass it. """ def _base_scope(self, **request): """The base scope for a request.""" # This is a minimal valid ASGI scope, plus: # - headers['cookie'] for cookie support, # - 'client' often useful, see #8551. scope = { "asgi": {"version": "3.0"}, "type": "http", "http_version": "1.1", "client": ["127.0.0.1", 0], "server": ("testserver", "80"), "scheme": "http", "method": "GET", "headers": [], **self.defaults, **request, } scope["headers"].append( ( b"cookie", b"; ".join( sorted( ("%s=%s" % (morsel.key, morsel.coded_value)).encode("ascii") for morsel in self.cookies.values() ) ), ) ) return scope def request(self, **request): """Construct a generic request object.""" # This is synchronous, which means all methods on this class are. # AsyncClient, however, has an async request function, which makes all # its methods async. if "_body_file" in request: body_file = request.pop("_body_file") else: body_file = FakePayload("") # Wrap FakePayload body_file to allow large read() in test environment. return ASGIRequest( self._base_scope(**request), LimitedStream(body_file, len(body_file)) ) def generic( self, method, path, data="", content_type="application/octet-stream", secure=False, *, headers=None, query_params=None, **extra, ): """Construct an arbitrary HTTP request.""" parsed = urlsplit(str(path)) # path can be lazy. data = force_bytes(data, settings.DEFAULT_CHARSET) s = { "method": method, "path": self._get_path(parsed), "server": ("127.0.0.1", "443" if secure else "80"), "scheme": "https" if secure else "http", "headers": [(b"host", b"testserver")], } if self.defaults: extra = {**self.defaults, **extra} if data: s["headers"].extend( [ (b"content-length", str(len(data)).encode("ascii")), (b"content-type", content_type.encode("ascii")), ] ) s["_body_file"] = FakePayload(data) if query_params: s["query_string"] = urlencode(query_params, doseq=True) elif query_string := extra.pop("QUERY_STRING", None): s["query_string"] = query_string else: # If QUERY_STRING is absent or empty, we want to extract it from # the URL. s["query_string"] = parsed.query if headers: extra.update(HttpHeaders.to_asgi_names(headers)) s["headers"] += [ (key.lower().encode("ascii"), value.encode("latin1")) for key, value in extra.items() ] return self.request(**s) class ClientMixin: """ Mixin with common methods between Client and AsyncClient. """ def store_exc_info(self, **kwargs): """Store exceptions when they are generated by a view.""" self.exc_info = sys.exc_info() def check_exception(self, response): """ Look for a signaled exception, clear the current context exception data, re-raise the signaled exception, and clear the signaled exception from the local cache. """ response.exc_info = self.exc_info if self.exc_info: _, exc_value, _ = self.exc_info self.exc_info = None if self.raise_request_exception: raise exc_value @property def session(self): """Return the current session variables.""" engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() session.save() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session async def asession(self): engine = import_module(settings.SESSION_ENGINE) cookie = self.cookies.get(settings.SESSION_COOKIE_NAME) if cookie: return engine.SessionStore(cookie.value) session = engine.SessionStore() await session.asave() self.cookies[settings.SESSION_COOKIE_NAME] = session.session_key return session def login(self, **credentials): """ Set the Factory to appear as if it has successfully logged into a site. Return True if login is possible or False if the provided credentials are incorrect. """ from django.contrib.auth import authenticate user = authenticate(**credentials) if user: self._login(user) return True return False async def alogin(self, **credentials): """See login().""" from django.contrib.auth import aauthenticate user = await aauthenticate(**credentials) if user: await self._alogin(user) return True return False def force_login(self, user, backend=None): if backend is None: backend = self._get_backend() user.backend = backend self._login(user, backend) async def aforce_login(self, user, backend=None): if backend is None: backend = self._get_backend() user.backend = backend await self._alogin(user, backend) def _get_backend(self): from django.contrib.auth import load_backend for backend_path in settings.AUTHENTICATION_BACKENDS: backend = load_backend(backend_path) if hasattr(backend, "get_user"): return backend_path def _login(self, user, backend=None): from django.contrib.auth import login # Create a fake request to store login details. request = HttpRequest() if self.session: request.session = self.session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() login(request, user, backend) # Save the session values. request.session.save() self._set_login_cookies(request) async def _alogin(self, user, backend=None): from django.contrib.auth import alogin # Create a fake request to store login details. request = HttpRequest() session = await self.asession() if session: request.session = session else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() await alogin(request, user, backend) # Save the session values. await request.session.asave() self._set_login_cookies(request) def _set_login_cookies(self, request): # Set the cookie to represent the session. session_cookie = settings.SESSION_COOKIE_NAME self.cookies[session_cookie] = request.session.session_key cookie_data = { "max-age": None, "path": "/", "domain": settings.SESSION_COOKIE_DOMAIN, "secure": settings.SESSION_COOKIE_SECURE or None, "expires": None, } self.cookies[session_cookie].update(cookie_data) def logout(self): """Log out the user by removing the cookies and session object.""" from django.contrib.auth import get_user, logout request = HttpRequest() if self.session: request.session = self.session request.user = get_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() logout(request) self.cookies = SimpleCookie() async def alogout(self): """See logout().""" from django.contrib.auth import aget_user, alogout request = HttpRequest() session = await self.asession() if session: request.session = session request.user = await aget_user(request) else: engine = import_module(settings.SESSION_ENGINE) request.session = engine.SessionStore() await alogout(request) self.cookies = SimpleCookie() def _parse_json(self, response, **extra): if not hasattr(response, "_json"): if not JSON_CONTENT_TYPE_RE.match(response.get("Content-Type")): raise ValueError( 'Content-Type header is "%s", not "application/json"' % response.get("Content-Type") ) response._json = json.loads(response.text, **extra) return response._json def _follow_redirect( self, response, *, data="", content_type="", headers=None, query_params=None, **extra, ): """Follow a single redirect contained in response using GET.""" response_url = response.url redirect_chain = response.redirect_chain redirect_chain.append((response_url, response.status_code)) url = urlsplit(response_url) if url.scheme: extra["wsgi.url_scheme"] = url.scheme if url.hostname: extra["SERVER_NAME"] = url.hostname extra["HTTP_HOST"] = url.hostname if url.port: extra["SERVER_PORT"] = str(url.port) path = url.path # RFC 3986 Section 6.2.3: Empty path should be normalized to "/". if not path and url.netloc: path = "/" # Prepend the request path to handle relative path redirects if not path.startswith("/"): path = urljoin(response.request["PATH_INFO"], path)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/runner.py
django/test/runner.py
import argparse import ctypes import faulthandler import functools import hashlib import io import itertools import logging import multiprocessing import os import pickle import random import sys import textwrap import unittest import unittest.suite from collections import defaultdict from contextlib import contextmanager from importlib import import_module import django from django.core.management import call_command from django.db import connections from django.test import SimpleTestCase, TestCase from django.test.utils import NullTimeKeeper, TimeKeeper, iter_test_cases from django.test.utils import setup_databases as _setup_databases from django.test.utils import setup_test_environment from django.test.utils import teardown_databases as _teardown_databases from django.test.utils import teardown_test_environment from django.utils.datastructures import OrderedSet from django.utils.version import PY313 try: import ipdb as pdb except ImportError: import pdb try: import tblib.pickling_support except ImportError: tblib = None class QueryFormatter(logging.Formatter): def format(self, record): if (alias := getattr(record, "alias", None)) in connections: format_sql = connections[alias].ops.format_debug_sql sql = None formatted_sql = None if args := record.args: if isinstance(args, tuple) and len(args) > 1 and (sql := args[1]): record.args = (args[0], formatted_sql := format_sql(sql), *args[2:]) elif isinstance(record.args, dict) and (sql := record.args.get("sql")): record.args["sql"] = formatted_sql = format_sql(sql) if extra_sql := getattr(record, "sql", None): if extra_sql == sql: record.sql = formatted_sql else: record.sql = format_sql(extra_sql) return super().format(record) class DebugSQLTextTestResult(unittest.TextTestResult): def __init__(self, stream, descriptions, verbosity): self.logger = logging.getLogger("django.db.backends") self.logger.setLevel(logging.DEBUG) self.handler = None super().__init__(stream, descriptions, verbosity) def _read_logger_stream(self): if self.handler is None: # Error before tests e.g. in setUpTestData(). sql = "" else: self.handler.stream.seek(0) sql = self.handler.stream.read() return sql def startTest(self, test): self.handler = logging.StreamHandler(io.StringIO()) self.handler.setFormatter(QueryFormatter()) self.logger.addHandler(self.handler) super().startTest(test) def stopTest(self, test): super().stopTest(test) self.logger.removeHandler(self.handler) if self.showAll: self.stream.write(self._read_logger_stream()) self.stream.writeln(self.separator2) def addError(self, test, err): super().addError(test, err) self.errors[-1] = self.errors[-1] + (self._read_logger_stream(),) def addFailure(self, test, err): super().addFailure(test, err) self.failures[-1] = self.failures[-1] + (self._read_logger_stream(),) def addSubTest(self, test, subtest, err): super().addSubTest(test, subtest, err) if err is not None: errors = ( self.failures if issubclass(err[0], test.failureException) else self.errors ) errors[-1] = errors[-1] + (self._read_logger_stream(),) def printErrorList(self, flavour, errors): for test, err, sql_debug in errors: self.stream.writeln(self.separator1) self.stream.writeln("%s: %s" % (flavour, self.getDescription(test))) self.stream.writeln(self.separator2) self.stream.writeln(err) self.stream.writeln(self.separator2) self.stream.writeln(sql_debug) class PDBDebugResult(unittest.TextTestResult): """ Custom result class that triggers a PDB session when an error or failure occurs. """ def addError(self, test, err): super().addError(test, err) self.debug(err) def addFailure(self, test, err): super().addFailure(test, err) self.debug(err) def addSubTest(self, test, subtest, err): if err is not None: self.debug(err) super().addSubTest(test, subtest, err) def debug(self, error): self._restoreStdout() self.buffer = False exc_type, exc_value, traceback = error print("\nOpening PDB: %r" % exc_value) if PY313: pdb.post_mortem(exc_value) else: pdb.post_mortem(traceback) class DummyList: """ Dummy list class for faking storage of results in unittest.TestResult. """ __slots__ = () def append(self, item): pass class RemoteTestResult(unittest.TestResult): """ Extend unittest.TestResult to record events in the child processes so they can be replayed in the parent process. Events include things like which tests succeeded or failed. """ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) # Fake storage of results to reduce memory usage. These are used by the # unittest default methods, but here 'events' is used instead. dummy_list = DummyList() self.failures = dummy_list self.errors = dummy_list self.skipped = dummy_list self.expectedFailures = dummy_list self.unexpectedSuccesses = dummy_list if tblib is not None: tblib.pickling_support.install() self.events = [] def __getstate__(self): # Make this class picklable by removing the file-like buffer # attributes. This is possible since they aren't used after unpickling # after being sent to ParallelTestSuite. state = self.__dict__.copy() state.pop("_stdout_buffer", None) state.pop("_stderr_buffer", None) state.pop("_original_stdout", None) state.pop("_original_stderr", None) return state @property def test_index(self): return self.testsRun - 1 def _confirm_picklable(self, obj): """ Confirm that obj can be pickled and unpickled as multiprocessing will need to pickle the exception in the child process and unpickle it in the parent process. Let the exception rise, if not. """ pickle.loads(pickle.dumps(obj)) def _print_unpicklable_subtest(self, test, subtest, pickle_exc): print( """ Subtest failed: test: {} subtest: {} Unfortunately, the subtest that failed cannot be pickled, so the parallel test runner cannot handle it cleanly. Here is the pickling error: > {} You should re-run this test with --parallel=1 to reproduce the failure with a cleaner failure message. """.format( test, subtest, pickle_exc ) ) def check_picklable(self, test, err): # Ensure that sys.exc_info() tuples are picklable. This displays a # clear multiprocessing.pool.RemoteTraceback generated in the child # process instead of a multiprocessing.pool.MaybeEncodingError, making # the root cause easier to figure out for users who aren't familiar # with the multiprocessing module. Since we're in a forked process, # our best chance to communicate with them is to print to stdout. try: self._confirm_picklable(err) except Exception as exc: original_exc_txt = repr(err[1]) original_exc_txt = textwrap.fill( original_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) pickle_exc_txt = repr(exc) pickle_exc_txt = textwrap.fill( pickle_exc_txt, 75, initial_indent=" ", subsequent_indent=" " ) if tblib is None: print( """ {} failed: {} Unfortunately, tracebacks cannot be pickled, making it impossible for the parallel test runner to handle this exception cleanly. In order to see the traceback, you should install tblib: python -m pip install tblib """.format( test, original_exc_txt ) ) else: print( """ {} failed: {} Unfortunately, the exception it raised cannot be pickled, making it impossible for the parallel test runner to handle it cleanly. Here's the error encountered while trying to pickle the exception: {} You should re-run this test with the --parallel=1 option to reproduce the failure and get a correct traceback. """.format( test, original_exc_txt, pickle_exc_txt ) ) raise def check_subtest_picklable(self, test, subtest): try: self._confirm_picklable(subtest) except Exception as exc: self._print_unpicklable_subtest(test, subtest, exc) raise def startTestRun(self): super().startTestRun() self.events.append(("startTestRun",)) def stopTestRun(self): super().stopTestRun() self.events.append(("stopTestRun",)) def startTest(self, test): super().startTest(test) self.events.append(("startTest", self.test_index)) def stopTest(self, test): super().stopTest(test) self.events.append(("stopTest", self.test_index)) def addDuration(self, test, elapsed): super().addDuration(test, elapsed) self.events.append(("addDuration", self.test_index, elapsed)) def addError(self, test, err): self.check_picklable(test, err) event_occurred_before_first_test = self.test_index == -1 if event_occurred_before_first_test and isinstance( test, unittest.suite._ErrorHolder ): self.events.append(("addError", self.test_index, test.id(), err)) else: self.events.append(("addError", self.test_index, err)) super().addError(test, err) def addFailure(self, test, err): self.check_picklable(test, err) self.events.append(("addFailure", self.test_index, err)) super().addFailure(test, err) def addSubTest(self, test, subtest, err): # Follow Python's implementation of unittest.TestResult.addSubTest() by # not doing anything when a subtest is successful. if err is not None: # Call check_picklable() before check_subtest_picklable() since # check_picklable() performs the tblib check. self.check_picklable(test, err) self.check_subtest_picklable(test, subtest) self.events.append(("addSubTest", self.test_index, subtest, err)) super().addSubTest(test, subtest, err) def addSuccess(self, test): self.events.append(("addSuccess", self.test_index)) super().addSuccess(test) def addSkip(self, test, reason): self.events.append(("addSkip", self.test_index, reason)) super().addSkip(test, reason) def addExpectedFailure(self, test, err): # If tblib isn't installed, pickling the traceback will always fail. # However we don't want tblib to be required for running the tests # when they pass or fail as expected. Drop the traceback when an # expected failure occurs. if tblib is None: err = err[0], err[1], None self.check_picklable(test, err) self.events.append(("addExpectedFailure", self.test_index, err)) super().addExpectedFailure(test, err) def addUnexpectedSuccess(self, test): self.events.append(("addUnexpectedSuccess", self.test_index)) super().addUnexpectedSuccess(test) def wasSuccessful(self): """Tells whether or not this result was a success.""" failure_types = {"addError", "addFailure", "addSubTest", "addUnexpectedSuccess"} return all(e[0] not in failure_types for e in self.events) def _exc_info_to_string(self, err, test): # Make this method no-op. It only powers the default unittest behavior # for recording errors, but this class pickles errors into 'events' # instead. return "" class RemoteTestRunner: """ Run tests and record everything but don't display anything. The implementation matches the unpythonic coding style of unittest2. """ resultclass = RemoteTestResult def __init__(self, failfast=False, resultclass=None, buffer=False): self.failfast = failfast self.buffer = buffer if resultclass is not None: self.resultclass = resultclass def run(self, test): result = self.resultclass() unittest.registerResult(result) result.failfast = self.failfast result.buffer = self.buffer test(result) return result def get_max_test_processes(): """ The maximum number of test processes when using the --parallel option. """ # The current implementation of the parallel test runner requires # multiprocessing to start subprocesses with fork(), forkserver(), or # spawn(). if multiprocessing.get_start_method() not in {"fork", "spawn", "forkserver"}: return 1 try: return int(os.environ["DJANGO_TEST_PROCESSES"]) except KeyError: return multiprocessing.cpu_count() def parallel_type(value): """Parse value passed to the --parallel option.""" if value == "auto": return value try: return int(value) except ValueError: raise argparse.ArgumentTypeError( f"{value!r} is not an integer or the string 'auto'" ) _worker_id = 0 def _init_worker( counter, initial_settings=None, serialized_contents=None, process_setup=None, process_setup_args=None, debug_mode=None, used_aliases=None, ): """ Switch to databases dedicated to this worker and run system checks. This helper lives at module-level because of the multiprocessing module's requirements. """ global _worker_id with counter.get_lock(): counter.value += 1 _worker_id = counter.value is_spawn_or_forkserver = multiprocessing.get_start_method() in { "forkserver", "spawn", } if is_spawn_or_forkserver: if process_setup and callable(process_setup): if process_setup_args is None: process_setup_args = () process_setup(*process_setup_args) django.setup() setup_test_environment(debug=debug_mode) db_aliases = used_aliases if used_aliases is not None else connections for alias in db_aliases: connection = connections[alias] if is_spawn_or_forkserver: # Restore initial settings in spawned processes. connection.settings_dict.update(initial_settings[alias]) if value := serialized_contents.get(alias): connection._test_serialized_contents = value connection.creation.setup_worker_connection(_worker_id) if ( is_spawn_or_forkserver and os.environ.get("RUNNING_DJANGOS_TEST_SUITE") == "true" ): connection.creation.mark_expected_failures_and_skips() if is_spawn_or_forkserver: call_command( "check", stdout=io.StringIO(), stderr=io.StringIO(), databases=used_aliases ) def _safe_init_worker(init_worker, counter, *args, **kwargs): try: init_worker(counter, *args, **kwargs) except Exception: with counter.get_lock(): # Set a value that will not increment above zero any time soon. counter.value = -1000 raise def _run_subsuite(args): """ Run a suite of tests with a RemoteTestRunner and return a RemoteTestResult. This helper lives at module-level and its arguments are wrapped in a tuple because of the multiprocessing module's requirements. """ runner_class, subsuite_index, subsuite, failfast, buffer = args runner = runner_class(failfast=failfast, buffer=buffer) result = runner.run(subsuite) return subsuite_index, result.events def _process_setup_stub(*args): """Stub method to simplify run() implementation.""" pass class ParallelTestSuite(unittest.TestSuite): """ Run a series of tests in parallel in several processes. While the unittest module's documentation implies that orchestrating the execution of tests is the responsibility of the test runner, in practice, it appears that TestRunner classes are more concerned with formatting and displaying test results. Since there are fewer use cases for customizing TestSuite than TestRunner, implementing parallelization at the level of the TestSuite improves interoperability with existing custom test runners. A single instance of a test runner can still collect results from all tests without being aware that they have been run in parallel. """ # In case someone wants to modify these in a subclass. init_worker = _init_worker process_setup = _process_setup_stub process_setup_args = () run_subsuite = _run_subsuite runner_class = RemoteTestRunner def __init__( self, subsuites, processes, failfast=False, debug_mode=False, buffer=False ): self.subsuites = subsuites self.processes = processes self.failfast = failfast self.debug_mode = debug_mode self.buffer = buffer self.initial_settings = None self.serialized_contents = None self.used_aliases = None super().__init__() def run(self, result): """ Distribute TestCases across workers. Return an identifier of each TestCase with its result in order to use imap_unordered to show results as soon as they're available. To minimize pickling errors when getting results from workers: - pass back numeric indexes in self.subsuites instead of tests - make tracebacks picklable with tblib, if available Even with tblib, errors may still occur for dynamically created exception classes which cannot be unpickled. """ self.initialize_suite() counter = multiprocessing.Value(ctypes.c_int, 0) args = [ (self.runner_class, index, subsuite, self.failfast, self.buffer) for index, subsuite in enumerate(self.subsuites) ] # Don't buffer in the main process to avoid error propagation issues. result.buffer = False with multiprocessing.Pool( processes=self.processes, initializer=functools.partial(_safe_init_worker, self.init_worker.__func__), initargs=[ counter, self.initial_settings, self.serialized_contents, self.process_setup.__func__, self.process_setup_args, self.debug_mode, self.used_aliases, ], ) as pool: test_results = pool.imap_unordered(self.run_subsuite.__func__, args) while True: if result.shouldStop: pool.terminate() break try: subsuite_index, events = test_results.next(timeout=0.1) except multiprocessing.TimeoutError as err: if counter.value < 0: err.add_note("ERROR: _init_worker failed, see prior traceback") raise continue except StopIteration: pool.close() break tests = list(self.subsuites[subsuite_index]) for event in events: self.handle_event(result, tests, event) pool.join() return result def handle_event(self, result, tests, event): event_name = event[0] handler = getattr(result, event_name, None) if handler is None: return test_index = event[1] event_occurred_before_first_test = test_index == -1 if ( event_name == "addError" and event_occurred_before_first_test and len(event) >= 4 ): test_id = event[2] test = unittest.suite._ErrorHolder(test_id) args = event[3:] else: test = tests[test_index] args = event[2:] handler(test, *args) def __iter__(self): return iter(self.subsuites) def initialize_suite(self): if multiprocessing.get_start_method() in {"forkserver", "spawn"}: self.initial_settings = { alias: connections[alias].settings_dict for alias in connections } self.serialized_contents = { alias: connections[alias]._test_serialized_contents for alias in connections if alias in self.serialized_aliases } class Shuffler: """ This class implements shuffling with a special consistency property. Consistency means that, for a given seed and key function, if two sets of items are shuffled, the resulting order will agree on the intersection of the two sets. For example, if items are removed from an original set, the shuffled order for the new set will be the shuffled order of the original set restricted to the smaller set. """ # This doesn't need to be cryptographically strong, so use what's fastest. hash_algorithm = "md5" @classmethod def _hash_text(cls, text): h = hashlib.new(cls.hash_algorithm, usedforsecurity=False) h.update(text.encode("utf-8")) return h.hexdigest() def __init__(self, seed=None): if seed is None: # Limit seeds to 10 digits for simpler output. seed = random.randint(0, 10**10 - 1) seed_source = "generated" else: seed_source = "given" self.seed = seed self.seed_source = seed_source @property def seed_display(self): return f"{self.seed!r} ({self.seed_source})" def _hash_item(self, item, key): text = "{}{}".format(self.seed, key(item)) return self._hash_text(text) def shuffle(self, items, key): """ Return a new list of the items in a shuffled order. The `key` is a function that accepts an item in `items` and returns a string unique for that item that can be viewed as a string id. The order of the return value is deterministic. It depends on the seed and key function but not on the original order. """ hashes = {} for item in items: hashed = self._hash_item(item, key) if hashed in hashes: msg = "item {!r} has same hash {!r} as item {!r}".format( item, hashed, hashes[hashed], ) raise RuntimeError(msg) hashes[hashed] = item return [hashes[hashed] for hashed in sorted(hashes)] class DiscoverRunner: """A Django test runner that uses unittest2 test discovery.""" test_suite = unittest.TestSuite parallel_test_suite = ParallelTestSuite test_runner = unittest.TextTestRunner test_loader = unittest.defaultTestLoader reorder_by = (TestCase, SimpleTestCase) def __init__( self, pattern=None, top_level=None, verbosity=1, interactive=True, failfast=False, keepdb=False, reverse=False, debug_mode=False, debug_sql=False, parallel=0, tags=None, exclude_tags=None, test_name_patterns=None, pdb=False, buffer=False, enable_faulthandler=True, timing=False, shuffle=False, logger=None, durations=None, **kwargs, ): self.pattern = pattern self.top_level = top_level self.verbosity = verbosity self.interactive = interactive self.failfast = failfast self.keepdb = keepdb self.reverse = reverse self.debug_mode = debug_mode self.debug_sql = debug_sql self.parallel = parallel self.tags = set(tags or []) self.exclude_tags = set(exclude_tags or []) if not faulthandler.is_enabled() and enable_faulthandler: try: faulthandler.enable(file=sys.stderr.fileno()) except (AttributeError, io.UnsupportedOperation): faulthandler.enable(file=sys.__stderr__.fileno()) self.pdb = pdb if self.pdb and self.parallel > 1: raise ValueError( "You cannot use --pdb with parallel tests; pass --parallel=1 to use it." ) self.buffer = buffer self.test_name_patterns = None self.time_keeper = TimeKeeper() if timing else NullTimeKeeper() if test_name_patterns: # unittest does not export the _convert_select_pattern function # that converts command-line arguments to patterns. self.test_name_patterns = { pattern if "*" in pattern else "*%s*" % pattern for pattern in test_name_patterns } self.shuffle = shuffle self._shuffler = None self.logger = logger self.durations = durations @classmethod def add_arguments(cls, parser): parser.add_argument( "--failfast", action="store_true", help="Stops the test suite after the first failure.", ) parser.add_argument( "-t", "--top-level-directory", dest="top_level", help="Top level of project for unittest discovery.", ) parser.add_argument( "-p", "--pattern", default="test*.py", help="The test matching pattern. Defaults to test*.py.", ) parser.add_argument( "--keepdb", action="store_true", help="Preserves the test DB between runs." ) parser.add_argument( "--shuffle", nargs="?", default=False, type=int, metavar="SEED", help="Shuffles test case order.", ) parser.add_argument( "-r", "--reverse", action="store_true", help="Reverses test case order.", ) parser.add_argument( "--debug-mode", action="store_true", help="Sets settings.DEBUG to True.", ) parser.add_argument( "-d", "--debug-sql", action="store_true", help="Prints logged SQL queries on failure.", ) parser.add_argument( "--parallel", nargs="?", const="auto", default=0, type=parallel_type, metavar="N", help=( "Run tests using up to N parallel processes. Use the value " '"auto" to run one test process for each processor core.' ), ) parser.add_argument( "--tag", action="append", dest="tags", help="Run only tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--exclude-tag", action="append", dest="exclude_tags", help="Do not run tests with the specified tag. Can be used multiple times.", ) parser.add_argument( "--pdb", action="store_true", help="Runs a debugger (pdb, or ipdb if installed) on error or failure.", ) parser.add_argument( "-b", "--buffer", action="store_true", help="Discard output from passing tests.", ) parser.add_argument( "--no-faulthandler", action="store_false", dest="enable_faulthandler", help="Disables the Python faulthandler module during tests.", ) parser.add_argument( "--timing", action="store_true", help=("Output timings, including database set up and total run time."), ) parser.add_argument( "-k", action="append", dest="test_name_patterns", help=( "Only run test methods and classes that match the pattern " "or substring. Can be used multiple times. Same as " "unittest -k option." ), ) parser.add_argument( "--durations", dest="durations", type=int, default=None, metavar="N", help="Show the N slowest test cases (N=0 for all).", ) @property def shuffle_seed(self): if self._shuffler is None: return None return self._shuffler.seed def log(self, msg, level=None): """ Log the message at the given logging level (the default is INFO). If a logger isn't set, the message is instead printed to the console, respecting the configured verbosity. A verbosity of 0 prints no output, a verbosity of 1 prints INFO and above, and a verbosity of 2 or higher prints all levels. """ if level is None: level = logging.INFO if self.logger is None: if self.verbosity <= 0 or (self.verbosity == 1 and level < logging.INFO): return print(msg) else: self.logger.log(level, msg) def setup_test_environment(self, **kwargs): setup_test_environment(debug=self.debug_mode) unittest.installHandler() def setup_shuffler(self): if self.shuffle is False: return shuffler = Shuffler(seed=self.shuffle) self.log(f"Using shuffle seed: {shuffler.seed_display}") self._shuffler = shuffler @contextmanager def load_with_patterns(self): original_test_name_patterns = self.test_loader.testNamePatterns self.test_loader.testNamePatterns = self.test_name_patterns try: yield finally: # Restore the original patterns. self.test_loader.testNamePatterns = original_test_name_patterns def load_tests_for_label(self, label, discover_kwargs): label_as_path = os.path.abspath(label) tests = None # If a module, or "module.ClassName[.method_name]", just run those. if not os.path.exists(label_as_path): with self.load_with_patterns(): tests = self.test_loader.loadTestsFromName(label) if tests.countTestCases(): return tests # Try discovery if "label" is a package or directory. is_importable, is_package = try_importing(label) if is_importable: if not is_package: return tests elif not os.path.isdir(label_as_path): if os.path.exists(label_as_path): assert tests is None raise RuntimeError( f"One of the test labels is a path to a file: {label!r}, " f"which is not supported. Use a dotted module name or " f"path to a directory instead." ) return tests kwargs = discover_kwargs.copy() if os.path.isdir(label_as_path) and not self.top_level: kwargs["top_level_dir"] = find_top_level(label_as_path) with self.load_with_patterns(): tests = self.test_loader.discover(start_dir=label, **kwargs) # Make unittest forget the top-level dir it calculated from this run, # to support running tests from two different top-levels. self.test_loader._top_level_dir = None return tests def build_suite(self, test_labels=None, **kwargs): test_labels = test_labels or ["."] discover_kwargs = {} if self.pattern is not None: discover_kwargs["pattern"] = self.pattern if self.top_level is not None:
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/html.py
django/test/html.py
"""Compare two HTML documents.""" import html from html.parser import HTMLParser from django.utils.html import VOID_ELEMENTS from django.utils.regex_helper import _lazy_re_compile # ASCII whitespace is U+0009 TAB, U+000A LF, U+000C FF, U+000D CR, or U+0020 # SPACE. # https://infra.spec.whatwg.org/#ascii-whitespace ASCII_WHITESPACE = _lazy_re_compile(r"[\t\n\f\r ]+") # https://html.spec.whatwg.org/#attributes-3 BOOLEAN_ATTRIBUTES = { "allowfullscreen", "async", "autofocus", "autoplay", "checked", "controls", "default", "defer ", "disabled", "formnovalidate", "hidden", "ismap", "itemscope", "loop", "multiple", "muted", "nomodule", "novalidate", "open", "playsinline", "readonly", "required", "reversed", "selected", # Attributes for deprecated tags. "truespeed", } def normalize_whitespace(string): return ASCII_WHITESPACE.sub(" ", string) def normalize_attributes(attributes): normalized = [] for name, value in attributes: if name == "class" and value: # Special case handling of 'class' attribute, so that comparisons # of DOM instances are not sensitive to ordering of classes. value = " ".join( sorted(value for value in ASCII_WHITESPACE.split(value) if value) ) # Boolean attributes without a value is same as attribute with value # that equals the attributes name. For example: # <input checked> == <input checked="checked"> if name in BOOLEAN_ATTRIBUTES: if not value or value == name: value = None elif value is None: value = "" normalized.append((name, value)) return normalized class Element: def __init__(self, name, attributes): self.name = name self.attributes = sorted(attributes) self.children = [] def append(self, element): if isinstance(element, str): element = normalize_whitespace(element) if self.children and isinstance(self.children[-1], str): self.children[-1] += element self.children[-1] = normalize_whitespace(self.children[-1]) return elif self.children: # removing last children if it is only whitespace # this can result in incorrect dom representations since # whitespace between inline tags like <span> is significant if isinstance(self.children[-1], str) and self.children[-1].isspace(): self.children.pop() if element: self.children.append(element) def finalize(self): def rstrip_last_element(children): if children and isinstance(children[-1], str): children[-1] = children[-1].rstrip() if not children[-1]: children.pop() children = rstrip_last_element(children) return children rstrip_last_element(self.children) for i, child in enumerate(self.children): if isinstance(child, str): self.children[i] = child.strip() elif hasattr(child, "finalize"): child.finalize() def __eq__(self, element): if not hasattr(element, "name") or self.name != element.name: return False if self.attributes != element.attributes: return False return self.children == element.children def __hash__(self): return hash((self.name, *self.attributes)) def _count(self, element, count=True): if not isinstance(element, str) and self == element: return 1 if isinstance(element, RootElement) and self.children == element.children: return 1 i = 0 elem_child_idx = 0 for child in self.children: # child is text content and element is also text content, then # make a simple "text" in "text" if isinstance(child, str): if isinstance(element, str): if count: i += child.count(element) elif element in child: return 1 else: # Look for element wholly within this child. i += child._count(element, count=count) if not count and i: return i # Also look for a sequence of element's children among self's # children. self.children == element.children is tested above, # but will fail if self has additional children. Ex: '<a/><b/>' # is contained in '<a/><b/><c/>'. if isinstance(element, RootElement) and element.children: elem_child = element.children[elem_child_idx] # Start or continue match, advance index. if elem_child == child: elem_child_idx += 1 # Match found, reset index. if elem_child_idx == len(element.children): i += 1 elem_child_idx = 0 # No match, reset index. else: elem_child_idx = 0 return i def __contains__(self, element): return self._count(element, count=False) > 0 def count(self, element): return self._count(element, count=True) def __getitem__(self, key): return self.children[key] def __str__(self): output = "<%s" % self.name for key, value in self.attributes: if value is not None: output += ' %s="%s"' % (key, value) else: output += " %s" % key if self.children: output += ">\n" output += "".join( [ html.escape(c) if isinstance(c, str) else str(c) for c in self.children ] ) output += "\n</%s>" % self.name else: output += ">" return output def __repr__(self): return str(self) class RootElement(Element): def __init__(self): super().__init__(None, ()) def __str__(self): return "".join( [html.escape(c) if isinstance(c, str) else str(c) for c in self.children] ) class HTMLParseError(Exception): pass class Parser(HTMLParser): def __init__(self): super().__init__() self.root = RootElement() self.open_tags = [] self.element_positions = {} def error(self, msg): raise HTMLParseError(msg, self.getpos()) def format_position(self, position=None, element=None): if not position and element: position = self.element_positions[element] if position is None: position = self.getpos() if hasattr(position, "lineno"): position = position.lineno, position.offset return "Line %d, Column %d" % position @property def current(self): if self.open_tags: return self.open_tags[-1] else: return self.root def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) if tag not in VOID_ELEMENTS: self.handle_endtag(tag) def handle_starttag(self, tag, attrs): attrs = normalize_attributes(attrs) element = Element(tag, attrs) self.current.append(element) if tag not in VOID_ELEMENTS: self.open_tags.append(element) self.element_positions[element] = self.getpos() def handle_endtag(self, tag): if not self.open_tags: self.error("Unexpected end tag `%s` (%s)" % (tag, self.format_position())) element = self.open_tags.pop() while element.name != tag: if not self.open_tags: self.error( "Unexpected end tag `%s` (%s)" % (tag, self.format_position()) ) element = self.open_tags.pop() def handle_data(self, data): self.current.append(data) def parse_html(html): """ Take a string that contains HTML and turn it into a Python object structure that can be easily compared against other HTML on semantic equivalence. Syntactical differences like which quotation is used on arguments will be ignored. """ parser = Parser() parser.feed(html) parser.close() document = parser.root document.finalize() # Removing ROOT element if it's not necessary if len(document.children) == 1 and not isinstance(document.children[0], str): document = document.children[0] return document
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/selenium.py
django/test/selenium.py
import sys import unittest from contextlib import contextmanager from functools import wraps from pathlib import Path from django.conf import settings from django.test import LiveServerTestCase, override_settings, tag from django.utils.functional import classproperty from django.utils.module_loading import import_string from django.utils.text import capfirst class SeleniumTestCaseBase(type(LiveServerTestCase)): # List of browsers to dynamically create test classes for. browsers = [] # A selenium hub URL to test against. selenium_hub = None # The external host Selenium Hub can reach. external_host = None # Sentinel value to differentiate browser-specific instances. browser = None # Run browsers in headless mode. headless = False def __new__(cls, name, bases, attrs): """ Dynamically create new classes and add them to the test module when multiple browsers specs are provided (e.g. --selenium=firefox,chrome). """ test_class = super().__new__(cls, name, bases, attrs) # If the test class is either browser-specific or a test base, return # it. if test_class.browser or not any( name.startswith("test") and callable(value) for name, value in attrs.items() ): return test_class elif test_class.browsers: # Reuse the created test class to make it browser-specific. # We can't rename it to include the browser name or create a # subclass like we do with the remaining browsers as it would # either duplicate tests or prevent pickling of its instances. first_browser = test_class.browsers[0] test_class.browser = first_browser # Listen on an external interface if using a selenium hub. host = test_class.host if not test_class.selenium_hub else "0.0.0.0" test_class.host = host test_class.external_host = cls.external_host # Create subclasses for each of the remaining browsers and expose # them through the test's module namespace. module = sys.modules[test_class.__module__] for browser in test_class.browsers[1:]: browser_test_class = cls.__new__( cls, "%s%s" % (capfirst(browser), name), (test_class,), { "browser": browser, "host": host, "external_host": cls.external_host, "__module__": test_class.__module__, }, ) setattr(module, browser_test_class.__name__, browser_test_class) return test_class # If no browsers were specified, skip this class (it'll still be # discovered). return unittest.skip("No browsers specified.")(test_class) @classmethod def import_webdriver(cls, browser): return import_string("selenium.webdriver.%s.webdriver.WebDriver" % browser) @classmethod def import_options(cls, browser): return import_string("selenium.webdriver.%s.options.Options" % browser) @classmethod def get_capability(cls, browser): from selenium.webdriver.common.desired_capabilities import DesiredCapabilities caps = getattr(DesiredCapabilities, browser.upper()) if browser == "chrome": caps["goog:loggingPrefs"] = {"browser": "ALL"} return caps def create_options(self): options = self.import_options(self.browser)() if self.browser == "chrome": # Disable Google Password Manager "Data Breach" alert pop-ups. options.add_argument("--guest") options.add_argument("--disable-infobars") if self.headless: match self.browser: case "chrome" | "edge": options.add_argument("--headless=new") case "firefox": options.add_argument("-headless") return options def create_webdriver(self): options = self.create_options() if self.selenium_hub: from selenium import webdriver for key, value in self.get_capability(self.browser).items(): options.set_capability(key, value) return webdriver.Remote(command_executor=self.selenium_hub, options=options) return self.import_webdriver(self.browser)(options=options) class ChangeWindowSize: def __init__(self, width, height, selenium): self.selenium = selenium self.new_size = (width, height) def __enter__(self): self.old_size = self.selenium.get_window_size() self.selenium.set_window_size(*self.new_size) return self def __exit__(self, exc_type, exc_value, traceback): self.selenium.set_window_size(self.old_size["width"], self.old_size["height"]) @tag("selenium") class SeleniumTestCase(LiveServerTestCase, metaclass=SeleniumTestCaseBase): implicit_wait = 10 external_host = None screenshots = False @classmethod def __init_subclass__(cls, **kwargs): super().__init_subclass__(**kwargs) if not cls.screenshots: return for name, func in list(cls.__dict__.items()): if not hasattr(func, "_screenshot_cases"): continue # Remove the main test. delattr(cls, name) # Add separate tests for each screenshot type. for screenshot_case in getattr(func, "_screenshot_cases"): @wraps(func) def test(self, *args, _func=func, _case=screenshot_case, **kwargs): with getattr(self, _case)(): return _func(self, *args, **kwargs) test.__name__ = f"{name}_{screenshot_case}" test.__qualname__ = f"{test.__qualname__}_{screenshot_case}" test._screenshot_name = name test._screenshot_case = screenshot_case setattr(cls, test.__name__, test) @classproperty def live_server_url(cls): return "http://%s:%s" % (cls.external_host or cls.host, cls.server_thread.port) @classproperty def allowed_host(cls): return cls.external_host or cls.host @classmethod def setUpClass(cls): cls.selenium = cls.create_webdriver() cls.selenium.implicitly_wait(cls.implicit_wait) super().setUpClass() cls.addClassCleanup(cls._quit_selenium) @contextmanager def desktop_size(self): with ChangeWindowSize(1280, 720, self.selenium): yield @contextmanager def small_screen_size(self): with ChangeWindowSize(1024, 768, self.selenium): yield @contextmanager def mobile_size(self): with ChangeWindowSize(360, 800, self.selenium): yield @contextmanager def rtl(self): with self.desktop_size(): with override_settings(LANGUAGE_CODE=settings.LANGUAGES_BIDI[-1]): yield @contextmanager def dark(self): # Navigate to a page before executing a script. self.selenium.get(self.live_server_url) self.selenium.execute_script("localStorage.setItem('theme', 'dark');") with self.desktop_size(): try: yield finally: self.selenium.execute_script("localStorage.removeItem('theme');") def set_emulated_media(self, *, media=None, features=None): if self.browser not in {"chrome", "edge"}: self.skipTest( "Emulation.setEmulatedMedia is only supported on Chromium and " "Chrome-based browsers. See https://chromedevtools.github.io/devtools-" "protocol/1-3/Emulation/#method-setEmulatedMedia for more details." ) params = {} if media is not None: params["media"] = media if features is not None: params["features"] = features # Not using .execute_cdp_cmd() as it isn't supported by the remote web # driver when using --selenium-hub. self.selenium.execute( driver_command="executeCdpCommand", params={"cmd": "Emulation.setEmulatedMedia", "params": params}, ) @contextmanager def high_contrast(self): self.set_emulated_media(features=[{"name": "forced-colors", "value": "active"}]) with self.desktop_size(): try: yield finally: self.set_emulated_media( features=[{"name": "forced-colors", "value": "none"}] ) def take_screenshot(self, name): if not self.screenshots: return test = getattr(self, self._testMethodName) filename = f"{test._screenshot_name}--{name}--{test._screenshot_case}.png" path = Path.cwd() / "screenshots" / filename path.parent.mkdir(exist_ok=True, parents=True) self.selenium.save_screenshot(path) def get_browser_logs(self, source=None, level="ALL"): """ Return Chrome console logs filtered by level and optionally source. """ try: logs = self.selenium.get_log("browser") except AttributeError: logs = [] return [ log for log in logs if (level == "ALL" or log["level"] == level) and (source is None or log["source"] == source) ] @classmethod def _quit_selenium(cls): # quit() the WebDriver before attempting to terminate and join the # single-threaded LiveServerThread to avoid a dead lock if the browser # kept a connection alive. if hasattr(cls, "selenium"): cls.selenium.quit() @contextmanager def disable_implicit_wait(self): """Disable the default implicit wait.""" self.selenium.implicitly_wait(0) try: yield finally: self.selenium.implicitly_wait(self.implicit_wait) def screenshot_cases(method_names): if isinstance(method_names, str): method_names = method_names.split(",") def wrapper(func): func._screenshot_cases = method_names setattr(func, "tags", {"screenshot"}.union(getattr(func, "tags", set()))) return func return wrapper
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/signals.py
django/test/signals.py
import os import time import warnings from asgiref.local import Local from django.apps import apps from django.core.exceptions import ImproperlyConfigured from django.core.signals import setting_changed from django.db import connections, router from django.db.utils import ConnectionRouter from django.dispatch import Signal, receiver from django.utils import timezone from django.utils.formats import FORMAT_SETTINGS, reset_format_cache from django.utils.functional import empty template_rendered = Signal() # Most setting_changed receivers are supposed to be added below, # except for cases where the receiver is related to a contrib app. # Settings that may not work well when using 'override_settings' (#19031) COMPLEX_OVERRIDE_SETTINGS = {"DATABASES"} @receiver(setting_changed) def clear_cache_handlers(*, setting, **kwargs): if setting == "CACHES": from django.core.cache import caches, close_caches close_caches() caches._settings = caches.settings = caches.configure_settings(None) caches._connections = Local() @receiver(setting_changed) def update_installed_apps(*, setting, **kwargs): if setting == "INSTALLED_APPS": # Rebuild any AppDirectoriesFinder instance. from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() # Rebuild management commands cache from django.core.management import get_commands get_commands.cache_clear() # Rebuild get_app_template_dirs cache. from django.template.utils import get_app_template_dirs get_app_template_dirs.cache_clear() # Rebuild translations cache. from django.utils.translation import trans_real trans_real._translations = {} @receiver(setting_changed) def update_connections_time_zone(*, setting, **kwargs): if setting == "TIME_ZONE": # Reset process time zone if hasattr(time, "tzset"): if kwargs["value"]: os.environ["TZ"] = kwargs["value"] else: os.environ.pop("TZ", None) time.tzset() # Reset local time zone cache timezone.get_default_timezone.cache_clear() # Reset the database connections' time zone if setting in {"TIME_ZONE", "USE_TZ"}: for conn in connections.all(initialized_only=True): try: del conn.timezone except AttributeError: pass try: del conn.timezone_name except AttributeError: pass conn.ensure_timezone() @receiver(setting_changed) def clear_routers_cache(*, setting, **kwargs): if setting == "DATABASE_ROUTERS": router.routers = ConnectionRouter().routers @receiver(setting_changed) def reset_template_engines(*, setting, **kwargs): if setting in { "TEMPLATES", "DEBUG", "INSTALLED_APPS", }: from django.template import engines try: del engines.templates except AttributeError: pass engines._templates = None engines._engines = {} from django.template.engine import Engine Engine.get_default.cache_clear() from django.forms.renderers import get_default_renderer get_default_renderer.cache_clear() @receiver(setting_changed) def storages_changed(*, setting, **kwargs): from django.contrib.staticfiles.storage import staticfiles_storage from django.core.files.storage import default_storage, storages if setting in ( "STORAGES", "STATIC_ROOT", "STATIC_URL", ): try: del storages.backends except AttributeError: pass storages._backends = None storages._storages = {} default_storage._wrapped = empty staticfiles_storage._wrapped = empty @receiver(setting_changed) def clear_serializers_cache(*, setting, **kwargs): if setting == "SERIALIZATION_MODULES": from django.core import serializers serializers._serializers = {} @receiver(setting_changed) def language_changed(*, setting, **kwargs): if setting in {"LANGUAGES", "LANGUAGE_CODE", "LOCALE_PATHS"}: from django.utils.translation import trans_real trans_real._default = None trans_real._active = Local() if setting in {"LANGUAGES", "LOCALE_PATHS"}: from django.utils.translation import trans_real trans_real._translations = {} trans_real.check_for_language.cache_clear() @receiver(setting_changed) def localize_settings_changed(*, setting, **kwargs): if setting in FORMAT_SETTINGS or setting == "USE_THOUSAND_SEPARATOR": reset_format_cache() @receiver(setting_changed) def complex_setting_changed(*, enter, setting, **kwargs): if enter and setting in COMPLEX_OVERRIDE_SETTINGS: # Considering the current implementation of the signals framework, # this stacklevel shows the line containing the override_settings call. warnings.warn( f"Overriding setting {setting} can lead to unexpected behavior.", stacklevel=5, ) @receiver(setting_changed) def root_urlconf_changed(*, setting, **kwargs): if setting == "ROOT_URLCONF": from django.urls import clear_url_caches, set_urlconf clear_url_caches() set_urlconf(None) @receiver(setting_changed) def static_storage_changed(*, setting, **kwargs): if setting in { "STATIC_ROOT", "STATIC_URL", }: from django.contrib.staticfiles.storage import staticfiles_storage staticfiles_storage._wrapped = empty @receiver(setting_changed) def static_finders_changed(*, setting, **kwargs): if setting in { "STATICFILES_DIRS", "STATIC_ROOT", }: from django.contrib.staticfiles.finders import get_finder get_finder.cache_clear() @receiver(setting_changed) def form_renderer_changed(*, setting, **kwargs): if setting == "FORM_RENDERER": from django.forms.renderers import get_default_renderer get_default_renderer.cache_clear() @receiver(setting_changed) def auth_password_validators_changed(*, setting, **kwargs): if setting == "AUTH_PASSWORD_VALIDATORS": from django.contrib.auth.password_validation import ( get_default_password_validators, ) get_default_password_validators.cache_clear() @receiver(setting_changed) def user_model_swapped(*, setting, **kwargs): if setting == "AUTH_USER_MODEL": apps.clear_cache() try: from django.contrib.auth import get_user_model UserModel = get_user_model() except ImproperlyConfigured: # Some tests set an invalid AUTH_USER_MODEL. pass else: from django.contrib.auth import backends backends.UserModel = UserModel from django.contrib.auth import forms forms.UserModel = UserModel from django.contrib.auth.handlers import modwsgi modwsgi.UserModel = UserModel from django.contrib.auth.management.commands import changepassword changepassword.UserModel = UserModel from django.contrib.auth import views views.UserModel = UserModel
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/utils.py
django/test/utils.py
import collections import gc import logging import os import re import sys import time import warnings from contextlib import contextmanager from functools import wraps from io import StringIO from itertools import chain from types import SimpleNamespace from unittest import TestCase, skipIf, skipUnless from xml.dom.minidom import Node, parseString from asgiref.sync import iscoroutinefunction from django.apps import apps from django.apps.registry import Apps from django.conf import UserSettingsHolder, settings from django.core import mail from django.core.exceptions import ImproperlyConfigured from django.core.signals import request_started, setting_changed from django.db import DEFAULT_DB_ALIAS, connections, reset_queries from django.db.models.options import Options from django.template import PartialTemplate, Template from django.test.signals import template_rendered from django.urls import get_script_prefix, set_script_prefix from django.utils.translation import deactivate from django.utils.version import PYPY try: import jinja2 except ImportError: jinja2 = None __all__ = ( "Approximate", "ContextList", "isolate_lru_cache", "garbage_collect", "get_runner", "CaptureQueriesContext", "ignore_warnings", "isolate_apps", "modify_settings", "override_settings", "override_system_checks", "tag", "requires_tz_support", "setup_databases", "setup_test_environment", "teardown_test_environment", ) TZ_SUPPORT = hasattr(time, "tzset") class Approximate: def __init__(self, val, places=7): self.val = val self.places = places def __repr__(self): return repr(self.val) def __eq__(self, other): return self.val == other or round(abs(self.val - other), self.places) == 0 class ContextList(list): """ A wrapper that provides direct key access to context items contained in a list of context objects. """ def __getitem__(self, key): if isinstance(key, str): for subcontext in self: if key in subcontext: return subcontext[key] raise KeyError(key) else: return super().__getitem__(key) def get(self, key, default=None): try: return self.__getitem__(key) except KeyError: return default def __contains__(self, key): try: self[key] except KeyError: return False return True def keys(self): """ Flattened keys of subcontexts. """ return set(chain.from_iterable(d for subcontext in self for d in subcontext)) def instrumented_test_render(self, context): """ An instrumented Template render method, providing a signal that can be intercepted by the test Client. """ template_rendered.send(sender=self, template=self, context=context) return self.nodelist.render(context) class _TestState: pass def setup_test_environment(debug=None): """ Perform global pre-test setup, such as installing the instrumented template renderer and setting the email backend to the locmem email backend. """ if hasattr(_TestState, "saved_data"): # Executing this function twice would overwrite the saved values. raise RuntimeError( "setup_test_environment() was already called and can't be called " "again without first calling teardown_test_environment()." ) if debug is None: debug = settings.DEBUG saved_data = SimpleNamespace() _TestState.saved_data = saved_data saved_data.allowed_hosts = settings.ALLOWED_HOSTS # Add the default host of the test client. settings.ALLOWED_HOSTS = [*settings.ALLOWED_HOSTS, "testserver"] saved_data.debug = settings.DEBUG settings.DEBUG = debug saved_data.email_backend = settings.EMAIL_BACKEND settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend" saved_data.template_render = Template._render saved_data.partial_template_render = PartialTemplate._render Template._render = instrumented_test_render PartialTemplate._render = instrumented_test_render mail.outbox = [] deactivate() def teardown_test_environment(): """ Perform any global post-test teardown, such as restoring the original template renderer and restoring the email sending functions. """ saved_data = _TestState.saved_data settings.ALLOWED_HOSTS = saved_data.allowed_hosts settings.DEBUG = saved_data.debug settings.EMAIL_BACKEND = saved_data.email_backend Template._render = saved_data.template_render PartialTemplate._render = saved_data.partial_template_render del _TestState.saved_data del mail.outbox def setup_databases( verbosity, interactive, *, time_keeper=None, keepdb=False, debug_sql=False, parallel=0, aliases=None, serialized_aliases=None, **kwargs, ): """Create the test databases.""" if time_keeper is None: time_keeper = NullTimeKeeper() test_databases, mirrored_aliases = get_unique_databases_and_mirrors(aliases) old_names = [] serialize_connections = [] for db_name, aliases in test_databases.values(): first_alias = None for alias in aliases: connection = connections[alias] old_names.append((connection, db_name, first_alias is None)) # Actually create the database for the first connection if first_alias is None: first_alias = alias with time_keeper.timed(" Creating '%s'" % alias): connection.creation.create_test_db( verbosity=verbosity, autoclobber=not interactive, keepdb=keepdb, ) if serialized_aliases is None or alias in serialized_aliases: serialize_connections.append(connection) if parallel > 1: for index in range(parallel): with time_keeper.timed(" Cloning '%s'" % alias): connection.creation.clone_test_db( suffix=str(index + 1), verbosity=verbosity, keepdb=keepdb, ) # Configure all other connections as mirrors of the first one else: connections[alias].creation.set_as_test_mirror( connections[first_alias].settings_dict ) # Configure the test mirrors. for alias, mirror_alias in mirrored_aliases.items(): connections[alias].creation.set_as_test_mirror( connections[mirror_alias].settings_dict ) # Serialize content of test databases only once all of them are setup to # account for database mirroring and routing during serialization. This # slightly horrific process is so people who are testing on databases # without transactions or using TransactionTestCase still get a clean # database on every test run. for serialize_connection in serialize_connections: serialize_connection._test_serialized_contents = ( serialize_connection.creation.serialize_db_to_string() ) if debug_sql: for alias in connections: connections[alias].force_debug_cursor = True return old_names def iter_test_cases(tests): """ Return an iterator over a test suite's unittest.TestCase objects. The tests argument can also be an iterable of TestCase objects. """ for test in tests: if isinstance(test, str): # Prevent an unfriendly RecursionError that can happen with # strings. raise TypeError( f"Test {test!r} must be a test case or test suite not string " f"(was found in {tests!r})." ) if isinstance(test, TestCase): yield test else: # Otherwise, assume it is a test suite. yield from iter_test_cases(test) def dependency_ordered(test_databases, dependencies): """ Reorder test_databases into an order that honors the dependencies described in TEST[DEPENDENCIES]. """ ordered_test_databases = [] resolved_databases = set() # Maps db signature to dependencies of all its aliases dependencies_map = {} # Check that no database depends on its own alias for sig, (_, aliases) in test_databases: all_deps = set() for alias in aliases: all_deps.update(dependencies.get(alias, [])) if not all_deps.isdisjoint(aliases): raise ImproperlyConfigured( "Circular dependency: databases %r depend on each other, " "but are aliases." % aliases ) dependencies_map[sig] = all_deps while test_databases: changed = False deferred = [] # Try to find a DB that has all its dependencies met for signature, (db_name, aliases) in test_databases: if dependencies_map[signature].issubset(resolved_databases): resolved_databases.update(aliases) ordered_test_databases.append((signature, (db_name, aliases))) changed = True else: deferred.append((signature, (db_name, aliases))) if not changed: raise ImproperlyConfigured("Circular dependency in TEST[DEPENDENCIES]") test_databases = deferred return ordered_test_databases def get_unique_databases_and_mirrors(aliases=None): """ Figure out which databases actually need to be created. Deduplicate entries in DATABASES that correspond the same database or are configured as test mirrors. Return two values: - test_databases: ordered mapping of signatures to (name, list of aliases) where all aliases share the same underlying database. - mirrored_aliases: mapping of mirror aliases to original aliases. """ if aliases is None: aliases = connections mirrored_aliases = {} test_databases = {} dependencies = {} default_sig = connections[DEFAULT_DB_ALIAS].creation.test_db_signature() for alias in connections: connection = connections[alias] test_settings = connection.settings_dict["TEST"] if test_settings["MIRROR"]: # If the database is marked as a test mirror, save the alias. mirrored_aliases[alias] = test_settings["MIRROR"] elif alias in aliases: # Store a tuple with DB parameters that uniquely identify it. # If we have two aliases with the same values for that tuple, # we only need to create the test database once. item = test_databases.setdefault( connection.creation.test_db_signature(), (connection.settings_dict["NAME"], []), ) # The default database must be the first because data migrations # use the default alias by default. if alias == DEFAULT_DB_ALIAS: item[1].insert(0, alias) else: item[1].append(alias) if "DEPENDENCIES" in test_settings: dependencies[alias] = test_settings["DEPENDENCIES"] else: if ( alias != DEFAULT_DB_ALIAS and connection.creation.test_db_signature() != default_sig ): dependencies[alias] = test_settings.get( "DEPENDENCIES", [DEFAULT_DB_ALIAS] ) test_databases = dict(dependency_ordered(test_databases.items(), dependencies)) return test_databases, mirrored_aliases def teardown_databases(old_config, verbosity, parallel=0, keepdb=False): """Destroy all the non-mirror databases.""" for connection, old_name, destroy in old_config: if destroy: if parallel > 1: for index in range(parallel): connection.creation.destroy_test_db( suffix=str(index + 1), verbosity=verbosity, keepdb=keepdb, ) connection.creation.destroy_test_db(old_name, verbosity, keepdb) def get_runner(settings, test_runner_class=None): test_runner_class = test_runner_class or settings.TEST_RUNNER test_path = test_runner_class.split(".") # Allow for relative paths if len(test_path) > 1: test_module_name = ".".join(test_path[:-1]) else: test_module_name = "." test_module = __import__(test_module_name, {}, {}, test_path[-1]) return getattr(test_module, test_path[-1]) class TestContextDecorator: """ A base class that can either be used as a context manager during tests or as a test function or unittest.TestCase subclass decorator to perform temporary alterations. `attr_name`: attribute assigned the return value of enable() if used as a class decorator. `kwarg_name`: keyword argument passing the return value of enable() if used as a function decorator. """ def __init__(self, attr_name=None, kwarg_name=None): self.attr_name = attr_name self.kwarg_name = kwarg_name def enable(self): raise NotImplementedError def disable(self): raise NotImplementedError def __enter__(self): return self.enable() def __exit__(self, exc_type, exc_value, traceback): self.disable() def decorate_class(self, cls): if issubclass(cls, TestCase): decorated_setUp = cls.setUp def setUp(inner_self): context = self.enable() inner_self.addCleanup(self.disable) if self.attr_name: setattr(inner_self, self.attr_name, context) decorated_setUp(inner_self) cls.setUp = setUp return cls raise TypeError("Can only decorate subclasses of unittest.TestCase") def decorate_callable(self, func): if iscoroutinefunction(func): # If the inner function is an async function, we must execute async # as well so that the `with` statement executes at the right time. @wraps(func) async def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return await func(*args, **kwargs) else: @wraps(func) def inner(*args, **kwargs): with self as context: if self.kwarg_name: kwargs[self.kwarg_name] = context return func(*args, **kwargs) return inner def __call__(self, decorated): if isinstance(decorated, type): return self.decorate_class(decorated) elif callable(decorated): return self.decorate_callable(decorated) raise TypeError("Cannot decorate object of type %s" % type(decorated)) class override_settings(TestContextDecorator): """ Act as either a decorator or a context manager. If it's a decorator, take a function and return a wrapped function. If it's a contextmanager, use it with the ``with`` statement. In either event, entering/exiting are called before and after, respectively, the function/block is executed. """ enable_exception = None def __init__(self, **kwargs): self.options = kwargs super().__init__() def enable(self): # Keep this code at the beginning to leave the settings unchanged # in case it raises an exception because INSTALLED_APPS is invalid. if "INSTALLED_APPS" in self.options: try: apps.set_installed_apps(self.options["INSTALLED_APPS"]) except Exception: apps.unset_installed_apps() raise override = UserSettingsHolder(settings._wrapped) for key, new_value in self.options.items(): setattr(override, key, new_value) self.wrapped = settings._wrapped settings._wrapped = override for key, new_value in self.options.items(): try: setting_changed.send( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=True, ) except Exception as exc: self.enable_exception = exc self.disable() def disable(self): if "INSTALLED_APPS" in self.options: apps.unset_installed_apps() settings._wrapped = self.wrapped del self.wrapped responses = [] for key in self.options: new_value = getattr(settings, key, None) responses_for_setting = setting_changed.send_robust( sender=settings._wrapped.__class__, setting=key, value=new_value, enter=False, ) responses.extend(responses_for_setting) if self.enable_exception is not None: exc = self.enable_exception self.enable_exception = None raise exc for _, response in responses: if isinstance(response, Exception): raise response def save_options(self, test_func): if test_func._overridden_settings is None: test_func._overridden_settings = self.options else: # Duplicate dict to prevent subclasses from altering their parent. test_func._overridden_settings = { **test_func._overridden_settings, **self.options, } def decorate_class(self, cls): from django.test import SimpleTestCase if not issubclass(cls, SimpleTestCase): raise ValueError( "Only subclasses of Django SimpleTestCase can be decorated " "with override_settings" ) self.save_options(cls) return cls class modify_settings(override_settings): """ Like override_settings, but makes it possible to append, prepend, or remove items instead of redefining the entire list. """ def __init__(self, *args, **kwargs): if args: # Hack used when instantiating from SimpleTestCase.setUpClass. assert not kwargs self.operations = args[0] else: assert not args self.operations = list(kwargs.items()) super(override_settings, self).__init__() def save_options(self, test_func): if test_func._modified_settings is None: test_func._modified_settings = self.operations else: # Duplicate list to prevent subclasses from altering their parent. test_func._modified_settings = ( list(test_func._modified_settings) + self.operations ) def enable(self): self.options = {} for name, operations in self.operations: try: # When called from SimpleTestCase.setUpClass, values may be # overridden several times; cumulate changes. value = self.options[name] except KeyError: value = list(getattr(settings, name, [])) for action, items in operations.items(): # items may be a single value or an iterable. if isinstance(items, str): items = [items] if action == "append": value += [item for item in items if item not in value] elif action == "prepend": value = [item for item in items if item not in value] + value elif action == "remove": value = [item for item in value if item not in items] else: raise ValueError("Unsupported action: %s" % action) self.options[name] = value super().enable() class override_system_checks(TestContextDecorator): """ Act as a decorator. Override list of registered system checks. Useful when you override `INSTALLED_APPS`, e.g. if you exclude `auth` app, you also need to exclude its system checks. """ def __init__(self, new_checks, deployment_checks=None): from django.core.checks.registry import registry self.registry = registry self.new_checks = new_checks self.deployment_checks = deployment_checks super().__init__() def enable(self): self.old_checks = self.registry.registered_checks self.registry.registered_checks = set() for check in self.new_checks: self.registry.register(check, *getattr(check, "tags", ())) self.old_deployment_checks = self.registry.deployment_checks if self.deployment_checks is not None: self.registry.deployment_checks = set() for check in self.deployment_checks: self.registry.register(check, *getattr(check, "tags", ()), deploy=True) def disable(self): self.registry.registered_checks = self.old_checks self.registry.deployment_checks = self.old_deployment_checks def compare_xml(want, got): """ Try to do a 'xml-comparison' of want and got. Plain string comparison doesn't always work because, for example, attribute ordering should not be important. Ignore comment nodes, processing instructions, document type node, and leading and trailing whitespaces. Based on https://github.com/lxml/lxml/blob/master/src/lxml/doctestcompare.py """ _norm_whitespace_re = re.compile(r"[ \t\n][ \t\n]+") def norm_whitespace(v): return _norm_whitespace_re.sub(" ", v) def child_text(element): return "".join( c.data for c in element.childNodes if c.nodeType == Node.TEXT_NODE ) def children(element): return [c for c in element.childNodes if c.nodeType == Node.ELEMENT_NODE] def norm_child_text(element): return norm_whitespace(child_text(element)) def attrs_dict(element): return dict(element.attributes.items()) def check_element(want_element, got_element): if want_element.tagName != got_element.tagName: return False if norm_child_text(want_element) != norm_child_text(got_element): return False if attrs_dict(want_element) != attrs_dict(got_element): return False want_children = children(want_element) got_children = children(got_element) if len(want_children) != len(got_children): return False return all( check_element(want, got) for want, got in zip(want_children, got_children) ) def first_node(document): for node in document.childNodes: if node.nodeType not in ( Node.COMMENT_NODE, Node.DOCUMENT_TYPE_NODE, Node.PROCESSING_INSTRUCTION_NODE, ): return node want = want.strip().replace("\\n", "\n") got = got.strip().replace("\\n", "\n") # If the string is not a complete xml document, we may need to add a # root element. This allow us to compare fragments, like "<foo/><bar/>" if not want.startswith("<?xml"): wrapper = "<root>%s</root>" want = wrapper % want got = wrapper % got # Parse the want and got strings, and compare the parsings. want_root = first_node(parseString(want)) got_root = first_node(parseString(got)) return check_element(want_root, got_root) class CaptureQueriesContext: """ Context manager that captures queries executed by the specified connection. """ def __init__(self, connection): self.connection = connection def __iter__(self): return iter(self.captured_queries) def __getitem__(self, index): return self.captured_queries[index] def __len__(self): return len(self.captured_queries) @property def captured_queries(self): return self.connection.queries[self.initial_queries : self.final_queries] def __enter__(self): self.force_debug_cursor = self.connection.force_debug_cursor self.connection.force_debug_cursor = True # Run any initialization queries if needed so that they won't be # included as part of the count. self.connection.ensure_connection() self.initial_queries = len(self.connection.queries_log) self.final_queries = None self.reset_queries_disconnected = request_started.disconnect(reset_queries) return self def __exit__(self, exc_type, exc_value, traceback): self.connection.force_debug_cursor = self.force_debug_cursor if self.reset_queries_disconnected: request_started.connect(reset_queries) if exc_type is not None: return self.final_queries = len(self.connection.queries_log) class ignore_warnings(TestContextDecorator): def __init__(self, **kwargs): self.ignore_kwargs = kwargs if "message" in self.ignore_kwargs or "module" in self.ignore_kwargs: self.filter_func = warnings.filterwarnings else: self.filter_func = warnings.simplefilter super().__init__() def enable(self): self.catch_warnings = warnings.catch_warnings() self.catch_warnings.__enter__() self.filter_func("ignore", **self.ignore_kwargs) def disable(self): self.catch_warnings.__exit__(*sys.exc_info()) # On OSes that don't provide tzset (Windows), we can't set the timezone # in which the program runs. As a consequence, we must skip tests that # don't enforce a specific timezone (with timezone.override or equivalent), # or attempt to interpret naive datetimes in the default timezone. requires_tz_support = skipUnless( TZ_SUPPORT, "This test relies on the ability to run a program in an arbitrary " "time zone, but your operating system isn't able to do that.", ) @contextmanager def extend_sys_path(*paths): """Context manager to temporarily add paths to sys.path.""" _orig_sys_path = sys.path[:] sys.path.extend(paths) try: yield finally: sys.path = _orig_sys_path @contextmanager def isolate_lru_cache(lru_cache_object): """Clear the cache of an LRU cache object on entering and exiting.""" lru_cache_object.cache_clear() try: yield finally: lru_cache_object.cache_clear() @contextmanager def captured_output(stream_name): """Return a context manager used by captured_stdout/stdin/stderr that temporarily replaces the sys stream *stream_name* with a StringIO. Note: This function and the following ``captured_std*`` are copied from CPython's ``test.support`` module.""" orig_stdout = getattr(sys, stream_name) setattr(sys, stream_name, StringIO()) try: yield getattr(sys, stream_name) finally: setattr(sys, stream_name, orig_stdout) def captured_stdout(): """Capture the output of sys.stdout: with captured_stdout() as stdout: print("hello") self.assertEqual(stdout.getvalue(), "hello\n") """ return captured_output("stdout") def captured_stderr(): """Capture the output of sys.stderr: with captured_stderr() as stderr: print("hello", file=sys.stderr) self.assertEqual(stderr.getvalue(), "hello\n") """ return captured_output("stderr") def captured_stdin(): """Capture the input to sys.stdin: with captured_stdin() as stdin: stdin.write('hello\n') stdin.seek(0) # call test code that consumes from sys.stdin captured = input() self.assertEqual(captured, "hello") """ return captured_output("stdin") @contextmanager def freeze_time(t): """ Context manager to temporarily freeze time.time(). This temporarily modifies the time function of the time module. Modules which import the time function directly (e.g. `from time import time`) won't be affected This isn't meant as a public API, but helps reduce some repetitive code in Django's test suite. """ _real_time = time.time time.time = lambda: t try: yield finally: time.time = _real_time def require_jinja2(test_func): """ Decorator to enable a Jinja2 template engine in addition to the regular Django template engine for a test or skip it if Jinja2 isn't available. """ test_func = skipIf(jinja2 is None, "this test requires jinja2")(test_func) return override_settings( TEMPLATES=[ { "BACKEND": "django.template.backends.django.DjangoTemplates", "APP_DIRS": True, }, { "BACKEND": "django.template.backends.jinja2.Jinja2", "APP_DIRS": True, "OPTIONS": {"keep_trailing_newline": True}, }, ] )(test_func) class override_script_prefix(TestContextDecorator): """Decorator or context manager to temporary override the script prefix.""" def __init__(self, prefix): self.prefix = prefix super().__init__() def enable(self): self.old_prefix = get_script_prefix() set_script_prefix(self.prefix) def disable(self): set_script_prefix(self.old_prefix) class LoggingCaptureMixin: """ Capture the output from the 'django' logger and store it on the class's logger_output attribute. """ def setUp(self): self.logger = logging.getLogger("django") self.old_stream = self.logger.handlers[0].stream self.logger_output = StringIO() self.logger.handlers[0].stream = self.logger_output def tearDown(self): self.logger.handlers[0].stream = self.old_stream class isolate_apps(TestContextDecorator): """ Act as either a decorator or a context manager to register models defined in its wrapped context to an isolated registry. The list of installed apps the isolated registry should contain must be passed as arguments. Two optional keyword arguments can be specified: `attr_name`: attribute assigned the isolated registry if used as a class decorator. `kwarg_name`: keyword argument passing the isolated registry if used as a function decorator. """ def __init__(self, *installed_apps, **kwargs): self.installed_apps = installed_apps super().__init__(**kwargs) def enable(self): self.old_apps = Options.default_apps apps = Apps(self.installed_apps) setattr(Options, "default_apps", apps) return apps def disable(self): setattr(Options, "default_apps", self.old_apps) class TimeKeeper: def __init__(self): self.records = collections.defaultdict(list) @contextmanager def timed(self, name): self.records[name] start_time = time.perf_counter() try: yield finally: end_time = time.perf_counter() - start_time self.records[name].append(end_time) def print_results(self): for name, end_times in self.records.items(): for record_time in end_times: record = "%s took %.3fs" % (name, record_time) sys.stderr.write(record + os.linesep) class NullTimeKeeper: @contextmanager def timed(self, name): yield def print_results(self): pass def tag(*tags): """Decorator to add tags to a test class or method.""" def decorator(obj): if hasattr(obj, "tags"): obj.tags = obj.tags.union(tags) else: setattr(obj, "tags", set(tags)) return obj return decorator @contextmanager def register_lookup(field, *lookups, lookup_name=None): """ Context manager to temporarily register lookups on a model field using lookup_name (or the lookup's lookup_name if not provided). """ try: for lookup in lookups: field.register_lookup(lookup, lookup_name) yield finally: for lookup in lookups:
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/__init__.py
django/test/__init__.py
"""Django Unit Test framework.""" from django.test.client import AsyncClient, AsyncRequestFactory, Client, RequestFactory from django.test.testcases import ( LiveServerTestCase, SimpleTestCase, TestCase, TransactionTestCase, skipIfDBFeature, skipUnlessAnyDBFeature, skipUnlessDBFeature, ) from django.test.utils import ( ignore_warnings, modify_settings, override_settings, override_system_checks, tag, ) __all__ = [ "AsyncClient", "AsyncRequestFactory", "Client", "RequestFactory", "TestCase", "TransactionTestCase", "SimpleTestCase", "LiveServerTestCase", "skipIfDBFeature", "skipUnlessAnyDBFeature", "skipUnlessDBFeature", "ignore_warnings", "modify_settings", "override_settings", "override_system_checks", "tag", ]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/test/testcases.py
django/test/testcases.py
import difflib import json import logging import pickle import posixpath import sys import threading import unittest from collections import Counter from contextlib import contextmanager from copy import copy, deepcopy from difflib import get_close_matches from functools import wraps from unittest import mock from unittest.suite import _DebugResult from unittest.util import safe_repr from urllib.parse import ( parse_qsl, unquote, urlencode, urljoin, urlparse, urlsplit, urlunsplit, ) from urllib.request import url2pathname from asgiref.sync import async_to_sync, iscoroutinefunction from django.apps import apps from django.conf import settings from django.core import mail from django.core.exceptions import ImproperlyConfigured, ValidationError from django.core.files import locks from django.core.handlers.wsgi import WSGIHandler, get_path_info from django.core.management import call_command from django.core.management.color import no_style from django.core.management.sql import emit_post_migrate_signal from django.core.servers.basehttp import ThreadedWSGIServer, WSGIRequestHandler from django.core.signals import setting_changed from django.db import DEFAULT_DB_ALIAS, connection, connections, transaction from django.db.backends.base.base import NO_DB_ALIAS, BaseDatabaseWrapper from django.forms.fields import CharField from django.http import QueryDict from django.http.request import split_domain_port, validate_host from django.template.base import PartialTemplate from django.test.client import AsyncClient, Client from django.test.html import HTMLParseError, parse_html from django.test.signals import template_rendered from django.test.utils import ( CaptureQueriesContext, ContextList, compare_xml, modify_settings, override_settings, ) from django.utils.functional import classproperty from django.views.static import serve logger = logging.getLogger("django.test") __all__ = ( "TestCase", "TransactionTestCase", "SimpleTestCase", "skipIfDBFeature", "skipUnlessDBFeature", ) # Make unittest ignore frames in this module when reporting failures. __unittest = True def to_list(value): """Put value into a list if it's not already one.""" if not isinstance(value, list): value = [value] return value def is_pickable(obj): """ Returns true if the object can be dumped and loaded through the pickle module. """ try: pickle.loads(pickle.dumps(obj)) except (AttributeError, TypeError, pickle.PickleError): return False return True def assert_and_parse_html(self, html, user_msg, msg): try: dom = parse_html(html) except HTMLParseError as e: standardMsg = "%s\n%s" % (msg, e) self.fail(self._formatMessage(user_msg, standardMsg)) return dom class _AssertNumQueriesContext(CaptureQueriesContext): def __init__(self, test_case, num, connection): self.test_case = test_case self.num = num super().__init__(connection) def __exit__(self, exc_type, exc_value, traceback): super().__exit__(exc_type, exc_value, traceback) if exc_type is not None: return executed = len(self) self.test_case.assertEqual( executed, self.num, "%d queries executed, %d expected\nCaptured queries were:\n%s" % ( executed, self.num, "\n".join( "%d. %s" % (i, query["sql"]) for i, query in enumerate(self.captured_queries, start=1) ), ), ) class _AssertTemplateUsedContext: def __init__(self, test_case, template_name, msg_prefix="", count=None): self.test_case = test_case self.template_name = template_name self.msg_prefix = msg_prefix self.count = count self.rendered_templates = [] self.context = ContextList() def on_template_render(self, sender, signal, template, context, **kwargs): self.rendered_templates.append(template) self.context.append(copy(context)) @property def rendered_template_names(self): return [ ( f"{t.origin.template_name}#{t.name}" if isinstance(t, PartialTemplate) else t.name ) for t in self.rendered_templates if t.name is not None ] def test(self): self.test_case._assert_template_used( self.template_name, self.rendered_template_names, self.msg_prefix, self.count, ) def __enter__(self): template_rendered.connect(self.on_template_render) return self def __exit__(self, exc_type, exc_value, traceback): template_rendered.disconnect(self.on_template_render) if exc_type is not None: return self.test() class _AssertTemplateNotUsedContext(_AssertTemplateUsedContext): def test(self): self.test_case.assertFalse( self.template_name in self.rendered_template_names, f"{self.msg_prefix}Template '{self.template_name}' was used " f"unexpectedly in rendering the response", ) class DatabaseOperationForbidden(AssertionError): pass class _DatabaseFailure: def __init__(self, wrapped, message): self.wrapped = wrapped self.message = message def __call__(self): raise DatabaseOperationForbidden(self.message) class SimpleTestCase(unittest.TestCase): # The class we'll use for the test client self.client. # Can be overridden in derived classes. client_class = Client async_client_class = AsyncClient _overridden_settings = None _modified_settings = None _pre_setup_ran_eagerly = False databases = set() _disallowed_database_msg = ( "Database %(operation)s to %(alias)r are not allowed in SimpleTestCase " "subclasses. Either subclass TestCase or TransactionTestCase to ensure " "proper test isolation or add %(alias)r to %(test)s.databases to silence " "this failure." ) _disallowed_connection_methods = [ ("connect", "connections"), ("temporary_connection", "connections"), ("cursor", "queries"), ("chunked_cursor", "queries"), ] @classmethod def setUpClass(cls): super().setUpClass() if cls._overridden_settings: cls.enterClassContext(override_settings(**cls._overridden_settings)) if cls._modified_settings: cls.enterClassContext(modify_settings(cls._modified_settings)) cls._add_databases_failures() cls.addClassCleanup(cls._remove_databases_failures) @classmethod def _validate_databases(cls): if cls.databases == "__all__": return frozenset(connections) for alias in cls.databases: if alias not in connections: message = ( "%s.%s.databases refers to %r which is not defined in " "settings.DATABASES." % ( cls.__module__, cls.__qualname__, alias, ) ) close_matches = get_close_matches(alias, list(connections)) if close_matches: message += " Did you mean %r?" % close_matches[0] raise ImproperlyConfigured(message) return frozenset(cls.databases) @classmethod def _add_databases_failures(cls): cls.databases = cls._validate_databases() for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, operation in cls._disallowed_connection_methods: message = cls._disallowed_database_msg % { "test": "%s.%s" % (cls.__module__, cls.__qualname__), "alias": alias, "operation": operation, } method = getattr(connection, name) setattr(connection, name, _DatabaseFailure(method, message)) cls.enterClassContext( mock.patch.object( BaseDatabaseWrapper, "ensure_connection", new=cls.ensure_connection_patch_method(), ) ) @classmethod def _remove_databases_failures(cls): for alias in connections: if alias in cls.databases: continue connection = connections[alias] for name, _ in cls._disallowed_connection_methods: method = getattr(connection, name) setattr(connection, name, method.wrapped) @classmethod def ensure_connection_patch_method(cls): real_ensure_connection = BaseDatabaseWrapper.ensure_connection def patched_ensure_connection(self, *args, **kwargs): if ( self.connection is None and self.alias not in cls.databases and self.alias != NO_DB_ALIAS # Dynamically created connections are always allowed. and self.alias in connections ): # Connection has not yet been established, but the alias is not # allowed. message = cls._disallowed_database_msg % { "test": f"{cls.__module__}.{cls.__qualname__}", "alias": self.alias, "operation": "threaded connections", } return _DatabaseFailure(self.ensure_connection, message)() real_ensure_connection(self, *args, **kwargs) return patched_ensure_connection def __call__(self, result=None): """ Wrapper around default __call__ method to perform common Django test set up. This means that user-defined TestCases aren't required to include a call to super().setUp(). """ self._setup_and_call(result) def __getstate__(self): """ Make SimpleTestCase picklable for parallel tests using subtests. """ state = super().__dict__ # _outcome and _subtest cannot be tested on picklability, since they # contain the TestCase itself, leading to an infinite recursion. if state["_outcome"]: pickable_state = {"_outcome": None, "_subtest": None} for key, value in state.items(): if key in pickable_state or not is_pickable(value): continue pickable_state[key] = value return pickable_state return state def debug(self): """Perform the same as __call__(), without catching the exception.""" debug_result = _DebugResult() self._setup_and_call(debug_result, debug=True) def _setup_and_call(self, result, debug=False): """ Perform the following in order: pre-setup, run test, post-teardown, skipping pre/post hooks if test is set to be skipped. If debug=True, reraise any errors in setup and use super().debug() instead of __call__() to run the test. """ testMethod = getattr(self, self._testMethodName) skipped = getattr(self.__class__, "__unittest_skip__", False) or getattr( testMethod, "__unittest_skip__", False ) # Convert async test methods. if iscoroutinefunction(testMethod): setattr(self, self._testMethodName, async_to_sync(testMethod)) if not skipped: try: if self.__class__._pre_setup_ran_eagerly: self.__class__._pre_setup_ran_eagerly = False else: self._pre_setup() except Exception: if debug: raise result.addError(self, sys.exc_info()) return if debug: super().debug() else: super().__call__(result) if not skipped: try: self._post_teardown() except Exception: if debug: raise result.addError(self, sys.exc_info()) return @classmethod def _pre_setup(cls): """ Perform pre-test setup: * Create a test client. * Clear the mail test outbox. """ cls.client = cls.client_class() cls.async_client = cls.async_client_class() mail.outbox = [] def _post_teardown(self): """Perform post-test things.""" pass def settings(self, **kwargs): """ A context manager that temporarily sets a setting and reverts to the original value when exiting the context. """ return override_settings(**kwargs) def modify_settings(self, **kwargs): """ A context manager that temporarily applies changes to a list setting and reverts back to the original value when exiting the context. """ return modify_settings(**kwargs) def assertRedirects( self, response, expected_url, status_code=302, target_status_code=200, msg_prefix="", fetch_redirect_response=True, ): """ Assert that a response redirected to a specific URL and that the redirect URL can be loaded. Won't work for external links since it uses the test client to do a request (use fetch_redirect_response=False to check such links without fetching them). """ if msg_prefix: msg_prefix += ": " if hasattr(response, "redirect_chain"): # The request was a followed redirect self.assertTrue( response.redirect_chain, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) self.assertEqual( response.redirect_chain[0][1], status_code, msg_prefix + ( "Initial response didn't redirect as expected: Response code was " "%d (expected %d)" ) % (response.redirect_chain[0][1], status_code), ) url, status_code = response.redirect_chain[-1] self.assertEqual( response.status_code, target_status_code, msg_prefix + ( "Response didn't redirect as expected: Final Response code was %d " "(expected %d)" ) % (response.status_code, target_status_code), ) else: # Not a followed redirect self.assertEqual( response.status_code, status_code, msg_prefix + ( "Response didn't redirect as expected: Response code was %d " "(expected %d)" ) % (response.status_code, status_code), ) url = response.url scheme, netloc, path, query, fragment = urlsplit(url) # Prepend the request path to handle relative path redirects. if not path.startswith("/"): url = urljoin(response.request["PATH_INFO"], url) path = urljoin(response.request["PATH_INFO"], path) if fetch_redirect_response: # netloc might be empty, or in cases where Django tests the # HTTP scheme, the convention is for netloc to be 'testserver'. # Trust both as "internal" URLs here. domain, port = split_domain_port(netloc) if domain and not validate_host(domain, settings.ALLOWED_HOSTS): raise ValueError( "The test client is unable to fetch remote URLs (got %s). " "If the host is served by Django, add '%s' to ALLOWED_HOSTS. " "Otherwise, use " "assertRedirects(..., fetch_redirect_response=False)." % (url, domain) ) # Get the redirection page, using the same client that was used # to obtain the original response. extra = response.client.extra or {} headers = response.client.headers or {} redirect_response = response.client.get( path, QueryDict(query), secure=(scheme == "https"), headers=headers, **extra, ) self.assertEqual( redirect_response.status_code, target_status_code, msg_prefix + ( "Couldn't retrieve redirection page '%s': response code was %d " "(expected %d)" ) % (path, redirect_response.status_code, target_status_code), ) self.assertURLEqual( url, expected_url, msg_prefix + "Response redirected to '%s', expected '%s'" % (url, expected_url), ) def assertURLEqual(self, url1, url2, msg_prefix=""): """ Assert that two URLs are the same, ignoring the order of query string parameters except for parameters with the same name. For example, /path/?x=1&y=2 is equal to /path/?y=2&x=1, but /path/?a=1&a=2 isn't equal to /path/?a=2&a=1. """ def normalize(url): """Sort the URL's query string parameters.""" url = str(url) # Coerce reverse_lazy() URLs. scheme, netloc, path, query, fragment = urlsplit(url) query_parts = sorted(parse_qsl(query)) return urlunsplit((scheme, netloc, path, urlencode(query_parts), fragment)) if msg_prefix: msg_prefix += ": " self.assertEqual( normalize(url1), normalize(url2), msg_prefix + "Expected '%s' to equal '%s'." % (url1, url2), ) def _text_repr(self, content, force_string): if isinstance(content, bytes) and not force_string: return safe_repr(content) return "'%s'" % str(content) def _assert_contains(self, response, text, status_code, msg_prefix, html): # If the response supports deferred rendering and hasn't been rendered # yet, then ensure that it does get rendered before proceeding further. if ( hasattr(response, "render") and callable(response.render) and not response.is_rendered ): response.render() if msg_prefix: msg_prefix += ": " self.assertEqual( response.status_code, status_code, msg_prefix + "Couldn't retrieve content: Response code was %d" " (expected %d)" % (response.status_code, status_code), ) if response.streaming: content = b"".join(response.streaming_content) else: content = response.content response_content = content if not isinstance(text, bytes) or html: text = str(text) content = content.decode(response.charset) if html: content = assert_and_parse_html( self, content, None, "Response's content is not valid HTML:" ) text = assert_and_parse_html( self, text, None, "Second argument is not valid HTML:" ) real_count = content.count(text) return real_count, msg_prefix, response_content def assertContains( self, response, text, count=None, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` occurs ``count`` times in the content of the response. If ``count`` is None, the count doesn't matter - the assertion is true if the text occurs at least once in the response. """ real_count, msg_prefix, response_content = self._assert_contains( response, text, status_code, msg_prefix, html ) if (count is None and real_count > 0) or ( (count is not None and real_count == count) ): return text_repr = self._text_repr(text, force_string=html) if count is not None: msg = ( f"{real_count} != {count} : {msg_prefix}Found {real_count} instances " f"of {text_repr} (expected {count}) in the following response\n" f"{response_content!r}" ) else: msg = ( f"False is not true : {msg_prefix}Couldn't find {text_repr} in the " f"following response\n{response_content!r}" ) self.fail(msg) def assertNotContains( self, response, text, status_code=200, msg_prefix="", html=False ): """ Assert that a response indicates that some content was retrieved successfully, (i.e., the HTTP status code was as expected) and that ``text`` doesn't occur in the content of the response. """ real_count, msg_prefix, response_content = self._assert_contains( response, text, status_code, msg_prefix, html ) if real_count != 0: text_repr = self._text_repr(text, force_string=html) self.fail( f"{real_count} != 0 :{msg_prefix}{text_repr} unexpectedly found in the " f"following response\n{response_content!r}" ) def _check_test_client_response(self, response, attribute, method_name): """ Raise a ValueError if the given response doesn't have the required attribute. """ if not hasattr(response, attribute): raise ValueError( f"{method_name}() is only usable on responses fetched using " "the Django test Client." ) def _form_repr(self, form, formset, form_index): if formset is None: return f"form {form!r}" return f"form {form_index} of formset {formset!r}" def _assert_form_error( self, form, field, errors, msg_prefix, formset=None, form_index=None ): if not form.is_bound: self.fail( "%sThe %s is not bound, it will never have any errors." % (msg_prefix, self._form_repr(form, formset, form_index)) ) if field is not None and field not in form.fields: self.fail( "%sThe %s does not contain the field %r." % (msg_prefix, self._form_repr(form, formset, form_index), field) ) field_errors = ( form.non_field_errors() if field is None else form.errors.get(field, []) ) if field_errors == errors: return # Use assertEqual to show detailed diff if errors don't match. if field is None: failure_message = "The non-field errors of %s don't match." % ( self._form_repr(form, formset, form_index), ) else: failure_message = "The errors of field %r on %s don't match." % ( field, self._form_repr(form, formset, form_index), ) self.assertEqual(field_errors, errors, msg_prefix + failure_message) def assertFormError(self, form, field, errors, msg_prefix=""): """ Assert that a field named "field" on the given form object has specific errors. errors can be either a single error message or a list of errors messages. Using errors=[] test that the field has no errors. You can pass field=None to check the form's non-field errors. """ if msg_prefix: msg_prefix += ": " errors = to_list(errors) self._assert_form_error(form, field, errors, msg_prefix) def assertFormSetError(self, formset, form_index, field, errors, msg_prefix=""): """ Similar to assertFormError() but for formsets. Use form_index=None to check the formset's non-form errors (in that case, you must also use field=None). Otherwise use an integer to check the formset's n-th form for errors. Other parameters are the same as assertFormError(). """ if form_index is None and field is not None: raise ValueError("You must use field=None with form_index=None.") if msg_prefix: msg_prefix += ": " errors = to_list(errors) if not formset.is_bound: self.fail( f"{msg_prefix}The formset {formset!r} is not bound, it will never have " f"any errors." ) if form_index is not None and form_index >= formset.total_form_count(): form_count = formset.total_form_count() form_or_forms = "forms" if form_count > 1 else "form" self.fail( f"{msg_prefix}The formset {formset!r} only has {form_count} " f"{form_or_forms}." ) if form_index is not None: self._assert_form_error( formset.forms[form_index], field, errors, msg_prefix, formset=formset, form_index=form_index, ) else: formset_errors = formset.non_form_errors() if formset_errors == errors: # Skip assertion if errors already match. return failure_message = f"The non-form errors of formset {formset!r} don't match." self.assertEqual(formset_errors, errors, msg_prefix + failure_message) def _get_template_used(self, response, template_name, msg_prefix, method_name): if response is None and template_name is None: raise TypeError("response and/or template_name argument must be provided") if msg_prefix: msg_prefix += ": " if template_name is not None and response is not None: self._check_test_client_response(response, "templates", method_name) if not hasattr(response, "templates") or (response is None and template_name): if response: template_name = response response = None # use this template with context manager return template_name, None, msg_prefix template_names = [t.name for t in response.templates if t.name is not None] return None, template_names, msg_prefix def _assert_template_used(self, template_name, template_names, msg_prefix, count): if not template_names: self.fail(msg_prefix + "No templates used to render the response") self.assertTrue( template_name in template_names, msg_prefix + "Template '%s' was not a template used to render" " the response. Actual template(s) used: %s" % (template_name, ", ".join(template_names)), ) if count is not None: self.assertEqual( template_names.count(template_name), count, msg_prefix + "Template '%s' was expected to be rendered %d " "time(s) but was actually rendered %d time(s)." % (template_name, count, template_names.count(template_name)), ) def assertTemplateUsed( self, response=None, template_name=None, msg_prefix="", count=None ): """ Assert that the template with the provided name was used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateUsed", ) if context_mgr_template: # Use assertTemplateUsed as context manager. return _AssertTemplateUsedContext( self, context_mgr_template, msg_prefix, count ) self._assert_template_used(template_name, template_names, msg_prefix, count) def assertTemplateNotUsed(self, response=None, template_name=None, msg_prefix=""): """ Assert that the template with the provided name was NOT used in rendering the response. Also usable as context manager. """ context_mgr_template, template_names, msg_prefix = self._get_template_used( response, template_name, msg_prefix, "assertTemplateNotUsed", ) if context_mgr_template: # Use assertTemplateNotUsed as context manager. return _AssertTemplateNotUsedContext(self, context_mgr_template, msg_prefix) self.assertFalse( template_name in template_names, msg_prefix + "Template '%s' was used unexpectedly in rendering the response" % template_name, ) @contextmanager def _assert_raises_or_warns_cm( self, func, cm_attr, expected_exception, expected_message ): with func(expected_exception) as cm: yield cm self.assertIn(expected_message, str(getattr(cm, cm_attr))) def _assertFooMessage( self, func, cm_attr, expected_exception, expected_message, *args, **kwargs ): callable_obj = None if args: callable_obj, *args = args cm = self._assert_raises_or_warns_cm( func, cm_attr, expected_exception, expected_message ) # Assertion used in context manager fashion. if callable_obj is None: return cm # Assertion was passed a callable. with cm: callable_obj(*args, **kwargs) def assertRaisesMessage( self, expected_exception, expected_message, *args, **kwargs ): """ Assert that expected_message is found in the message of a raised exception. Args: expected_exception: Exception class expected to be raised. expected_message: expected error message string value. args: Function to be called and extra positional args. kwargs: Extra kwargs. """ return self._assertFooMessage( self.assertRaises, "exception", expected_exception, expected_message, *args, **kwargs, ) def assertWarnsMessage(self, expected_warning, expected_message, *args, **kwargs): """ Same as assertRaisesMessage but for assertWarns() instead of assertRaises(). """ return self._assertFooMessage( self.assertWarns, "warning", expected_warning, expected_message, *args, **kwargs, ) def assertFieldOutput( self, fieldclass, valid, invalid, field_args=None, field_kwargs=None, empty_value="", ): """ Assert that a form field behaves correctly with various inputs. Args: fieldclass: the class of the field to be tested. valid: a dictionary mapping valid inputs to their expected cleaned values. invalid: a dictionary mapping invalid inputs to one or more raised error messages. field_args: the args passed to instantiate the field field_kwargs: the kwargs passed to instantiate the field empty_value: the expected clean output for inputs in empty_values """ if field_args is None: field_args = [] if field_kwargs is None: field_kwargs = {} required = fieldclass(*field_args, **field_kwargs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/formsets.py
django/forms/formsets.py
from django.core.exceptions import ValidationError from django.forms.fields import BooleanField, IntegerField from django.forms.forms import Form from django.forms.renderers import get_default_renderer from django.forms.utils import ErrorList, RenderableFormMixin from django.forms.widgets import CheckboxInput, HiddenInput, NumberInput from django.utils.functional import cached_property from django.utils.translation import gettext_lazy as _ from django.utils.translation import ngettext_lazy __all__ = ("BaseFormSet", "formset_factory", "all_valid") # special field names TOTAL_FORM_COUNT = "TOTAL_FORMS" INITIAL_FORM_COUNT = "INITIAL_FORMS" MIN_NUM_FORM_COUNT = "MIN_NUM_FORMS" MAX_NUM_FORM_COUNT = "MAX_NUM_FORMS" ORDERING_FIELD_NAME = "ORDER" DELETION_FIELD_NAME = "DELETE" # default minimum number of forms in a formset DEFAULT_MIN_NUM = 0 # default maximum number of forms in a formset, to prevent memory exhaustion DEFAULT_MAX_NUM = 1000 class ManagementForm(Form): """ Keep track of how many form instances are displayed on the page. If adding new forms via JavaScript, you should increment the count field of this form as well. """ TOTAL_FORMS = IntegerField(widget=HiddenInput) INITIAL_FORMS = IntegerField(widget=HiddenInput) # MIN_NUM_FORM_COUNT and MAX_NUM_FORM_COUNT are output with the rest of the # management form, but only for the convenience of client-side code. The # POST value of them returned from the client is not checked. MIN_NUM_FORMS = IntegerField(required=False, widget=HiddenInput) MAX_NUM_FORMS = IntegerField(required=False, widget=HiddenInput) def clean(self): cleaned_data = super().clean() # When the management form is invalid, we don't know how many forms # were submitted. cleaned_data.setdefault(TOTAL_FORM_COUNT, 0) cleaned_data.setdefault(INITIAL_FORM_COUNT, 0) return cleaned_data class BaseFormSet(RenderableFormMixin): """ A collection of instances of the same Form class. """ deletion_widget = CheckboxInput ordering_widget = NumberInput default_error_messages = { "missing_management_form": _( "ManagementForm data is missing or has been tampered with. Missing fields: " "%(field_names)s. You may need to file a bug report if the issue persists." ), "too_many_forms": ngettext_lazy( "Please submit at most %(num)d form.", "Please submit at most %(num)d forms.", "num", ), "too_few_forms": ngettext_lazy( "Please submit at least %(num)d form.", "Please submit at least %(num)d forms.", "num", ), } template_name_div = "django/forms/formsets/div.html" template_name_p = "django/forms/formsets/p.html" template_name_table = "django/forms/formsets/table.html" template_name_ul = "django/forms/formsets/ul.html" def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, form_kwargs=None, error_messages=None, ): self.is_bound = data is not None or files is not None self.prefix = prefix or self.get_default_prefix() self.auto_id = auto_id self.data = data or {} self.files = files or {} self.initial = initial self.form_kwargs = form_kwargs or {} self.error_class = error_class self._errors = None self._non_form_errors = None self.form_renderer = self.renderer self.renderer = self.renderer or get_default_renderer() messages = {} for cls in reversed(type(self).__mro__): messages.update(getattr(cls, "default_error_messages", {})) if error_messages is not None: messages.update(error_messages) self.error_messages = messages def __iter__(self): """Yield the forms in the order they should be rendered.""" return iter(self.forms) def __getitem__(self, index): """Return the form at the given index, based on the rendering order.""" return self.forms[index] def __len__(self): return len(self.forms) def __bool__(self): """ Return True since all formsets have a management form which is not included in the length. """ return True def __repr__(self): if self._errors is None: is_valid = "Unknown" else: is_valid = ( self.is_bound and not self._non_form_errors and not any(form_errors for form_errors in self._errors) ) return "<%s: bound=%s valid=%s total_forms=%s>" % ( self.__class__.__qualname__, self.is_bound, is_valid, self.total_form_count(), ) @cached_property def management_form(self): """Return the ManagementForm instance for this FormSet.""" if self.is_bound: form = ManagementForm( self.data, auto_id=self.auto_id, prefix=self.prefix, renderer=self.renderer, ) form.full_clean() else: form = ManagementForm( auto_id=self.auto_id, prefix=self.prefix, initial={ TOTAL_FORM_COUNT: self.total_form_count(), INITIAL_FORM_COUNT: self.initial_form_count(), MIN_NUM_FORM_COUNT: self.min_num, MAX_NUM_FORM_COUNT: self.max_num, }, renderer=self.renderer, ) return form def total_form_count(self): """Return the total number of forms in this FormSet.""" if self.is_bound: # return absolute_max if it is lower than the actual total form # count in the data; this is DoS protection to prevent clients # from forcing the server to instantiate arbitrary numbers of # forms return min( self.management_form.cleaned_data[TOTAL_FORM_COUNT], self.absolute_max ) else: initial_forms = self.initial_form_count() total_forms = max(initial_forms, self.min_num) + self.extra # Allow all existing related objects/inlines to be displayed, # but don't allow extra beyond max_num. if initial_forms > self.max_num >= 0: total_forms = initial_forms elif total_forms > self.max_num >= 0: total_forms = self.max_num return total_forms def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if self.is_bound: return self.management_form.cleaned_data[INITIAL_FORM_COUNT] else: # Use the length of the initial data if it's there, 0 otherwise. initial_forms = len(self.initial) if self.initial else 0 return initial_forms @cached_property def forms(self): """Instantiate forms at first property access.""" # DoS protection is included in total_form_count() return [ self._construct_form(i, **self.get_form_kwargs(i)) for i in range(self.total_form_count()) ] def get_form_kwargs(self, index): """ Return additional keyword arguments for each individual formset form. index will be None if the form being constructed is a new empty form. """ return self.form_kwargs.copy() def _construct_form(self, i, **kwargs): """Instantiate and return the i-th form instance in a formset.""" defaults = { "auto_id": self.auto_id, "prefix": self.add_prefix(i), "error_class": self.error_class, # Don't render the HTML 'required' attribute as it may cause # incorrect validation for extra, optional, and deleted # forms in the formset. "use_required_attribute": False, "renderer": self.form_renderer, } if self.is_bound: defaults["data"] = self.data defaults["files"] = self.files if self.initial and "initial" not in kwargs: try: defaults["initial"] = self.initial[i] except IndexError: pass # Allow extra forms to be empty, unless they're part of # the minimum forms. if i >= self.initial_form_count() and i >= self.min_num: defaults["empty_permitted"] = True defaults.update(kwargs) form = self.form(**defaults) self.add_fields(form, i) return form @property def initial_forms(self): """Return a list of all the initial forms in this formset.""" return self.forms[: self.initial_form_count()] @property def extra_forms(self): """Return a list of all the extra forms in this formset.""" return self.forms[self.initial_form_count() :] @property def empty_form(self): form_kwargs = { **self.get_form_kwargs(None), "auto_id": self.auto_id, "prefix": self.add_prefix("__prefix__"), "empty_permitted": True, "use_required_attribute": False, "renderer": self.form_renderer, } form = self.form(**form_kwargs) self.add_fields(form, None) return form @property def cleaned_data(self): """ Return a list of form.cleaned_data dicts for every form in self.forms. """ if not self.is_valid(): raise AttributeError( "'%s' object has no attribute 'cleaned_data'" % self.__class__.__name__ ) return [form.cleaned_data for form in self.forms] @property def deleted_forms(self): """Return a list of forms that have been marked for deletion.""" if not self.is_valid() or not self.can_delete: return [] # construct _deleted_form_indexes which is just a list of form indexes # that have had their deletion widget set to True if not hasattr(self, "_deleted_form_indexes"): self._deleted_form_indexes = [] for i, form in enumerate(self.forms): # If this is an extra form and hasn't changed, ignore it. if i >= self.initial_form_count() and not form.has_changed(): continue if self._should_delete_form(form): self._deleted_form_indexes.append(i) return [self.forms[i] for i in self._deleted_form_indexes] @property def ordered_forms(self): """ Return a list of form in the order specified by the incoming data. Raise an AttributeError if ordering is not allowed. """ if not self.is_valid() or not self.can_order: raise AttributeError( "'%s' object has no attribute 'ordered_forms'" % self.__class__.__name__ ) # Construct _ordering, which is a list of (form_index, # order_field_value) tuples. After constructing this list, we'll sort # it by order_field_value so we have a way to get to the form indexes # in the order specified by the form data. if not hasattr(self, "_ordering"): self._ordering = [] for i, form in enumerate(self.forms): # If this is an extra form and hasn't changed, ignore it. if i >= self.initial_form_count() and not form.has_changed(): continue # don't add data marked for deletion to self.ordered_data if self.can_delete and self._should_delete_form(form): continue self._ordering.append((i, form.cleaned_data[ORDERING_FIELD_NAME])) # After we're done populating self._ordering, sort it. # A sort function to order things numerically ascending, but # None should be sorted below anything else. Allowing None as # a comparison value makes it so we can leave ordering fields # blank. def compare_ordering_key(k): if k[1] is None: return (1, 0) # +infinity, larger than any number return (0, k[1]) self._ordering.sort(key=compare_ordering_key) # Return a list of form.cleaned_data dicts in the order specified by # the form data. return [self.forms[i[0]] for i in self._ordering] @classmethod def get_default_prefix(cls): return "form" @classmethod def get_deletion_widget(cls): return cls.deletion_widget @classmethod def get_ordering_widget(cls): return cls.ordering_widget def non_form_errors(self): """ Return an ErrorList of errors that aren't associated with a particular form -- i.e., from formset.clean(). Return an empty ErrorList if there are none. """ if self._non_form_errors is None: self.full_clean() return self._non_form_errors @property def errors(self): """Return a list of form.errors for every form in self.forms.""" if self._errors is None: self.full_clean() return self._errors def total_error_count(self): """Return the number of errors across all forms in the formset.""" return len(self.non_form_errors()) + sum( len(form_errors) for form_errors in self.errors ) def _should_delete_form(self, form): """Return whether or not the form was marked for deletion.""" return form.cleaned_data.get(DELETION_FIELD_NAME, False) def is_valid(self): """Return True if every form in self.forms is valid.""" if not self.is_bound: return False # Accessing errors triggers a full clean the first time only. self.errors # List comprehension ensures is_valid() is called for all forms. # Forms due to be deleted shouldn't cause the formset to be invalid. forms_valid = all( [ form.is_valid() for form in self.forms if not (self.can_delete and self._should_delete_form(form)) ] ) return forms_valid and not self.non_form_errors() def full_clean(self): """ Clean all of self.data and populate self._errors and self._non_form_errors. """ self._errors = [] self._non_form_errors = self.error_class( error_class="nonform", renderer=self.renderer ) empty_forms_count = 0 if not self.is_bound: # Stop further processing. return if not self.management_form.is_valid(): error = ValidationError( self.error_messages["missing_management_form"], params={ "field_names": ", ".join( self.management_form.add_prefix(field_name) for field_name in self.management_form.errors ), }, code="missing_management_form", ) self._non_form_errors.append(error) for i, form in enumerate(self.forms): # Empty forms are unchanged forms beyond those with initial data. if not form.has_changed() and i >= self.initial_form_count(): empty_forms_count += 1 # Accessing errors calls full_clean() if necessary. # _should_delete_form() requires cleaned_data. form_errors = form.errors if self.can_delete and self._should_delete_form(form): continue self._errors.append(form_errors) try: if ( self.validate_max and self.total_form_count() - len(self.deleted_forms) > self.max_num ) or self.management_form.cleaned_data[ TOTAL_FORM_COUNT ] > self.absolute_max: raise ValidationError( self.error_messages["too_many_forms"] % {"num": self.max_num}, code="too_many_forms", ) if ( self.validate_min and self.total_form_count() - len(self.deleted_forms) - empty_forms_count < self.min_num ): raise ValidationError( self.error_messages["too_few_forms"] % {"num": self.min_num}, code="too_few_forms", ) # Give self.clean() a chance to do cross-form validation. self.clean() except ValidationError as e: self._non_form_errors = self.error_class( e.error_list, error_class="nonform", renderer=self.renderer, ) def clean(self): """ Hook for doing any extra formset-wide cleaning after Form.clean() has been called on every form. Any ValidationError raised by this method will not be associated with a particular form; it will be accessible via formset.non_form_errors() """ pass def has_changed(self): """Return True if data in any form differs from initial.""" return any(form.has_changed() for form in self) def add_fields(self, form, index): """A hook for adding extra fields on to each form instance.""" initial_form_count = self.initial_form_count() if self.can_order: # Only pre-fill the ordering field for initial forms. if index is not None and index < initial_form_count: form.fields[ORDERING_FIELD_NAME] = IntegerField( label=_("Order"), initial=index + 1, required=False, widget=self.get_ordering_widget(), ) else: form.fields[ORDERING_FIELD_NAME] = IntegerField( label=_("Order"), required=False, widget=self.get_ordering_widget(), ) if self.can_delete and ( self.can_delete_extra or (index is not None and index < initial_form_count) ): form.fields[DELETION_FIELD_NAME] = BooleanField( label=_("Delete"), required=False, widget=self.get_deletion_widget(), ) def add_prefix(self, index): return "%s-%s" % (self.prefix, index) def is_multipart(self): """ Return True if the formset needs to be multipart, i.e. it has FileInput, or False otherwise. """ if self.forms: return self.forms[0].is_multipart() else: return self.empty_form.is_multipart() @property def media(self): # All the forms on a FormSet are the same, so you only need to # interrogate the first form for media. if self.forms: return self.forms[0].media else: return self.empty_form.media @property def template_name(self): return self.renderer.formset_template_name def get_context(self): return {"formset": self} def formset_factory( form, formset=BaseFormSet, extra=1, can_order=False, can_delete=False, max_num=None, validate_max=False, min_num=None, validate_min=False, absolute_max=None, can_delete_extra=True, renderer=None, ): """Return a FormSet for the given form class.""" if min_num is None: min_num = DEFAULT_MIN_NUM if max_num is None: max_num = DEFAULT_MAX_NUM # absolute_max is a hard limit on forms instantiated, to prevent # memory-exhaustion attacks. Default to max_num + DEFAULT_MAX_NUM # (which is 2 * DEFAULT_MAX_NUM if max_num is None in the first place). if absolute_max is None: absolute_max = max_num + DEFAULT_MAX_NUM if max_num > absolute_max: raise ValueError("'absolute_max' must be greater or equal to 'max_num'.") attrs = { "form": form, "extra": extra, "can_order": can_order, "can_delete": can_delete, "can_delete_extra": can_delete_extra, "min_num": min_num, "max_num": max_num, "absolute_max": absolute_max, "validate_min": validate_min, "validate_max": validate_max, "renderer": renderer, } form_name = form.__name__ if form_name.endswith("Form"): formset_name = form_name + "Set" else: formset_name = form_name + "FormSet" return type(formset_name, (formset,), attrs) def all_valid(formsets): """Validate every formset and return True if all are valid.""" # List comprehension ensures is_valid() is called for all formsets. return all([formset.is_valid() for formset in formsets])
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/models.py
django/forms/models.py
""" Helper functions for creating Form classes from Django models and database field objects. """ from itertools import chain from django.core.exceptions import ( NON_FIELD_ERRORS, FieldError, ImproperlyConfigured, ValidationError, ) from django.core.validators import ProhibitNullCharactersValidator from django.db.models.utils import AltersData from django.forms.fields import ChoiceField, Field from django.forms.forms import BaseForm, DeclarativeFieldsMetaclass from django.forms.formsets import BaseFormSet, formset_factory from django.forms.utils import ErrorList from django.forms.widgets import ( HiddenInput, MultipleHiddenInput, RadioSelect, SelectMultiple, ) from django.utils.choices import BaseChoiceIterator from django.utils.hashable import make_hashable from django.utils.text import capfirst, get_text_list from django.utils.translation import gettext from django.utils.translation import gettext_lazy as _ __all__ = ( "ModelForm", "BaseModelForm", "model_to_dict", "fields_for_model", "ModelChoiceField", "ModelMultipleChoiceField", "ALL_FIELDS", "BaseModelFormSet", "modelformset_factory", "BaseInlineFormSet", "inlineformset_factory", "modelform_factory", ) ALL_FIELDS = "__all__" def construct_instance(form, instance, fields=None, exclude=None): """ Construct and return a model instance from the bound ``form``'s ``cleaned_data``, but do not save the returned instance to the database. """ from django.db import models opts = instance._meta cleaned_data = form.cleaned_data file_field_list = [] for f in opts.fields: if ( not f.editable or isinstance(f, models.AutoField) or f.name not in cleaned_data ): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue # Leave defaults for fields that aren't in POST data, except for # checkbox inputs because they don't appear in POST data if not # checked. if ( f.has_default() and form[f.name].field.widget.value_omitted_from_data( form.data, form.files, form.add_prefix(f.name) ) and cleaned_data.get(f.name) in form[f.name].field.empty_values ): continue # Defer saving file-type fields until after the other fields, so a # callable upload_to can use the values from other fields. if isinstance(f, models.FileField): file_field_list.append(f) else: f.save_form_data(instance, cleaned_data[f.name]) for f in file_field_list: f.save_form_data(instance, cleaned_data[f.name]) return instance # ModelForms ################################################################# def model_to_dict(instance, fields=None, exclude=None): """ Return a dict containing the data in ``instance`` suitable for passing as a Form's ``initial`` keyword argument. ``fields`` is an optional list of field names. If provided, return only the named. ``exclude`` is an optional list of field names. If provided, exclude the named from the returned dict, even if they are listed in the ``fields`` argument. """ opts = instance._meta data = {} for f in chain(opts.concrete_fields, opts.private_fields, opts.many_to_many): if not getattr(f, "editable", False): continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue data[f.name] = f.value_from_object(instance) return data def apply_limit_choices_to_to_formfield(formfield): """Apply limit_choices_to to the formfield's queryset if needed.""" from django.db.models import Exists, OuterRef, Q if hasattr(formfield, "queryset") and hasattr(formfield, "get_limit_choices_to"): limit_choices_to = formfield.get_limit_choices_to() if limit_choices_to: complex_filter = limit_choices_to if not isinstance(complex_filter, Q): complex_filter = Q(**limit_choices_to) complex_filter &= Q(pk=OuterRef("pk")) # Use Exists() to avoid potential duplicates. formfield.queryset = formfield.queryset.filter( Exists(formfield.queryset.model._base_manager.filter(complex_filter)), ) def fields_for_model( model, fields=None, exclude=None, widgets=None, formfield_callback=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, *, apply_limit_choices_to=True, form_declared_fields=None, ): """ Return a dictionary containing form fields for the given model. ``fields`` is an optional list of field names. If provided, return only the named fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``localized_fields`` is a list of names of fields which should be localized. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. ``apply_limit_choices_to`` is a boolean indicating if limit_choices_to should be applied to a field's queryset. ``form_declared_fields`` is a dictionary of form fields created directly on a form. """ form_declared_fields = form_declared_fields or {} field_dict = {} ignored = [] opts = model._meta # Avoid circular import from django.db.models import Field as ModelField sortable_private_fields = [ f for f in opts.private_fields if isinstance(f, ModelField) ] for f in sorted( chain(opts.concrete_fields, sortable_private_fields, opts.many_to_many) ): if not getattr(f, "editable", False): if ( fields is not None and f.name in fields and (exclude is None or f.name not in exclude) ): raise FieldError( "'%s' cannot be specified for %s model form as it is a " "non-editable field" % (f.name, model.__name__) ) continue if fields is not None and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in form_declared_fields: field_dict[f.name] = form_declared_fields[f.name] continue kwargs = {} if widgets and f.name in widgets: kwargs["widget"] = widgets[f.name] if localized_fields == ALL_FIELDS or ( localized_fields and f.name in localized_fields ): kwargs["localize"] = True if labels and f.name in labels: kwargs["label"] = labels[f.name] if help_texts and f.name in help_texts: kwargs["help_text"] = help_texts[f.name] if error_messages and f.name in error_messages: kwargs["error_messages"] = error_messages[f.name] if field_classes and f.name in field_classes: kwargs["form_class"] = field_classes[f.name] if formfield_callback is None: formfield = f.formfield(**kwargs) elif not callable(formfield_callback): raise TypeError("formfield_callback must be a function or callable") else: formfield = formfield_callback(f, **kwargs) if formfield: if apply_limit_choices_to: apply_limit_choices_to_to_formfield(formfield) field_dict[f.name] = formfield else: ignored.append(f.name) if fields: field_dict = { f: field_dict.get(f) for f in fields if (not exclude or f not in exclude) and f not in ignored } return field_dict class ModelFormOptions: def __init__(self, options=None): self.model = getattr(options, "model", None) self.fields = getattr(options, "fields", None) self.exclude = getattr(options, "exclude", None) self.widgets = getattr(options, "widgets", None) self.localized_fields = getattr(options, "localized_fields", None) self.labels = getattr(options, "labels", None) self.help_texts = getattr(options, "help_texts", None) self.error_messages = getattr(options, "error_messages", None) self.field_classes = getattr(options, "field_classes", None) self.formfield_callback = getattr(options, "formfield_callback", None) class ModelFormMetaclass(DeclarativeFieldsMetaclass): def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if bases == (BaseModelForm,): return new_class opts = new_class._meta = ModelFormOptions(getattr(new_class, "Meta", None)) # We check if a string was passed to `fields` or `exclude`, # which is likely to be a mistake where the user typed ('foo') instead # of ('foo',) for opt in ["fields", "exclude", "localized_fields"]: value = getattr(opts, opt) if isinstance(value, str) and value != ALL_FIELDS: msg = ( "%(model)s.Meta.%(opt)s cannot be a string. " "Did you mean to type: ('%(value)s',)?" % { "model": new_class.__name__, "opt": opt, "value": value, } ) raise TypeError(msg) if opts.model: # If a model is defined, extract form fields from it. if opts.fields is None and opts.exclude is None: raise ImproperlyConfigured( "Creating a ModelForm without either the 'fields' attribute " "or the 'exclude' attribute is prohibited; form %s " "needs updating." % name ) if opts.fields == ALL_FIELDS: # Sentinel for fields_for_model to indicate "get the list of # fields from the model" opts.fields = None fields = fields_for_model( opts.model, opts.fields, opts.exclude, opts.widgets, opts.formfield_callback, opts.localized_fields, opts.labels, opts.help_texts, opts.error_messages, opts.field_classes, # limit_choices_to will be applied during ModelForm.__init__(). apply_limit_choices_to=False, form_declared_fields=new_class.declared_fields, ) # make sure opts.fields doesn't specify an invalid field none_model_fields = {k for k, v in fields.items() if not v} missing_fields = none_model_fields.difference(new_class.declared_fields) if missing_fields: message = "Unknown field(s) (%s) specified for %s" message %= (", ".join(missing_fields), opts.model.__name__) raise FieldError(message) # Include all the other declared fields. fields.update(new_class.declared_fields) else: fields = new_class.declared_fields new_class.base_fields = fields return new_class class BaseModelForm(BaseForm, AltersData): def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, instance=None, use_required_attribute=None, renderer=None, ): opts = self._meta if opts.model is None: raise ValueError("ModelForm has no model class specified.") if instance is None: # if we didn't get an instance, instantiate a new one self.instance = opts.model() object_data = {} else: self.instance = instance object_data = model_to_dict(instance, opts.fields, opts.exclude) # if initial was provided, it should override the values from instance if initial is not None: object_data.update(initial) # self._validate_(unique|constraints) will be set to True by # BaseModelForm.clean(). It is False by default so overriding # self.clean() and failing to call super will stop # validate_(unique|constraints) from being called. self._validate_unique = False self._validate_constraints = False super().__init__( data, files, auto_id, prefix, object_data, error_class, label_suffix, empty_permitted, use_required_attribute=use_required_attribute, renderer=renderer, ) for formfield in self.fields.values(): apply_limit_choices_to_to_formfield(formfield) def _get_validation_exclusions(self): """ For backwards-compatibility, exclude several types of fields from model validation. See tickets #12507, #12521, #12553. """ exclude = set() # Build up a list of fields that should be excluded from model field # validation and unique checks. for f in self.instance._meta.fields: field = f.name # Exclude fields that aren't on the form. The developer may be # adding these values to the model after form validation. if field not in self.fields: exclude.add(f.name) # Don't perform model validation on fields that were defined # manually on the form and excluded via the ModelForm's Meta # class. See #12901. elif self._meta.fields and field not in self._meta.fields: exclude.add(f.name) elif self._meta.exclude and field in self._meta.exclude: exclude.add(f.name) # Exclude fields that failed form validation. There's no need for # the model fields to validate them as well. elif field in self._errors: exclude.add(f.name) # Exclude empty fields that are not required by the form, if the # underlying model field is required. This keeps the model field # from raising a required error. Note: don't exclude the field from # validation if the model field allows blanks. If it does, the # blank value may be included in a unique check, so cannot be # excluded from validation. else: form_field = self.fields[field] field_value = self.cleaned_data.get(field) if ( not f.blank and not form_field.required and field_value in form_field.empty_values ): exclude.add(f.name) return exclude def clean(self): self._validate_unique = True self._validate_constraints = True return self.cleaned_data def _update_errors(self, errors): # Override any validation error messages defined at the model level # with those defined at the form level. opts = self._meta # Allow the model generated by construct_instance() to raise # ValidationError and have them handled in the same way as others. if hasattr(errors, "error_dict"): error_dict = errors.error_dict else: error_dict = {NON_FIELD_ERRORS: errors} for field, messages in error_dict.items(): if ( field == NON_FIELD_ERRORS and opts.error_messages and NON_FIELD_ERRORS in opts.error_messages ): error_messages = opts.error_messages[NON_FIELD_ERRORS] elif field in self.fields: error_messages = self.fields[field].error_messages else: continue for message in messages: if ( isinstance(message, ValidationError) and message.code in error_messages ): message.message = error_messages[message.code] self.add_error(None, errors) def _post_clean(self): opts = self._meta exclude = self._get_validation_exclusions() # Foreign Keys being used to represent inline relationships # are excluded from basic field value validation. This is for two # reasons: firstly, the value may not be supplied (#12507; the # case of providing new values to the admin); secondly the # object being referred to may not yet fully exist (#12749). # However, these fields *must* be included in uniqueness checks, # so this can't be part of _get_validation_exclusions(). for name, field in self.fields.items(): if isinstance(field, InlineForeignKeyField): exclude.add(name) try: self.instance = construct_instance( self, self.instance, opts.fields, opts.exclude ) except ValidationError as e: self._update_errors(e) try: self.instance.full_clean( exclude=exclude, validate_unique=False, validate_constraints=False ) except ValidationError as e: self._update_errors(e) # Validate uniqueness and constraints if needed. if self._validate_unique: self.validate_unique() if self._validate_constraints: self.validate_constraints() def validate_unique(self): """ Call the instance's validate_unique() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_unique(exclude=exclude) except ValidationError as e: self._update_errors(e) def validate_constraints(self): """ Call the instance's validate_constraints() method and update the form's validation errors if any were raised. """ exclude = self._get_validation_exclusions() try: self.instance.validate_constraints(exclude=exclude) except ValidationError as e: self._update_errors(e) def _save_m2m(self): """ Save the many-to-many fields and generic relations for this form. """ cleaned_data = self.cleaned_data exclude = self._meta.exclude fields = self._meta.fields opts = self.instance._meta # Note that for historical reasons we want to include also # private_fields here. (GenericRelation was previously a fake # m2m field). for f in chain(opts.many_to_many, opts.private_fields): if not hasattr(f, "save_form_data"): continue if fields and f.name not in fields: continue if exclude and f.name in exclude: continue if f.name in cleaned_data: f.save_form_data(self.instance, cleaned_data[f.name]) def save(self, commit=True): """ Save this form's self.instance object if commit=True. Otherwise, add a save_m2m() method to the form which can be called after the instance is saved manually at a later time. Return the model instance. """ if self.errors: raise ValueError( "The %s could not be %s because the data didn't validate." % ( self.instance._meta.object_name, "created" if self.instance._state.adding else "changed", ) ) if commit: # If committing, save the instance and the m2m data immediately. self.instance.save() self._save_m2m() else: # If not committing, add a method to the form to allow deferred # saving of m2m data. self.save_m2m = self._save_m2m return self.instance save.alters_data = True class ModelForm(BaseModelForm, metaclass=ModelFormMetaclass): pass def modelform_factory( model, form=ModelForm, fields=None, exclude=None, formfield_callback=None, widgets=None, localized_fields=None, labels=None, help_texts=None, error_messages=None, field_classes=None, ): """ Return a ModelForm containing form fields for the given model. You can optionally pass a `form` argument to use as a starting point for constructing the ModelForm. ``fields`` is an optional list of field names. If provided, include only the named fields in the returned fields. If omitted or '__all__', use all fields. ``exclude`` is an optional list of field names. If provided, exclude the named fields from the returned fields, even if they are listed in the ``fields`` argument. ``widgets`` is a dictionary of model field names mapped to a widget. ``localized_fields`` is a list of names of fields which should be localized. ``formfield_callback`` is a callable that takes a model field and returns a form field. ``labels`` is a dictionary of model field names mapped to a label. ``help_texts`` is a dictionary of model field names mapped to a help text. ``error_messages`` is a dictionary of model field names mapped to a dictionary of error messages. ``field_classes`` is a dictionary of model field names mapped to a form field class. """ # Create the inner Meta class. FIXME: ideally, we should be able to # construct a ModelForm without creating and passing in a temporary # inner class. # Build up a list of attributes that the Meta object will have. attrs = {"model": model} if fields is not None: attrs["fields"] = fields if exclude is not None: attrs["exclude"] = exclude if widgets is not None: attrs["widgets"] = widgets if localized_fields is not None: attrs["localized_fields"] = localized_fields if labels is not None: attrs["labels"] = labels if help_texts is not None: attrs["help_texts"] = help_texts if error_messages is not None: attrs["error_messages"] = error_messages if field_classes is not None: attrs["field_classes"] = field_classes # If parent form class already has an inner Meta, the Meta we're # creating needs to inherit from the parent's inner meta. bases = (form.Meta,) if hasattr(form, "Meta") else () Meta = type("Meta", bases, attrs) if formfield_callback: Meta.formfield_callback = staticmethod(formfield_callback) # Give this new form class a reasonable name. class_name = model.__name__ + "Form" # Class attributes for the new form class. form_class_attrs = {"Meta": Meta} if getattr(Meta, "fields", None) is None and getattr(Meta, "exclude", None) is None: raise ImproperlyConfigured( "Calling modelform_factory without defining 'fields' or " "'exclude' explicitly is prohibited." ) # Instantiate type(form) in order to use the same metaclass as form. return type(form)(class_name, (form,), form_class_attrs) # ModelFormSets ############################################################## class BaseModelFormSet(BaseFormSet, AltersData): """ A ``FormSet`` for editing a queryset and/or adding new objects to it. """ model = None edit_only = False # Set of fields that must be unique among forms of this set. unique_fields = set() def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, queryset=None, *, initial=None, **kwargs, ): self.queryset = queryset self.initial_extra = initial super().__init__( **{ "data": data, "files": files, "auto_id": auto_id, "prefix": prefix, **kwargs, } ) def initial_form_count(self): """Return the number of forms that are required in this FormSet.""" if not self.is_bound: return len(self.get_queryset()) return super().initial_form_count() def _existing_object(self, pk): if not hasattr(self, "_object_dict"): self._object_dict = {o.pk: o for o in self.get_queryset()} return self._object_dict.get(pk) def _get_to_python(self, field): """ If the field is a related field, fetch the concrete field's (that is, the ultimate pointed-to field's) to_python. """ while field.remote_field is not None: field = field.remote_field.get_related_field() return field.to_python def _construct_form(self, i, **kwargs): pk_required = i < self.initial_form_count() if pk_required: if self.is_bound: pk_key = "%s-%s" % (self.add_prefix(i), self.model._meta.pk.name) try: pk = self.data[pk_key] except KeyError: # The primary key is missing. The user may have tampered # with POST data. pass else: to_python = self._get_to_python(self.model._meta.pk) try: pk = to_python(pk) except ValidationError: # The primary key exists but is an invalid value. The # user may have tampered with POST data. pass else: kwargs["instance"] = self._existing_object(pk) else: kwargs["instance"] = self.get_queryset()[i] elif self.initial_extra: # Set initial values for extra forms try: kwargs["initial"] = self.initial_extra[i - self.initial_form_count()] except IndexError: pass form = super()._construct_form(i, **kwargs) if pk_required: form.fields[self.model._meta.pk.name].required = True return form def get_queryset(self): if not hasattr(self, "_queryset"): if self.queryset is not None: qs = self.queryset else: qs = self.model._default_manager.get_queryset() # If the queryset isn't already ordered we need to add an # artificial ordering here to make sure that all formsets # constructed from this queryset have the same form order. if not qs.ordered: qs = qs.order_by(self.model._meta.pk.name) # Removed queryset limiting here. As per discussion re: #13023 # on django-dev, max_num should not prevent existing # related objects/inlines from being displayed. self._queryset = qs return self._queryset def save_new(self, form, commit=True): """Save and return a new model instance for the given form.""" return form.save(commit=commit) def save_existing(self, form, obj, commit=True): """Save and return an existing model instance for the given form.""" return form.save(commit=commit) def delete_existing(self, obj, commit=True): """Deletes an existing model instance.""" if commit: obj.delete() def save(self, commit=True): """ Save model instances for every form, adding and changing instances as necessary, and return the list of instances. """ if not commit: self.saved_forms = [] def save_m2m(): for form in self.saved_forms: form.save_m2m() self.save_m2m = save_m2m if self.edit_only: return self.save_existing_objects(commit) else: return self.save_existing_objects(commit) + self.save_new_objects(commit) save.alters_data = True def clean(self): self.validate_unique() def validate_unique(self): # Collect unique_checks and date_checks to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [ form for form in self.forms if form.is_valid() and form not in forms_to_delete ] for form in valid_forms: exclude = form._get_validation_exclusions() unique_checks, date_checks = form.instance._get_unique_checks( exclude=exclude, include_meta_constraints=True, ) all_unique_checks.update(unique_checks) all_date_checks.update(date_checks) errors = [] # Do each of the unique checks (unique and unique_together) for uclass, unique_check in all_unique_checks: seen_data = set() for form in valid_forms: # Get the data for the set of fields that must be unique among # the forms. row_data = ( field if field in self.unique_fields else form.cleaned_data[field] for field in unique_check if field in form.cleaned_data ) # Reduce Model instances to their primary key values row_data = tuple( ( d._get_pk_val() if hasattr(d, "_get_pk_val") # Prevent "unhashable type" errors later on. else make_hashable(d) ) for d in row_data ) if row_data and None not in row_data: # if we've already seen it then we have a uniqueness # failure if row_data in seen_data: # poke error messages into the right places and mark # the form as invalid errors.append(self.get_unique_error_message(unique_check)) form._errors[NON_FIELD_ERRORS] = self.error_class( [self.get_form_error()], renderer=self.renderer, ) # Remove the data from the cleaned_data dict since it # was invalid. for field in unique_check: if field in form.cleaned_data: del form.cleaned_data[field] # mark the data as seen seen_data.add(row_data) # iterate over each of the date checks now for date_check in all_date_checks: seen_data = set() uclass, lookup, field, unique_for = date_check for form in valid_forms: # see if we have data for both fields if ( form.cleaned_data and form.cleaned_data[field] is not None and form.cleaned_data[unique_for] is not None ): # if it's a date lookup we need to get the data for all the # fields if lookup == "date": date = form.cleaned_data[unique_for] date_data = (date.year, date.month, date.day)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/boundfield.py
django/forms/boundfield.py
import re from django.core.exceptions import ValidationError from django.forms.utils import RenderableFieldMixin, pretty_name from django.forms.widgets import MultiWidget, Textarea, TextInput from django.utils.functional import cached_property from django.utils.html import format_html, html_safe from django.utils.translation import gettext_lazy as _ __all__ = ("BoundField",) class BoundField(RenderableFieldMixin): "A Field plus data" def __init__(self, form, field, name): self.form = form self.field = field self.name = name self.html_name = form.add_prefix(name) self.html_initial_name = form.add_initial_prefix(name) self.html_initial_id = form.add_initial_prefix(self.auto_id) if self.field.label is None: self.label = pretty_name(name) else: self.label = self.field.label self.help_text = field.help_text or "" self.renderer = form.renderer @cached_property def subwidgets(self): """ Most widgets yield a single subwidget, but others like RadioSelect and CheckboxSelectMultiple produce one subwidget for each choice. This property is cached so that only one database query occurs when rendering ModelChoiceFields. """ id_ = self.field.widget.attrs.get("id") or self.auto_id attrs = {"id": id_} if id_ else {} attrs = self.build_widget_attrs(attrs) return [ BoundWidget(self.field.widget, widget, self.form.renderer) for widget in self.field.widget.subwidgets( self.html_name, self.value(), attrs=attrs ) ] def __bool__(self): # BoundField evaluates to True even if it doesn't have subwidgets. return True def __iter__(self): return iter(self.subwidgets) def __len__(self): return len(self.subwidgets) def __getitem__(self, idx): # Prevent unnecessary reevaluation when accessing BoundField's attrs # from templates. if not isinstance(idx, (int, slice)): raise TypeError( "BoundField indices must be integers or slices, not %s." % type(idx).__name__ ) return self.subwidgets[idx] @property def errors(self): """ Return an ErrorList (empty if there are no errors) for this field. """ return self.form.errors.get( self.name, self.form.error_class(renderer=self.form.renderer) ) @property def template_name(self): return self.field.template_name or self.form.renderer.field_template_name def get_context(self): return {"field": self} def as_widget(self, widget=None, attrs=None, only_initial=False): """ Render the field by rendering the passed widget, adding any HTML attributes passed as attrs. If a widget isn't specified, use the field's default widget. """ widget = widget or self.field.widget if self.field.localize: widget.is_localized = True attrs = attrs or {} attrs = self.build_widget_attrs(attrs, widget) if self.auto_id and "id" not in widget.attrs: attrs.setdefault( "id", self.html_initial_id if only_initial else self.auto_id ) if only_initial and self.html_initial_name in self.form.data: # Propagate the hidden initial value. value = self.form._widget_data_value( self.field.hidden_widget(), self.html_initial_name, ) else: value = self.value() return widget.render( name=self.html_initial_name if only_initial else self.html_name, value=value, attrs=attrs, renderer=self.form.renderer, ) def as_text(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="text">. """ return self.as_widget(TextInput(), attrs, **kwargs) def as_textarea(self, attrs=None, **kwargs): """Return a string of HTML for representing this as a <textarea>.""" return self.as_widget(Textarea(), attrs, **kwargs) def as_hidden(self, attrs=None, **kwargs): """ Return a string of HTML for representing this as an <input type="hidden">. """ return self.as_widget(self.field.hidden_widget(), attrs, **kwargs) @property def data(self): """ Return the data for this BoundField, or None if it wasn't given. """ return self.form._widget_data_value(self.field.widget, self.html_name) def value(self): """ Return the value for this BoundField, using the initial value if the form is not bound or the data otherwise. """ data = self.initial if self.form.is_bound: data = self.field.bound_data(self.data, data) return self.field.prepare_value(data) def _has_changed(self): field = self.field if field.show_hidden_initial: hidden_widget = field.hidden_widget() initial_value = self.form._widget_data_value( hidden_widget, self.html_initial_name, ) try: initial_value = field.to_python(initial_value) except ValidationError: # Always assume data has changed if validation fails. return True else: initial_value = self.initial return field.has_changed(initial_value, self.data) def label_tag(self, contents=None, attrs=None, label_suffix=None, tag=None): """ Wrap the given contents in a <label>, if the field has an ID attribute. contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <label> tag. label_suffix overrides the form's label_suffix. """ contents = contents or self.label if label_suffix is None: label_suffix = ( self.field.label_suffix if self.field.label_suffix is not None else self.form.label_suffix ) # Only add the suffix if the label does not end in punctuation. # Translators: If found as last label character, these punctuation # characters will prevent the default label_suffix to be appended to # the label if label_suffix and contents and contents[-1] not in _(":?.!"): contents = format_html("{}{}", contents, label_suffix) widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id if id_: id_for_label = widget.id_for_label(id_) if id_for_label: attrs = attrs or {} if tag != "legend": attrs = {**attrs, "for": id_for_label} if self.field.required and hasattr(self.form, "required_css_class"): attrs = attrs or {} if "class" in attrs: attrs["class"] += " " + self.form.required_css_class else: attrs["class"] = self.form.required_css_class context = { "field": self, "label": contents, "attrs": attrs, "use_tag": bool(id_), "tag": tag or "label", } return self.form.render(self.form.template_name_label, context) def legend_tag(self, contents=None, attrs=None, label_suffix=None): """ Wrap the given contents in a <legend>, if the field has an ID attribute. Contents should be mark_safe'd to avoid HTML escaping. If contents aren't given, use the field's HTML-escaped label. If attrs are given, use them as HTML attributes on the <legend> tag. label_suffix overrides the form's label_suffix. """ return self.label_tag(contents, attrs, label_suffix, tag="legend") def css_classes(self, extra_classes=None): """ Return a string of space-separated CSS classes for this field. """ if hasattr(extra_classes, "split"): extra_classes = extra_classes.split() extra_classes = set(extra_classes or []) if self.errors and hasattr(self.form, "error_css_class"): extra_classes.add(self.form.error_css_class) if self.field.required and hasattr(self.form, "required_css_class"): extra_classes.add(self.form.required_css_class) return " ".join(extra_classes) @property def is_hidden(self): """Return True if this BoundField's widget is hidden.""" return self.field.widget.is_hidden @property def auto_id(self): """ Calculate and return the ID attribute for this BoundField, if the associated Form has specified auto_id. Return an empty string otherwise. """ auto_id = self.form.auto_id # Boolean or string if auto_id and "%s" in str(auto_id): return auto_id % self.html_name elif auto_id: return self.html_name return "" @property def id_for_label(self): """ Wrapper around the field widget's `id_for_label` method. Useful, for example, for focusing on this field regardless of whether it has a single widget or a MultiWidget. """ widget = self.field.widget id_ = widget.attrs.get("id") or self.auto_id return widget.id_for_label(id_) @cached_property def initial(self): return self.form.get_initial_for_field(self.field, self.name) def build_widget_attrs(self, attrs, widget=None): widget = widget or self.field.widget attrs = dict(attrs) # Copy attrs to avoid modifying the argument. if ( widget.use_required_attribute(self.initial) and self.field.required and self.form.use_required_attribute ): # MultiValueField has require_all_fields: if False, fall back # on subfields. if ( hasattr(self.field, "require_all_fields") and not self.field.require_all_fields and isinstance(self.field.widget, MultiWidget) ): for subfield, subwidget in zip(self.field.fields, widget.widgets): subwidget.attrs["required"] = ( subwidget.use_required_attribute(self.initial) and subfield.required ) else: attrs["required"] = True if self.field.disabled: attrs["disabled"] = True if not widget.is_hidden and self.errors: attrs["aria-invalid"] = "true" # Preserve aria-describedby provided by the attrs argument so user # can set the desired order. if not attrs.get("aria-describedby") and not self.use_fieldset: if aria_describedby := self.aria_describedby: attrs["aria-describedby"] = aria_describedby return attrs @property def aria_describedby(self): # Preserve aria-describedby set on the widget. if self.field.widget.attrs.get("aria-describedby"): return None aria_describedby = [] if self.auto_id and not self.is_hidden: if self.help_text: aria_describedby.append(f"{self.auto_id}_helptext") if self.errors: aria_describedby.append(f"{self.auto_id}_error") return " ".join(aria_describedby) @property def widget_type(self): return re.sub( r"widget$|input$", "", self.field.widget.__class__.__name__.lower() ) @property def use_fieldset(self): """ Return the value of this BoundField widget's use_fieldset attribute. """ return self.field.widget.use_fieldset @html_safe class BoundWidget: """ A container class used for iterating over widgets. This is useful for widgets that have choices. For example, the following can be used in a template: {% for radio in myform.beatles %} <label for="{{ radio.id_for_label }}"> {{ radio.choice_label }} <span class="radio">{{ radio.tag }}</span> </label> {% endfor %} """ def __init__(self, parent_widget, data, renderer): self.parent_widget = parent_widget self.data = data self.renderer = renderer def __str__(self): return self.tag(wrap_label=True) def tag(self, wrap_label=False): context = {"widget": {**self.data, "wrap_label": wrap_label}} return self.parent_widget._render(self.template_name, context, self.renderer) @property def template_name(self): if "template_name" in self.data: return self.data["template_name"] return self.parent_widget.template_name @property def id_for_label(self): return self.data["attrs"].get("id") @property def choice_label(self): return self.data["label"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/widgets.py
django/forms/widgets.py
""" HTML Widget classes """ import copy import datetime import warnings from collections import defaultdict from graphlib import CycleError, TopologicalSorter from itertools import chain from django.forms.utils import flatatt, to_current_timezone from django.templatetags.static import static from django.utils import formats from django.utils.choices import normalize_choices from django.utils.dates import MONTHS from django.utils.formats import get_format from django.utils.html import format_html, html_safe from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ from .renderers import get_default_renderer __all__ = ( "Script", "Media", "MediaDefiningClass", "Widget", "TextInput", "NumberInput", "EmailInput", "URLInput", "ColorInput", "SearchInput", "TelInput", "PasswordInput", "HiddenInput", "MultipleHiddenInput", "FileInput", "ClearableFileInput", "Textarea", "DateInput", "DateTimeInput", "TimeInput", "CheckboxInput", "Select", "NullBooleanSelect", "SelectMultiple", "RadioSelect", "CheckboxSelectMultiple", "MultiWidget", "SplitDateTimeWidget", "SplitHiddenDateTimeWidget", "SelectDateWidget", ) MEDIA_TYPES = ("css", "js") class MediaOrderConflictWarning(RuntimeWarning): pass @html_safe class MediaAsset: element_template = "{path}" def __init__(self, path, **attributes): self._path = path self.attributes = attributes def __eq__(self, other): # Compare the path only, to ensure performant comparison in # Media.merge. return (self.__class__ is other.__class__ and self.path == other.path) or ( isinstance(other, str) and self._path == other ) def __hash__(self): # Hash the path only, to ensure performant comparison in Media.merge. return hash(self._path) def __str__(self): return format_html( self.element_template, path=self.path, attributes=flatatt(self.attributes), ) def __repr__(self): return f"{type(self).__qualname__}({self._path!r})" @property def path(self): """ Ensure an absolute path. Relative paths are resolved via the {% static %} template tag. """ if self._path.startswith(("http://", "https://", "/")): return self._path return static(self._path) class Script(MediaAsset): element_template = '<script src="{path}"{attributes}></script>' def __init__(self, src, **attributes): # Alter the signature to allow src to be passed as a keyword argument. super().__init__(src, **attributes) @html_safe class Media: def __init__(self, media=None, css=None, js=None): if media is not None: css = getattr(media, "css", {}) js = getattr(media, "js", []) else: if css is None: css = {} if js is None: js = [] self._css_lists = [css] self._js_lists = [js] def __repr__(self): return "Media(css=%r, js=%r)" % (self._css, self._js) def __str__(self): return self.render() @property def _css(self): css = defaultdict(list) for css_list in self._css_lists: for medium, sublist in css_list.items(): css[medium].append(sublist) return {medium: self.merge(*lists) for medium, lists in css.items()} @property def _js(self): return self.merge(*self._js_lists) def render(self): return mark_safe( "\n".join( chain.from_iterable( getattr(self, "render_" + name)() for name in MEDIA_TYPES ) ) ) def render_js(self): return [ ( path.__html__() if hasattr(path, "__html__") else format_html('<script src="{}"></script>', self.absolute_path(path)) ) for path in self._js ] def render_css(self): # To keep rendering order consistent, we can't just iterate over # items(). We need to sort the keys, and iterate over the sorted list. media = sorted(self._css) return chain.from_iterable( [ ( path.__html__() if hasattr(path, "__html__") else format_html( '<link href="{}" media="{}" rel="stylesheet">', self.absolute_path(path), medium, ) ) for path in self._css[medium] ] for medium in media ) def absolute_path(self, path): """ Given a relative or absolute path to a static asset, return an absolute path. An absolute path will be returned unchanged while a relative path will be passed to django.templatetags.static.static(). """ if path.startswith(("http://", "https://", "/")): return path return static(path) def __getitem__(self, name): """Return a Media object that only contains media of the given type.""" if name in MEDIA_TYPES: return Media(**{str(name): getattr(self, "_" + name)}) raise KeyError('Unknown media type "%s"' % name) @staticmethod def merge(*lists): """ Merge lists while trying to keep the relative order of the elements. Warn if the lists have the same elements in a different relative order. For static assets it can be important to have them included in the DOM in a certain order. In JavaScript you may not be able to reference a global or in CSS you might want to override a style. """ ts = TopologicalSorter() for head, *tail in filter(None, lists): ts.add(head) # Ensure that the first items are included. for item in tail: if head != item: # Avoid circular dependency to self. ts.add(item, head) head = item try: return list(ts.static_order()) except CycleError: warnings.warn( "Detected duplicate Media files in an opposite order: {}".format( ", ".join(repr(list_) for list_ in lists) ), MediaOrderConflictWarning, ) return list(dict.fromkeys(chain.from_iterable(filter(None, lists)))) def __add__(self, other): combined = Media() combined._css_lists = self._css_lists[:] combined._js_lists = self._js_lists[:] for item in other._css_lists: if item and item not in self._css_lists: combined._css_lists.append(item) for item in other._js_lists: if item and item not in self._js_lists: combined._js_lists.append(item) return combined def media_property(cls): def _media(self): # Get the media property of the superclass, if it exists sup_cls = super(cls, self) try: base = sup_cls.media except AttributeError: base = Media() # Get the media definition for this class definition = getattr(cls, "Media", None) if definition: extend = getattr(definition, "extend", True) if extend: if extend is True: m = base else: m = Media() for medium in extend: m += base[medium] return m + Media(definition) return Media(definition) return base return property(_media) class MediaDefiningClass(type): """ Metaclass for classes that can have media definitions. """ def __new__(mcs, name, bases, attrs): new_class = super().__new__(mcs, name, bases, attrs) if "media" not in attrs: new_class.media = media_property(new_class) return new_class class Widget(metaclass=MediaDefiningClass): needs_multipart_form = False # Determines does this widget need multipart form is_localized = False is_required = False supports_microseconds = True use_fieldset = False def __init__(self, attrs=None): self.attrs = {} if attrs is None else attrs.copy() def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() memo[id(self)] = obj return obj @property def is_hidden(self): return self.input_type == "hidden" if hasattr(self, "input_type") else False def subwidgets(self, name, value, attrs=None): context = self.get_context(name, value, attrs) yield context["widget"] def format_value(self, value): """ Return a value as it should appear when rendered in a template. """ if value == "" or value is None: return None if self.is_localized: return formats.localize_input(value) return str(value) def get_context(self, name, value, attrs): return { "widget": { "name": name, "is_hidden": self.is_hidden, "required": self.is_required, "value": self.format_value(value), "attrs": self.build_attrs(self.attrs, attrs), "template_name": self.template_name, }, } def render(self, name, value, attrs=None, renderer=None): """Render the widget as an HTML string.""" context = self.get_context(name, value, attrs) return self._render(self.template_name, context, renderer) def _render(self, template_name, context, renderer=None): if renderer is None: renderer = get_default_renderer() return mark_safe(renderer.render(template_name, context)) def build_attrs(self, base_attrs, extra_attrs=None): """Build an attribute dictionary.""" return {**base_attrs, **(extra_attrs or {})} def value_from_datadict(self, data, files, name): """ Given a dictionary of data and this widget's name, return the value of this widget or None if it's not provided. """ return data.get(name) def value_omitted_from_data(self, data, files, name): return name not in data def id_for_label(self, id_): """ Return the HTML ID attribute of this Widget for use by a <label>, given the ID of the field. Return an empty string if no ID is available. This hook is necessary because some widgets have multiple HTML elements and, thus, multiple IDs. In that case, this method should return an ID value that corresponds to the first ID in the widget's tags. """ return id_ def use_required_attribute(self, initial): return not self.is_hidden class Input(Widget): """ Base class for all <input> widgets. """ input_type = None # Subclasses must define this. template_name = "django/forms/widgets/input.html" def __init__(self, attrs=None): if attrs is not None: attrs = attrs.copy() self.input_type = attrs.pop("type", self.input_type) super().__init__(attrs) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["type"] = self.input_type return context class TextInput(Input): input_type = "text" template_name = "django/forms/widgets/text.html" class NumberInput(Input): input_type = "number" template_name = "django/forms/widgets/number.html" class EmailInput(Input): input_type = "email" template_name = "django/forms/widgets/email.html" class URLInput(Input): input_type = "url" template_name = "django/forms/widgets/url.html" class ColorInput(Input): input_type = "color" template_name = "django/forms/widgets/color.html" class SearchInput(Input): input_type = "search" template_name = "django/forms/widgets/search.html" class TelInput(Input): input_type = "tel" template_name = "django/forms/widgets/tel.html" class PasswordInput(Input): input_type = "password" template_name = "django/forms/widgets/password.html" def __init__(self, attrs=None, render_value=False): super().__init__(attrs) self.render_value = render_value def get_context(self, name, value, attrs): if not self.render_value: value = None return super().get_context(name, value, attrs) class HiddenInput(Input): input_type = "hidden" template_name = "django/forms/widgets/hidden.html" class MultipleHiddenInput(HiddenInput): """ Handle <input type="hidden"> for fields that have a list of values. """ template_name = "django/forms/widgets/multiple_hidden.html" def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) final_attrs = context["widget"]["attrs"] id_ = context["widget"]["attrs"].get("id") subwidgets = [] for index, value_ in enumerate(context["widget"]["value"]): widget_attrs = final_attrs.copy() if id_: # An ID attribute was given. Add a numeric index as a suffix # so that the inputs don't all have the same ID attribute. widget_attrs["id"] = "%s_%s" % (id_, index) widget = HiddenInput() widget.is_required = self.is_required subwidgets.append(widget.get_context(name, value_, widget_attrs)["widget"]) context["widget"]["subwidgets"] = subwidgets return context def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def format_value(self, value): return [] if value is None else value class FileInput(Input): allow_multiple_selected = False input_type = "file" needs_multipart_form = True template_name = "django/forms/widgets/file.html" def __init__(self, attrs=None): if ( attrs is not None and not self.allow_multiple_selected and attrs.get("multiple", False) ): raise ValueError( "%s doesn't support uploading multiple files." % self.__class__.__qualname__ ) if self.allow_multiple_selected: if attrs is None: attrs = {"multiple": True} else: attrs.setdefault("multiple", True) super().__init__(attrs) def format_value(self, value): """File input never renders a value.""" return def value_from_datadict(self, data, files, name): "File widgets take data from FILES, not POST" getter = files.get if self.allow_multiple_selected: try: getter = files.getlist except AttributeError: pass return getter(name) def value_omitted_from_data(self, data, files, name): return name not in files def use_required_attribute(self, initial): return super().use_required_attribute(initial) and not initial FILE_INPUT_CONTRADICTION = object() class ClearableFileInput(FileInput): clear_checkbox_label = _("Clear") initial_text = _("Currently") input_text = _("Change") template_name = "django/forms/widgets/clearable_file_input.html" checked = False use_fieldset = False def clear_checkbox_name(self, name): """ Given the name of the file input, return the name of the clear checkbox input. """ return name + "-clear" def clear_checkbox_id(self, name): """ Given the name of the clear checkbox input, return the HTML id for it. """ return name + "_id" def is_initial(self, value): """ Return whether value is considered to be initial value. """ return bool(value and getattr(value, "url", False)) def format_value(self, value): """ Return the file object if it has a defined url attribute. """ if self.is_initial(value): return value def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) checkbox_name = self.clear_checkbox_name(name) checkbox_id = self.clear_checkbox_id(checkbox_name) context["widget"].update( { "checkbox_name": checkbox_name, "checkbox_id": checkbox_id, "is_initial": self.is_initial(value), "input_text": self.input_text, "initial_text": self.initial_text, "clear_checkbox_label": self.clear_checkbox_label, } ) context["widget"]["attrs"].setdefault("disabled", False) context["widget"]["attrs"]["checked"] = self.checked return context def value_from_datadict(self, data, files, name): upload = super().value_from_datadict(data, files, name) self.checked = self.clear_checkbox_name(name) in data if not self.is_required and CheckboxInput().value_from_datadict( data, files, self.clear_checkbox_name(name) ): if upload: # If the user contradicts themselves (uploads a new file AND # checks the "clear" checkbox), we return a unique marker # object that FileField will turn into a ValidationError. return FILE_INPUT_CONTRADICTION # False signals to clear any existing value, as opposed to just # None return False return upload def value_omitted_from_data(self, data, files, name): return ( super().value_omitted_from_data(data, files, name) and self.clear_checkbox_name(name) not in data ) class Textarea(Widget): template_name = "django/forms/widgets/textarea.html" def __init__(self, attrs=None): # Use slightly better defaults than HTML's 20x2 box default_attrs = {"cols": "40", "rows": "10"} if attrs: default_attrs.update(attrs) super().__init__(default_attrs) class DateTimeBaseInput(TextInput): format_key = "" supports_microseconds = False def __init__(self, attrs=None, format=None): super().__init__(attrs) self.format = format or None def format_value(self, value): return formats.localize_input( value, self.format or formats.get_format(self.format_key)[0] ) class DateInput(DateTimeBaseInput): format_key = "DATE_INPUT_FORMATS" template_name = "django/forms/widgets/date.html" class DateTimeInput(DateTimeBaseInput): format_key = "DATETIME_INPUT_FORMATS" template_name = "django/forms/widgets/datetime.html" class TimeInput(DateTimeBaseInput): format_key = "TIME_INPUT_FORMATS" template_name = "django/forms/widgets/time.html" # Defined at module level so that CheckboxInput is picklable (#17976) def boolean_check(v): return not (v is False or v is None or v == "") class CheckboxInput(Input): input_type = "checkbox" template_name = "django/forms/widgets/checkbox.html" def __init__(self, attrs=None, check_test=None): super().__init__(attrs) # check_test is a callable that takes a value and returns True # if the checkbox should be checked for that value. self.check_test = boolean_check if check_test is None else check_test def format_value(self, value): """Only return the 'value' attribute if value isn't empty.""" if value is True or value is False or value is None or value == "": return return str(value) def get_context(self, name, value, attrs): if self.check_test(value): attrs = {**(attrs or {}), "checked": True} return super().get_context(name, value, attrs) def value_from_datadict(self, data, files, name): if name not in data: # A missing value means False because HTML form submission does not # send results for unselected checkboxes. return False value = data.get(name) # Translate true and false strings to boolean values. values = {"true": True, "false": False} if isinstance(value, str): value = values.get(value.lower(), value) return bool(value) def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class ChoiceWidget(Widget): allow_multiple_selected = False input_type = None template_name = None option_template_name = None add_id_index = True checked_attribute = {"checked": True} option_inherits_attrs = True def __init__(self, attrs=None, choices=()): super().__init__(attrs) self.choices = choices def __deepcopy__(self, memo): obj = copy.copy(self) obj.attrs = self.attrs.copy() obj.choices = copy.copy(self.choices) memo[id(self)] = obj return obj def subwidgets(self, name, value, attrs=None): """ Yield all "subwidgets" of this widget. Used to enable iterating options from a BoundField for choice widgets. """ value = self.format_value(value) yield from self.options(name, value, attrs) def options(self, name, value, attrs=None): """Yield a flat list of options for this widget.""" for group in self.optgroups(name, value, attrs): yield from group[1] def optgroups(self, name, value, attrs=None): """Return a list of optgroups for this widget.""" groups = [] has_selected = False for index, (option_value, option_label) in enumerate(self.choices): if option_value is None: option_value = "" subgroup = [] if isinstance(option_label, (list, tuple)): group_name = option_value subindex = 0 choices = option_label else: group_name = None subindex = None choices = [(option_value, option_label)] groups.append((group_name, subgroup, index)) for subvalue, sublabel in choices: selected = (not has_selected or self.allow_multiple_selected) and str( subvalue ) in value has_selected |= selected subgroup.append( self.create_option( name, subvalue, sublabel, selected, index, subindex=subindex, attrs=attrs, ) ) if subindex is not None: subindex += 1 return groups def create_option( self, name, value, label, selected, index, subindex=None, attrs=None ): index = str(index) if subindex is None else "%s_%s" % (index, subindex) option_attrs = ( self.build_attrs(self.attrs, attrs) if self.option_inherits_attrs else {} ) if selected: option_attrs.update(self.checked_attribute) if "id" in option_attrs: option_attrs["id"] = self.id_for_label(option_attrs["id"], index) return { "name": name, "value": value, "label": label, "selected": selected, "index": index, "attrs": option_attrs, "type": self.input_type, "template_name": self.option_template_name, "wrap_label": True, } def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) context["widget"]["optgroups"] = self.optgroups( name, context["widget"]["value"], attrs ) return context def id_for_label(self, id_, index="0"): """ Use an incremented id for each option where the main widget references the zero index. """ if id_ and self.add_id_index: id_ = "%s_%s" % (id_, index) return id_ def value_from_datadict(self, data, files, name): getter = data.get if self.allow_multiple_selected: try: getter = data.getlist except AttributeError: pass return getter(name) def format_value(self, value): """Return selected values as a list.""" if value is None and self.allow_multiple_selected: return [] if not isinstance(value, (tuple, list)): value = [value] return [str(v) if v is not None else "" for v in value] @property def choices(self): return self._choices @choices.setter def choices(self, value): self._choices = normalize_choices(value) class Select(ChoiceWidget): input_type = "select" template_name = "django/forms/widgets/select.html" option_template_name = "django/forms/widgets/select_option.html" add_id_index = False checked_attribute = {"selected": True} option_inherits_attrs = False def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.allow_multiple_selected: context["widget"]["attrs"]["multiple"] = True return context @staticmethod def _choice_has_empty_value(choice): """Return True if the choice's value is empty string or None.""" value, _ = choice return value is None or value == "" def use_required_attribute(self, initial): """ Don't render 'required' if the first <option> has a value, as that's invalid HTML. """ use_required_attribute = super().use_required_attribute(initial) # 'required' is always okay for <select multiple>. if self.allow_multiple_selected: return use_required_attribute first_choice = next(iter(self.choices), None) return ( use_required_attribute and first_choice is not None and self._choice_has_empty_value(first_choice) ) class NullBooleanSelect(Select): """ A Select Widget intended to be used with NullBooleanField. """ def __init__(self, attrs=None): choices = ( ("unknown", _("Unknown")), ("true", _("Yes")), ("false", _("No")), ) super().__init__(attrs, choices) def format_value(self, value): try: return { True: "true", False: "false", "true": "true", "false": "false", # For backwards compatibility with Django < 2.2. "2": "true", "3": "false", }[value] except KeyError: return "unknown" def value_from_datadict(self, data, files, name): value = data.get(name) return { True: True, "True": True, "False": False, False: False, "true": True, "false": False, # For backwards compatibility with Django < 2.2. "2": True, "3": False, }.get(value) class SelectMultiple(Select): allow_multiple_selected = True def value_from_datadict(self, data, files, name): try: getter = data.getlist except AttributeError: getter = data.get return getter(name) def value_omitted_from_data(self, data, files, name): # An unselected <select multiple> doesn't appear in POST data, so it's # never known if the value is actually omitted. return False class RadioSelect(ChoiceWidget): input_type = "radio" template_name = "django/forms/widgets/radio.html" option_template_name = "django/forms/widgets/radio_option.html" use_fieldset = True def id_for_label(self, id_, index=None): """ Don't include for="field_0" in <label> to improve accessibility when using a screen reader, in addition clicking such a label would toggle the first input. """ if index is None: return "" return super().id_for_label(id_, index) class CheckboxSelectMultiple(RadioSelect): allow_multiple_selected = True input_type = "checkbox" template_name = "django/forms/widgets/checkbox_select.html" option_template_name = "django/forms/widgets/checkbox_option.html" def use_required_attribute(self, initial): # Don't use the 'required' attribute because browser validation would # require all checkboxes to be checked instead of at least one. return False def value_omitted_from_data(self, data, files, name): # HTML checkboxes don't appear in POST data if not checked, so it's # never known if the value is actually omitted. return False class MultiWidget(Widget): """ A widget that is composed of multiple widgets. In addition to the values added by Widget.get_context(), this widget adds a list of subwidgets to the context as widget['subwidgets']. These can be looped over and rendered like normal widgets. You'll probably want to use this class with MultiValueField. """ template_name = "django/forms/widgets/multiwidget.html" use_fieldset = True def __init__(self, widgets, attrs=None): if isinstance(widgets, dict): self.widgets_names = [("_%s" % name) if name else "" for name in widgets] widgets = widgets.values() else: self.widgets_names = ["_%s" % i for i in range(len(widgets))] self.widgets = [w() if isinstance(w, type) else w for w in widgets] super().__init__(attrs) @property def is_hidden(self): return all(w.is_hidden for w in self.widgets) def get_context(self, name, value, attrs): context = super().get_context(name, value, attrs) if self.is_localized: for widget in self.widgets: widget.is_localized = self.is_localized # value is a list/tuple of values, each corresponding to a widget # in self.widgets. if not isinstance(value, (list, tuple)): value = self.decompress(value) final_attrs = context["widget"]["attrs"] input_type = final_attrs.pop("type", None) id_ = final_attrs.get("id") subwidgets = [] for i, (widget_name, widget) in enumerate( zip(self.widgets_names, self.widgets) ): if input_type is not None: widget.input_type = input_type widget_name = name + widget_name try: widget_value = value[i] except IndexError: widget_value = None if id_: widget_attrs = final_attrs.copy() widget_attrs["id"] = "%s_%s" % (id_, i) else: widget_attrs = final_attrs subwidgets.append( widget.get_context(widget_name, widget_value, widget_attrs)["widget"] ) context["widget"]["subwidgets"] = subwidgets return context def id_for_label(self, id_): return "" def value_from_datadict(self, data, files, name): return [ widget.value_from_datadict(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ] def value_omitted_from_data(self, data, files, name): return all( widget.value_omitted_from_data(data, files, name + widget_name) for widget_name, widget in zip(self.widgets_names, self.widgets) ) def decompress(self, value): """
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/utils.py
django/forms/utils.py
import json from collections import UserList from django.conf import settings from django.core.exceptions import ValidationError from django.forms.renderers import get_default_renderer from django.utils import timezone from django.utils.html import escape, format_html_join from django.utils.safestring import mark_safe from django.utils.translation import gettext_lazy as _ def pretty_name(name): """Convert 'first_name' to 'First name'.""" if not name: return "" return name.replace("_", " ").capitalize() def flatatt(attrs): """ Convert a dictionary of attributes to a single string. The returned string will contain a leading space followed by key="value", XML-style pairs. In the case of a boolean value, the key will appear without a value. It is assumed that the keys do not need to be XML-escaped. If the passed dictionary is empty, then return an empty string. The result is passed through 'mark_safe' (by way of 'format_html_join'). """ key_value_attrs = [] boolean_attrs = [] for attr, value in attrs.items(): if isinstance(value, bool): if value: boolean_attrs.append((attr,)) elif value is not None: key_value_attrs.append((attr, value)) return format_html_join("", ' {}="{}"', sorted(key_value_attrs)) + format_html_join( "", " {}", sorted(boolean_attrs) ) class RenderableMixin: def get_context(self): raise NotImplementedError( "Subclasses of RenderableMixin must provide a get_context() method." ) def render(self, template_name=None, context=None, renderer=None): renderer = renderer or self.renderer template = template_name or self.template_name context = context or self.get_context() return mark_safe(renderer.render(template, context)) __str__ = render __html__ = render class RenderableFieldMixin(RenderableMixin): def as_field_group(self): return self.render() def as_hidden(self): raise NotImplementedError( "Subclasses of RenderableFieldMixin must provide an as_hidden() method." ) def as_widget(self): raise NotImplementedError( "Subclasses of RenderableFieldMixin must provide an as_widget() method." ) def __str__(self): """Render this field as an HTML widget.""" if self.field.show_hidden_initial: return self.as_widget() + self.as_hidden(only_initial=True) return self.as_widget() __html__ = __str__ class RenderableFormMixin(RenderableMixin): def as_p(self): """Render as <p> elements.""" return self.render(self.template_name_p) def as_table(self): """Render as <tr> elements excluding the surrounding <table> tag.""" return self.render(self.template_name_table) def as_ul(self): """Render as <li> elements excluding the surrounding <ul> tag.""" return self.render(self.template_name_ul) def as_div(self): """Render as <div> elements.""" return self.render(self.template_name_div) class RenderableErrorMixin(RenderableMixin): def as_json(self, escape_html=False): return json.dumps(self.get_json_data(escape_html)) def as_text(self): return self.render(self.template_name_text) def as_ul(self): return self.render(self.template_name_ul) class ErrorDict(dict, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. The dictionary keys are the field names, and the values are the errors. """ template_name = "django/forms/errors/dict/default.html" template_name_text = "django/forms/errors/dict/text.txt" template_name_ul = "django/forms/errors/dict/ul.html" def __init__(self, *args, renderer=None, **kwargs): super().__init__(*args, **kwargs) self.renderer = renderer or get_default_renderer() def as_data(self): return {f: e.as_data() for f, e in self.items()} def get_json_data(self, escape_html=False): return {f: e.get_json_data(escape_html) for f, e in self.items()} def get_context(self): return { "errors": self.items(), "error_class": "errorlist", } class ErrorList(UserList, list, RenderableErrorMixin): """ A collection of errors that knows how to display itself in various formats. """ template_name = "django/forms/errors/list/default.html" template_name_text = "django/forms/errors/list/text.txt" template_name_ul = "django/forms/errors/list/ul.html" def __init__(self, initlist=None, error_class=None, renderer=None, field_id=None): super().__init__(initlist) if error_class is None: self.error_class = "errorlist" else: self.error_class = "errorlist {}".format(error_class) self.renderer = renderer or get_default_renderer() self.field_id = field_id def as_data(self): return ValidationError(self.data).error_list def copy(self): copy = super().copy() copy.error_class = self.error_class copy.renderer = self.renderer return copy def get_json_data(self, escape_html=False): errors = [] for error in self.as_data(): message = next(iter(error)) errors.append( { "message": escape(message) if escape_html else message, "code": error.code or "", } ) return errors def get_context(self): return { "errors": self, "error_class": self.error_class, } def __repr__(self): return repr(list(self)) def __contains__(self, item): return item in list(self) def __eq__(self, other): return list(self) == other def __getitem__(self, i): error = self.data[i] if isinstance(error, ValidationError): return next(iter(error)) return error def __reduce_ex__(self, *args, **kwargs): # The `list` reduce function returns an iterator as the fourth element # that is normally used for repopulating. Since we only inherit from # `list` for `isinstance` backward compatibility (Refs #17413) we # nullify this iterator as it would otherwise result in duplicate # entries. (Refs #23594) info = super(UserList, self).__reduce_ex__(*args, **kwargs) return info[:3] + (None, None) # Utilities for time zone support in DateTimeField et al. def from_current_timezone(value): """ When time zone support is enabled, convert naive datetimes entered in the current time zone to aware datetimes. """ if settings.USE_TZ and value is not None and timezone.is_naive(value): current_timezone = timezone.get_current_timezone() try: if timezone._datetime_ambiguous_or_imaginary(value, current_timezone): raise ValueError("Ambiguous or non-existent time.") return timezone.make_aware(value, current_timezone) except Exception as exc: raise ValidationError( _( "%(datetime)s couldn’t be interpreted " "in time zone %(current_timezone)s; it " "may be ambiguous or it may not exist." ), code="ambiguous_timezone", params={"datetime": value, "current_timezone": current_timezone}, ) from exc return value def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): return timezone.make_naive(value) return value
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/fields.py
django/forms/fields.py
""" Field classes. """ import copy import datetime import json import math import operator import os import re import uuid from decimal import Decimal, DecimalException from io import BytesIO from urllib.parse import urlsplit, urlunsplit from django.core import validators from django.core.exceptions import ValidationError from django.forms.boundfield import BoundField from django.forms.utils import from_current_timezone, to_current_timezone from django.forms.widgets import ( FILE_INPUT_CONTRADICTION, CheckboxInput, ClearableFileInput, DateInput, DateTimeInput, EmailInput, FileInput, HiddenInput, MultipleHiddenInput, NullBooleanSelect, NumberInput, Select, SelectMultiple, SplitDateTimeWidget, SplitHiddenDateTimeWidget, Textarea, TextInput, TimeInput, URLInput, ) from django.utils import formats from django.utils.choices import normalize_choices from django.utils.dateparse import parse_datetime, parse_duration from django.utils.duration import duration_string from django.utils.ipv6 import MAX_IPV6_ADDRESS_LENGTH, clean_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 __all__ = ( "Field", "CharField", "IntegerField", "DateField", "TimeField", "DateTimeField", "DurationField", "RegexField", "EmailField", "FileField", "ImageField", "URLField", "BooleanField", "NullBooleanField", "ChoiceField", "MultipleChoiceField", "ComboField", "MultiValueField", "FloatField", "DecimalField", "SplitDateTimeField", "GenericIPAddressField", "FilePathField", "JSONField", "SlugField", "TypedChoiceField", "TypedMultipleChoiceField", "UUIDField", ) class Field: widget = TextInput # Default widget to use when rendering this type of Field. hidden_widget = ( HiddenInput # Default widget to use when rendering this as "hidden". ) default_validators = [] # Default set of validators # Add an 'invalid' entry to default_error_message if you want a specific # field error message not raised by the field validators. default_error_messages = { "required": _("This field is required."), } empty_values = list(validators.EMPTY_VALUES) bound_field_class = None def __init__( self, *, required=True, widget=None, label=None, initial=None, help_text="", error_messages=None, show_hidden_initial=False, validators=(), localize=False, disabled=False, label_suffix=None, template_name=None, bound_field_class=None, ): # required -- Boolean that specifies whether the field is required. # True by default. # widget -- A Widget class, or instance of a Widget class, that should # be used for this Field when displaying it. Each Field has a # default Widget that it'll use if you don't specify this. In # most cases, the default widget is TextInput. # label -- A verbose name for this field, for use in displaying this # field in a form. By default, Django will use a "pretty" # version of the form field name, if the Field is part of a # Form. # initial -- A value to use in this Field's initial display. This value # is *not* used as a fallback if data isn't given. # help_text -- An optional string to use as "help text" for this Field. # error_messages -- An optional dictionary to override the default # messages that the field will raise. # show_hidden_initial -- Boolean that specifies if it is needed to # render a hidden widget with initial value # after widget. # validators -- List of additional validators to use # localize -- Boolean that specifies if the field should be localized. # disabled -- Boolean that specifies whether the field is disabled, # that is its widget is shown in the form but not editable. # label_suffix -- Suffix to be added to the label. Overrides # form's label_suffix. # bound_field_class -- BoundField class to use in # Field.get_bound_field. self.required, self.label, self.initial = required, label, initial self.show_hidden_initial = show_hidden_initial self.help_text = help_text self.disabled = disabled self.label_suffix = label_suffix self.bound_field_class = bound_field_class or self.bound_field_class widget = widget or self.widget if isinstance(widget, type): widget = widget() else: widget = copy.deepcopy(widget) # Trigger the localization machinery if needed. self.localize = localize if self.localize: widget.is_localized = True # Let the widget know whether it should display as required. widget.is_required = self.required # Hook into self.widget_attrs() for any Field-specific HTML attributes. extra_attrs = self.widget_attrs(widget) if extra_attrs: widget.attrs.update(extra_attrs) self.widget = widget messages = {} for c in reversed(self.__class__.__mro__): messages.update(getattr(c, "default_error_messages", {})) messages.update(error_messages or {}) self.error_messages = messages self.validators = [*self.default_validators, *validators] self.template_name = template_name super().__init__() def prepare_value(self, value): return value def to_python(self, value): return value def validate(self, value): if value in self.empty_values and self.required: raise ValidationError(self.error_messages["required"], code="required") def run_validators(self, value): if value in self.empty_values: return errors = [] for v in self.validators: try: v(value) except ValidationError as e: if hasattr(e, "code") and e.code in self.error_messages: e.message = self.error_messages[e.code] errors.extend(e.error_list) if errors: raise ValidationError(errors) def clean(self, value): """ Validate the given value and return its "cleaned" value as an appropriate Python object. Raise ValidationError for any errors. """ value = self.to_python(value) self.validate(value) self.run_validators(value) return value def bound_data(self, data, initial): """ Return the value that should be shown for this field on render of a bound form, given the submitted POST data for the field and the initial data, if any. For most fields, this will simply be data; FileFields need to handle it a bit differently. """ if self.disabled: return initial return data def widget_attrs(self, widget): """ Given a Widget instance (*not* a Widget class), return a dictionary of any HTML attributes that should be added to the Widget, based on this Field. """ return {} def has_changed(self, initial, data): """Return True if data differs from initial.""" # Always return False if the field is disabled since self.bound_data # always uses the initial value in this case. if self.disabled: return False try: data = self.to_python(data) if hasattr(self, "_coerce"): return self._coerce(data) != self._coerce(initial) except ValidationError: return True # For purposes of seeing whether something has changed, None is # the same as an empty string, if the data or initial value we get # is None, replace it with ''. initial_value = initial if initial is not None else "" data_value = data if data is not None else "" return initial_value != data_value def get_bound_field(self, form, field_name): """ Return a BoundField instance that will be used when accessing the form field in a template. """ bound_field_class = ( self.bound_field_class or form.bound_field_class or BoundField ) return bound_field_class(form, self, field_name) def __deepcopy__(self, memo): result = copy.copy(self) memo[id(self)] = result result.widget = copy.deepcopy(self.widget, memo) result.error_messages = self.error_messages.copy() result.validators = self.validators[:] return result def _clean_bound_field(self, bf): value = bf.initial if self.disabled else bf.data return self.clean(value) class CharField(Field): def __init__( self, *, max_length=None, min_length=None, strip=True, empty_value="", **kwargs ): self.max_length = max_length self.min_length = min_length self.strip = strip self.empty_value = empty_value super().__init__(**kwargs) if min_length is not None: self.validators.append(validators.MinLengthValidator(int(min_length))) if max_length is not None: self.validators.append(validators.MaxLengthValidator(int(max_length))) self.validators.append(validators.ProhibitNullCharactersValidator()) def to_python(self, value): """Return a string.""" if value not in self.empty_values: value = str(value) if self.strip: value = value.strip() if value in self.empty_values: return self.empty_value return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if self.max_length is not None and not widget.is_hidden: # The HTML attribute is maxlength, not max_length. attrs["maxlength"] = str(self.max_length) if self.min_length is not None and not widget.is_hidden: # The HTML attribute is minlength, not min_length. attrs["minlength"] = str(self.min_length) return attrs class IntegerField(Field): widget = NumberInput default_error_messages = { "invalid": _("Enter a whole number."), } re_decimal = _lazy_re_compile(r"\.0*\s*$") def __init__(self, *, max_value=None, min_value=None, step_size=None, **kwargs): self.max_value, self.min_value, self.step_size = max_value, min_value, step_size if kwargs.get("localize") and self.widget == NumberInput: # Localized number input is not well supported on most browsers kwargs.setdefault("widget", super().widget) super().__init__(**kwargs) if max_value is not None: self.validators.append(validators.MaxValueValidator(max_value)) if min_value is not None: self.validators.append(validators.MinValueValidator(min_value)) if step_size is not None: self.validators.append( validators.StepValueValidator(step_size, offset=min_value) ) def to_python(self, value): """ Validate that int() can be called on the input. Return the result of int() or None for empty values. """ value = super().to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) # Strip trailing decimal and zeros. try: value = int(self.re_decimal.sub("", str(value))) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput): if self.min_value is not None: attrs["min"] = self.min_value if self.max_value is not None: attrs["max"] = self.max_value if self.step_size is not None: attrs["step"] = self.step_size return attrs class FloatField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def to_python(self, value): """ Validate that float() can be called on the input. Return the result of float() or None for empty values. """ value = super(IntegerField, self).to_python(value) if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = float(value) except (ValueError, TypeError): raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not math.isfinite(value): raise ValidationError(self.error_messages["invalid"], code="invalid") def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.step_size is not None: step = str(self.step_size) else: step = "any" attrs.setdefault("step", step) return attrs class DecimalField(IntegerField): default_error_messages = { "invalid": _("Enter a number."), } def __init__( self, *, max_value=None, min_value=None, max_digits=None, decimal_places=None, **kwargs, ): self.max_digits, self.decimal_places = max_digits, decimal_places super().__init__(max_value=max_value, min_value=min_value, **kwargs) self.validators.append(validators.DecimalValidator(max_digits, decimal_places)) def to_python(self, value): """ Validate that the input is a decimal number. Return a Decimal instance or None for empty values. Ensure that there are no more than max_digits in the number and no more than decimal_places digits after the decimal point. """ if value in self.empty_values: return None if self.localize: value = formats.sanitize_separators(value) try: value = Decimal(str(value)) except DecimalException: raise ValidationError(self.error_messages["invalid"], code="invalid") return value def validate(self, value): super().validate(value) if value in self.empty_values: return if not value.is_finite(): raise ValidationError( self.error_messages["invalid"], code="invalid", params={"value": value}, ) def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, NumberInput) and "step" not in widget.attrs: if self.decimal_places is not None: # Use exponential notation for small values since they might # be parsed as 0 otherwise. ref #20765 step = str(Decimal(1).scaleb(-self.decimal_places)).lower() else: step = "any" attrs.setdefault("step", step) return attrs class BaseTemporalField(Field): def __init__(self, *, input_formats=None, **kwargs): super().__init__(**kwargs) if input_formats is not None: self.input_formats = input_formats def to_python(self, value): value = value.strip() # Try to strptime against each input format. for format in self.input_formats: try: return self.strptime(value, format) except (ValueError, TypeError): continue raise ValidationError(self.error_messages["invalid"], code="invalid") def strptime(self, value, format): raise NotImplementedError("Subclasses must define this method.") class DateField(BaseTemporalField): widget = DateInput input_formats = formats.get_format_lazy("DATE_INPUT_FORMATS") default_error_messages = { "invalid": _("Enter a valid date."), } def to_python(self, value): """ Validate that the input can be converted to a date. Return a Python datetime.date object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return value.date() if isinstance(value, datetime.date): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).date() class TimeField(BaseTemporalField): widget = TimeInput input_formats = formats.get_format_lazy("TIME_INPUT_FORMATS") default_error_messages = {"invalid": _("Enter a valid time.")} def to_python(self, value): """ Validate that the input can be converted to a time. Return a Python datetime.time object. """ if value in self.empty_values: return None if isinstance(value, datetime.time): return value return super().to_python(value) def strptime(self, value, format): return datetime.datetime.strptime(value, format).time() class DateTimeFormatsIterator: def __iter__(self): yield from formats.get_format("DATETIME_INPUT_FORMATS") yield from formats.get_format("DATE_INPUT_FORMATS") class DateTimeField(BaseTemporalField): widget = DateTimeInput input_formats = DateTimeFormatsIterator() default_error_messages = { "invalid": _("Enter a valid date/time."), } def prepare_value(self, value): if isinstance(value, datetime.datetime): value = to_current_timezone(value) return value def to_python(self, value): """ Validate that the input can be converted to a datetime. Return a Python datetime.datetime object. """ if value in self.empty_values: return None if isinstance(value, datetime.datetime): return from_current_timezone(value) if isinstance(value, datetime.date): result = datetime.datetime(value.year, value.month, value.day) return from_current_timezone(result) try: result = parse_datetime(value.strip()) except ValueError: raise ValidationError(self.error_messages["invalid"], code="invalid") if not result: result = super().to_python(value) return from_current_timezone(result) def strptime(self, value, format): return datetime.datetime.strptime(value, format) class DurationField(Field): default_error_messages = { "invalid": _("Enter a valid duration."), "overflow": _("The number of days must be between {min_days} and {max_days}."), } def prepare_value(self, value): if isinstance(value, datetime.timedelta): return duration_string(value) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value try: value = parse_duration(str(value)) except OverflowError: raise ValidationError( self.error_messages["overflow"].format( min_days=datetime.timedelta.min.days, max_days=datetime.timedelta.max.days, ), code="overflow", ) if value is None: raise ValidationError(self.error_messages["invalid"], code="invalid") return value class RegexField(CharField): def __init__(self, regex, **kwargs): """ regex can be either a string or a compiled regular expression object. """ kwargs.setdefault("strip", False) super().__init__(**kwargs) self._set_regex(regex) def _get_regex(self): return self._regex def _set_regex(self, regex): if isinstance(regex, str): regex = re.compile(regex) self._regex = regex if ( hasattr(self, "_regex_validator") and self._regex_validator in self.validators ): self.validators.remove(self._regex_validator) self._regex_validator = validators.RegexValidator(regex=regex) self.validators.append(self._regex_validator) regex = property(_get_regex, _set_regex) class EmailField(CharField): widget = EmailInput default_validators = [validators.validate_email] def __init__(self, **kwargs): # The default maximum length of an email is 320 characters per RFC 3696 # section 3. kwargs.setdefault("max_length", 320) super().__init__(strip=True, **kwargs) class FileField(Field): widget = ClearableFileInput default_error_messages = { "invalid": _("No file was submitted. Check the encoding type on the form."), "missing": _("No file was submitted."), "empty": _("The submitted file is empty."), "max_length": ngettext_lazy( "Ensure this filename has at most %(max)d character (it has %(length)d).", "Ensure this filename has at most %(max)d characters (it has %(length)d).", "max", ), "contradiction": _( "Please either submit a file or check the clear checkbox, not both." ), } def __init__(self, *, max_length=None, allow_empty_file=False, **kwargs): self.max_length = max_length self.allow_empty_file = allow_empty_file super().__init__(**kwargs) def to_python(self, data): if data in self.empty_values: return None # UploadedFile objects should have name and size attributes. try: file_name = data.name file_size = data.size except AttributeError: raise ValidationError(self.error_messages["invalid"], code="invalid") if self.max_length is not None and len(file_name) > self.max_length: params = {"max": self.max_length, "length": len(file_name)} raise ValidationError( self.error_messages["max_length"], code="max_length", params=params ) if not file_name: raise ValidationError(self.error_messages["invalid"], code="invalid") if not self.allow_empty_file and not file_size: raise ValidationError(self.error_messages["empty"], code="empty") return data def clean(self, data, initial=None): # If the widget got contradictory inputs, we raise a validation error if data is FILE_INPUT_CONTRADICTION: raise ValidationError( self.error_messages["contradiction"], code="contradiction" ) # False means the field value should be cleared; further validation is # not needed. if data is False: if not self.required: return False # If the field is required, clearing is not possible (the widget # shouldn't return False data in that case anyway). False is not # in self.empty_value; if a False value makes it this far # it should be validated from here on out as None (so it will be # caught by the required check). data = None if not data and initial: return initial return super().clean(data) def bound_data(self, _, initial): return initial def has_changed(self, initial, data): return not self.disabled and data is not None def _clean_bound_field(self, bf): value = bf.initial if self.disabled else bf.data return self.clean(value, bf.initial) class ImageField(FileField): default_validators = [validators.validate_image_file_extension] default_error_messages = { "invalid_image": _( "Upload a valid image. The file you uploaded was either not an " "image or a corrupted image." ), } def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Pillow supports). """ f = super().to_python(data) if f is None: return None from PIL import Image # We need to get a file object for Pillow. We might have a path or we # might have to read the data into memory. if hasattr(data, "temporary_file_path"): file = data.temporary_file_path() else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # load() could spot a truncated JPEG, but it loads the entire # image in memory, which is a DoS vector. See #3848 and #18520. image = Image.open(file) # verify() must be called immediately after the constructor. image.verify() # Annotating so subclasses can reuse it for their own validation f.image = image # Pillow doesn't detect the MIME type of all formats. In those # cases, content_type will be None. f.content_type = Image.MIME.get(image.format) except Exception as exc: # Pillow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) return f def widget_attrs(self, widget): attrs = super().widget_attrs(widget) if isinstance(widget, FileInput) and "accept" not in widget.attrs: attrs.setdefault("accept", "image/*") return attrs class URLField(CharField): widget = URLInput default_error_messages = { "invalid": _("Enter a valid URL."), } default_validators = [validators.URLValidator()] def __init__(self, *, assume_scheme=None, **kwargs): self.assume_scheme = assume_scheme or "https" super().__init__(strip=True, **kwargs) def to_python(self, value): def split_url(url): """ Return a list of url parts via urlsplit(), or raise ValidationError for some malformed URLs. """ try: return list(urlsplit(url)) except ValueError: # urlsplit can raise a ValueError with some # misformatted URLs. raise ValidationError(self.error_messages["invalid"], code="invalid") value = super().to_python(value) if value: url_fields = split_url(value) if not url_fields[0]: # If no URL scheme given, add a scheme. url_fields[0] = self.assume_scheme if not url_fields[1]: # Assume that if no domain is provided, that the path segment # contains the domain. url_fields[1] = url_fields[2] url_fields[2] = "" # Rebuild the url_fields list, since the domain segment may now # contain the path too. url_fields = split_url(urlunsplit(url_fields)) value = urlunsplit(url_fields) return value class BooleanField(Field): widget = CheckboxInput def to_python(self, value): """Return a Python boolean object.""" # Explicitly check for the string 'False', which is what a hidden field # will submit for False. Also check for '0', since this is what # RadioSelect will provide. Because bool("True") == bool('1') == True, # we don't need to handle that explicitly. if isinstance(value, str) and value.lower() in ("false", "0"): value = False else: value = bool(value) return super().to_python(value) def validate(self, value): if not value and self.required: raise ValidationError(self.error_messages["required"], code="required") def has_changed(self, initial, data): if self.disabled: return False # Sometimes data or initial may be a string equivalent of a boolean # so we should run it through to_python first to get a boolean value return self.to_python(initial) != self.to_python(data) class NullBooleanField(BooleanField): """ A field whose valid values are None, True, and False. Clean invalid values to None. """ widget = NullBooleanSelect def to_python(self, value): """ Explicitly check for the string 'True' and 'False', which is what a hidden field will submit for True and False, for 'true' and 'false', which are likely to be returned by JavaScript serializations of forms, and for '1' and '0', which is what a RadioField will submit. Unlike the Booleanfield, this field must check for True because it doesn't use the bool() function. """ if value in (True, "True", "true", "1"): return True elif value in (False, "False", "false", "0"): return False else: return None def validate(self, value): pass class ChoiceField(Field): widget = Select default_error_messages = { "invalid_choice": _( "Select a valid choice. %(value)s is not one of the available choices." ), } def __init__(self, *, choices=(), **kwargs): super().__init__(**kwargs) self.choices = choices def __deepcopy__(self, memo): result = super().__deepcopy__(memo) result._choices = copy.deepcopy(self._choices, memo) return result @property def choices(self): return self._choices @choices.setter def choices(self, value): # Setting choices on the field also sets the choices on the widget. # Note that the property setter for the widget will re-normalize. self._choices = self.widget.choices = normalize_choices(value) def to_python(self, value): """Return a string.""" if value in self.empty_values: return "" return str(value) def validate(self, value): """Validate that the input is in self.choices.""" super().validate(value) if value and not self.valid_value(value): raise ValidationError( self.error_messages["invalid_choice"], code="invalid_choice", params={"value": value}, ) def valid_value(self, value): """Check to see if the provided value is a valid choice.""" text_value = str(value) for k, v in self.choices: if isinstance(v, (list, tuple)): # This is an optgroup, so look inside the group for options for k2, v2 in v: if value == k2 or text_value == str(k2): return True else: if value == k or text_value == str(k): return True return False class TypedChoiceField(ChoiceField): def __init__(self, *, coerce=lambda val: val, empty_value="", **kwargs): self.coerce = coerce self.empty_value = empty_value super().__init__(**kwargs) def _coerce(self, value): """ Validate that the value can be coerced to the right type (if not empty). """ if value == self.empty_value or value in self.empty_values: return self.empty_value try: value = self.coerce(value) except (ValueError, TypeError, ValidationError): raise ValidationError(
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
true
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/__init__.py
django/forms/__init__.py
""" Django validation and HTML form handling. """ from django.core.exceptions import ValidationError # NOQA from django.forms.boundfield import * # NOQA from django.forms.fields import * # NOQA from django.forms.forms import * # NOQA from django.forms.formsets import * # NOQA from django.forms.models import * # NOQA from django.forms.widgets import * # NOQA
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/renderers.py
django/forms/renderers.py
import functools from pathlib import Path from django.conf import settings from django.template.backends.django import DjangoTemplates from django.template.loader import get_template from django.utils.functional import cached_property from django.utils.module_loading import import_string @functools.lru_cache def get_default_renderer(): renderer_class = import_string(settings.FORM_RENDERER) return renderer_class() class BaseRenderer: form_template_name = "django/forms/div.html" formset_template_name = "django/forms/formsets/div.html" field_template_name = "django/forms/field.html" bound_field_class = None def get_template(self, template_name): raise NotImplementedError("subclasses must implement get_template()") def render(self, template_name, context, request=None): template = self.get_template(template_name) return template.render(context, request=request).strip() class EngineMixin: def get_template(self, template_name): return self.engine.get_template(template_name) @cached_property def engine(self): return self.backend( { "APP_DIRS": True, "DIRS": [Path(__file__).parent / self.backend.app_dirname], "NAME": "djangoforms", "OPTIONS": {}, } ) class DjangoTemplates(EngineMixin, BaseRenderer): """ Load Django templates from the built-in widget templates in django/forms/templates and from apps' 'templates' directory. """ backend = DjangoTemplates class Jinja2(EngineMixin, BaseRenderer): """ Load Jinja2 templates from the built-in widget templates in django/forms/jinja2 and from apps' 'jinja2' directory. """ @cached_property def backend(self): from django.template.backends.jinja2 import Jinja2 return Jinja2 class TemplatesSetting(BaseRenderer): """ Load templates using template.loader.get_template() which is configured based on settings.TEMPLATES. """ def get_template(self, template_name): return get_template(template_name)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/forms/forms.py
django/forms/forms.py
""" Form classes """ import copy import datetime from django.core.exceptions import NON_FIELD_ERRORS, ValidationError from django.forms.fields import Field from django.forms.utils import ErrorDict, ErrorList, RenderableFormMixin from django.forms.widgets import Media, MediaDefiningClass from django.utils.datastructures import MultiValueDict from django.utils.functional import cached_property from django.utils.translation import gettext as _ from .renderers import get_default_renderer __all__ = ("BaseForm", "Form") class DeclarativeFieldsMetaclass(MediaDefiningClass): """Collect Fields declared on the base classes.""" def __new__(mcs, name, bases, attrs): # Collect fields from current class and remove them from attrs. attrs["declared_fields"] = { key: attrs.pop(key) for key, value in list(attrs.items()) if isinstance(value, Field) } new_class = super().__new__(mcs, name, bases, attrs) # Walk through the MRO. declared_fields = {} for base in reversed(new_class.__mro__): # Collect fields from base class. if hasattr(base, "declared_fields"): declared_fields.update(base.declared_fields) # Field shadowing. for attr, value in base.__dict__.items(): if value is None and attr in declared_fields: declared_fields.pop(attr) new_class.base_fields = declared_fields new_class.declared_fields = declared_fields return new_class class BaseForm(RenderableFormMixin): """ The main implementation of all the Form logic. Note that this class is different than Form. See the comments by the Form class for more info. Any improvements to the form API should be made to this class, not to the Form class. """ default_renderer = None field_order = None prefix = None use_required_attribute = True template_name_div = "django/forms/div.html" template_name_p = "django/forms/p.html" template_name_table = "django/forms/table.html" template_name_ul = "django/forms/ul.html" template_name_label = "django/forms/label.html" bound_field_class = None def __init__( self, data=None, files=None, auto_id="id_%s", prefix=None, initial=None, error_class=ErrorList, label_suffix=None, empty_permitted=False, field_order=None, use_required_attribute=None, renderer=None, bound_field_class=None, ): self.is_bound = data is not None or files is not None self.data = MultiValueDict() if data is None else data self.files = MultiValueDict() if files is None else files self.auto_id = auto_id if prefix is not None: self.prefix = prefix self.initial = initial or {} self.error_class = error_class # Translators: This is the default suffix added to form field labels self.label_suffix = label_suffix if label_suffix is not None else _(":") self.empty_permitted = empty_permitted self._errors = None # Stores the errors after clean() has been called. # The base_fields class attribute is the *class-wide* definition of # fields. Because a particular *instance* of the class might want to # alter self.fields, we create self.fields here by copying base_fields. # Instances should always modify self.fields; they should not modify # self.base_fields. self.fields = copy.deepcopy(self.base_fields) self._bound_fields_cache = {} self.order_fields(self.field_order if field_order is None else field_order) if use_required_attribute is not None: self.use_required_attribute = use_required_attribute if self.empty_permitted and self.use_required_attribute: raise ValueError( "The empty_permitted and use_required_attribute arguments may " "not both be True." ) # Initialize form renderer. Use a global default if not specified # either as an argument or as self.default_renderer. if renderer is None: if self.default_renderer is None: renderer = get_default_renderer() else: renderer = self.default_renderer if isinstance(self.default_renderer, type): renderer = renderer() self.renderer = renderer self.bound_field_class = ( bound_field_class or self.bound_field_class or getattr(self.renderer, "bound_field_class", None) ) def order_fields(self, field_order): """ Rearrange the fields according to field_order. field_order is a list of field names specifying the order. Append fields not included in the list in the default order for backward compatibility with subclasses not overriding field_order. If field_order is None, keep all fields in the order defined in the class. Ignore unknown fields in field_order to allow disabling fields in form subclasses without redefining ordering. """ if field_order is None: return fields = {} for key in field_order: try: fields[key] = self.fields.pop(key) except KeyError: # ignore unknown fields pass fields.update(self.fields) # add remaining fields in original order self.fields = fields def __repr__(self): if self._errors is None: is_valid = "Unknown" else: is_valid = self.is_bound and not self._errors return "<%(cls)s bound=%(bound)s, valid=%(valid)s, fields=(%(fields)s)>" % { "cls": self.__class__.__name__, "bound": self.is_bound, "valid": is_valid, "fields": ";".join(self.fields), } def _bound_items(self): """Yield (name, bf) pairs, where bf is a BoundField object.""" for name in self.fields: yield name, self[name] def __iter__(self): """Yield the form's fields as BoundField objects.""" for name in self.fields: yield self[name] def __getitem__(self, name): """Return a BoundField with the given name.""" try: field = self.fields[name] except KeyError: raise KeyError( "Key '%s' not found in '%s'. Choices are: %s." % ( name, self.__class__.__name__, ", ".join(sorted(self.fields)), ) ) if name not in self._bound_fields_cache: self._bound_fields_cache[name] = field.get_bound_field(self, name) return self._bound_fields_cache[name] @property def errors(self): """Return an ErrorDict for the data provided for the form.""" if self._errors is None: self.full_clean() return self._errors def is_valid(self): """Return True if the form has no errors, or False otherwise.""" return self.is_bound and not self.errors def add_prefix(self, field_name): """ Return the field name with a prefix appended, if this Form has a prefix set. Subclasses may wish to override. """ return "%s-%s" % (self.prefix, field_name) if self.prefix else field_name def add_initial_prefix(self, field_name): """Add an 'initial' prefix for checking dynamic initial values.""" return "initial-%s" % self.add_prefix(field_name) def _widget_data_value(self, widget, html_name): # value_from_datadict() gets the data from the data dictionaries. # Each widget type knows how to retrieve its own data, because some # widgets split data over several HTML fields. return widget.value_from_datadict(self.data, self.files, html_name) @property def template_name(self): return self.renderer.form_template_name def get_context(self): fields = [] hidden_fields = [] top_errors = self.non_field_errors().copy() for name, bf in self._bound_items(): if bf.is_hidden: if bf.errors: top_errors += [ _("(Hidden field %(name)s) %(error)s") % {"name": name, "error": str(e)} for e in bf.errors ] hidden_fields.append(bf) else: fields.append((bf, bf.errors)) return { "form": self, "fields": fields, "hidden_fields": hidden_fields, "errors": top_errors, } def non_field_errors(self): """ Return an ErrorList of errors that aren't associated with a particular field -- i.e., from Form.clean(). Return an empty ErrorList if there are none. """ return self.errors.get( NON_FIELD_ERRORS, self.error_class(error_class="nonfield", renderer=self.renderer), ) def add_error(self, field, error): """ Update the content of `self._errors`. The `field` argument is the name of the field to which the errors should be added. If it's None, treat the errors as NON_FIELD_ERRORS. The `error` argument can be a single error, a list of errors, or a dictionary that maps field names to lists of errors. An "error" can be either a simple string or an instance of ValidationError with its message attribute set and a "list or dictionary" can be an actual `list` or `dict` or an instance of ValidationError with its `error_list` or `error_dict` attribute set. If `error` is a dictionary, the `field` argument *must* be None and errors will be added to the fields that correspond to the keys of the dictionary. """ if not isinstance(error, ValidationError): # Normalize to ValidationError and let its constructor # do the hard work of making sense of the input. error = ValidationError(error) if hasattr(error, "error_dict"): if field is not None: raise TypeError( "The argument `field` must be `None` when the `error` " "argument is a dictionary." ) else: error = error.error_dict else: error = {field or NON_FIELD_ERRORS: error.error_list} for field, error_list in error.items(): if field not in self.errors: if field != NON_FIELD_ERRORS and field not in self.fields: raise ValueError( "'%s' has no field named '%s'." % (self.__class__.__name__, field) ) if field == NON_FIELD_ERRORS: self._errors[field] = self.error_class( error_class="nonfield", renderer=self.renderer ) else: self._errors[field] = self.error_class( renderer=self.renderer, field_id=self[field].auto_id, ) self._errors[field].extend(error_list) if field in self.cleaned_data: del self.cleaned_data[field] def has_error(self, field, code=None): return field in self.errors and ( code is None or any(error.code == code for error in self.errors.as_data()[field]) ) def full_clean(self): """ Clean all of self.data and populate self._errors and self.cleaned_data. """ self._errors = ErrorDict(renderer=self.renderer) if not self.is_bound: # Stop further processing. return self.cleaned_data = {} # If the form is permitted to be empty, and none of the form data has # changed from the initial data, short circuit any validation. if self.empty_permitted and not self.has_changed(): return self._clean_fields() self._clean_form() self._post_clean() def _clean_fields(self): for name, bf in self._bound_items(): field = bf.field try: self.cleaned_data[name] = field._clean_bound_field(bf) if hasattr(self, "clean_%s" % name): value = getattr(self, "clean_%s" % name)() self.cleaned_data[name] = value except ValidationError as e: self.add_error(name, e) def _clean_form(self): try: cleaned_data = self.clean() except ValidationError as e: self.add_error(None, e) else: if cleaned_data is not None: self.cleaned_data = cleaned_data def _post_clean(self): """ An internal hook for performing additional cleaning after form cleaning is complete. Used for model validation in model forms. """ pass def clean(self): """ Hook for doing any extra form-wide cleaning after Field.clean() has been called on every field. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field named '__all__'. """ return self.cleaned_data def has_changed(self): """Return True if data differs from initial.""" return bool(self.changed_data) @cached_property def changed_data(self): return [name for name, bf in self._bound_items() if bf._has_changed()] @property def media(self): """Return all media required to render the widgets on this form.""" media = Media() for field in self.fields.values(): media += field.widget.media return media def is_multipart(self): """ Return True if the form needs to be multipart-encoded, i.e. it has FileInput, or False otherwise. """ return any(field.widget.needs_multipart_form for field in self.fields.values()) def hidden_fields(self): """ Return a list of all the BoundField objects that are hidden fields. Useful for manual form layout in templates. """ return [field for field in self if field.is_hidden] def visible_fields(self): """ Return a list of BoundField objects that aren't hidden fields. The opposite of the hidden_fields() method. """ return [field for field in self if not field.is_hidden] def get_initial_for_field(self, field, field_name): """ Return initial data for field on form. Use initial data from the form or the field, in that order. Evaluate callable values. """ value = self.initial.get(field_name, field.initial) if callable(value): value = value() # If this is an auto-generated default date, nix the microseconds # for standardized handling. See #22502. if ( isinstance(value, (datetime.datetime, datetime.time)) and not field.widget.supports_microseconds ): value = value.replace(microsecond=0) return value class Form(BaseForm, metaclass=DeclarativeFieldsMetaclass): "A collection of Fields, plus their associated data." # This is a separate class from BaseForm in order to abstract the way # self.fields is specified. This class (Form) is the one that does the # fancy metaclass stuff purely for the semantic sugar -- it allows one # to define a form using declarative syntax. # BaseForm itself has no way of designating self.fields.
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/module_loading.py
django/utils/module_loading.py
import copy import os import sys from importlib import import_module from importlib.util import find_spec as importlib_find def cached_import(module_path, class_name): # Check whether module is loaded and fully initialized. if not ( (module := sys.modules.get(module_path)) and (spec := getattr(module, "__spec__", None)) and getattr(spec, "_initializing", False) is False ): module = import_module(module_path) return getattr(module, class_name) def import_string(dotted_path): """ Import a dotted module path and return the attribute/class designated by the last name in the path. Raise ImportError if the import failed. """ try: module_path, class_name = dotted_path.rsplit(".", 1) except ValueError as err: raise ImportError("%s doesn't look like a module path" % dotted_path) from err try: return cached_import(module_path, class_name) except AttributeError as err: raise ImportError( 'Module "%s" does not define a "%s" attribute/class' % (module_path, class_name) ) from err def autodiscover_modules(*args, **kwargs): """ Auto-discover INSTALLED_APPS modules and fail silently when not present. This forces an import on them to register any admin bits they may want. You may provide a register_to keyword parameter as a way to access a registry. This register_to object must have a _registry instance variable to access it. """ from django.apps import apps register_to = kwargs.get("register_to") for app_config in apps.get_app_configs(): for module_to_search in args: # Attempt to import the app's module. try: if register_to: before_import_registry = copy.copy(register_to._registry) import_module("%s.%s" % (app_config.name, module_to_search)) except Exception: # Reset the registry to the state before the last import # as this import will have to reoccur on the next request and # this could raise NotRegistered and AlreadyRegistered # exceptions (see #8245). if register_to: register_to._registry = before_import_registry # Decide whether to bubble up this error. If the app just # doesn't have the module in question, we can ignore the error # attempting to import it, otherwise we want it to bubble up. if module_has_submodule(app_config.module, module_to_search): raise def module_has_submodule(package, module_name): """See if 'module' is in 'package'.""" try: package_name = package.__name__ package_path = package.__path__ except AttributeError: # package isn't a package. return False full_module_name = package_name + "." + module_name try: return importlib_find(full_module_name, package_path) is not None except ModuleNotFoundError: # When module_name is an invalid dotted path, Python raises # ModuleNotFoundError. return False def module_dir(module): """ Find the name of the directory that contains a module, if possible. Raise ValueError otherwise, e.g. for namespace packages that are split over several directories. """ # Convert to list because __path__ may not support indexing. paths = list(getattr(module, "__path__", [])) if len(paths) == 1: return paths[0] else: filename = getattr(module, "__file__", None) if filename is not None: return os.path.dirname(filename) raise ValueError("Cannot determine directory containing %s" % module)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/ipv6.py
django/utils/ipv6.py
import ipaddress from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ MAX_IPV6_ADDRESS_LENGTH = 39 def _ipv6_address_from_str(ip_str, max_length=MAX_IPV6_ADDRESS_LENGTH): if len(ip_str) > max_length: raise ValueError( f"Unable to convert {ip_str} to an IPv6 address (value too long)." ) return ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str))) def clean_ipv6_address( ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address."), max_length=MAX_IPV6_ADDRESS_LENGTH, ): """ Clean an IPv6 address string. Raise ValidationError if the address is invalid. Replace the longest continuous zero-sequence with "::", remove leading zeroes, and make sure all hextets are lowercase. Args: ip_str: A valid IPv6 address. unpack_ipv4: if an IPv4-mapped address is found, return the plain IPv4 address (default=False). error_message: An error message used in the ValidationError. Return a compressed IPv6 address or the same value. """ try: addr = _ipv6_address_from_str(ip_str, max_length) except ValueError: raise ValidationError( error_message, code="invalid", params={"protocol": _("IPv6")} ) if unpack_ipv4 and addr.ipv4_mapped: return str(addr.ipv4_mapped) elif addr.ipv4_mapped: return "::ffff:%s" % str(addr.ipv4_mapped) return str(addr) def is_valid_ipv6_address(ip_addr): """ Return whether the `ip_addr` object is a valid IPv6 address. """ if isinstance(ip_addr, ipaddress.IPv6Address): return True try: _ipv6_address_from_str(ip_addr) except (TypeError, ValueError): 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/utils/csp.py
django/utils/csp.py
import secrets from enum import StrEnum from django.utils.functional import SimpleLazyObject, empty class CSP(StrEnum): """ Content Security Policy constants for directive values and special tokens. These constants represent: 1. Standard quoted string values from the CSP spec (e.g., 'self', 'unsafe-inline') 2. Special placeholder tokens (NONCE) that get replaced by the middleware Using this enum instead of raw strings provides better type checking, autocompletion, and protection against common mistakes like: - Typos (e.g., 'noone' instead of 'none') - Missing quotes (e.g., ["self"] instead of ["'self'"]) - Inconsistent quote styles (e.g., ["'self'", "\"unsafe-inline\""]) Example usage in Django settings: SECURE_CSP = { "default-src": [CSP.NONE], "script-src": [CSP.SELF, CSP.NONCE], } """ # HTTP Headers. HEADER_ENFORCE = "Content-Security-Policy" HEADER_REPORT_ONLY = "Content-Security-Policy-Report-Only" # Standard CSP directive values. NONE = "'none'" REPORT_SAMPLE = "'report-sample'" SELF = "'self'" STRICT_DYNAMIC = "'strict-dynamic'" UNSAFE_EVAL = "'unsafe-eval'" UNSAFE_HASHES = "'unsafe-hashes'" UNSAFE_INLINE = "'unsafe-inline'" WASM_UNSAFE_EVAL = "'wasm-unsafe-eval'" # Special placeholder that gets replaced by the middleware. # The value itself is arbitrary and should not be mistaken for a real # nonce. NONCE = "<CSP_NONCE_SENTINEL>" class LazyNonce(SimpleLazyObject): """ Lazily generates a cryptographically secure nonce string, for use in CSP headers. The nonce is only generated when first accessed (e.g., via string interpolation or inside a template). The nonce will evaluate as `True` if it has been generated, and `False` if it has not. This is useful for third-party Django libraries that want to support CSP without requiring it. Example Django template usage with context processors enabled: <script{% if csp_nonce %} nonce="{{ csp_nonce }}"...{% endif %}> The `{% if %}` block will only render if the nonce has been evaluated elsewhere. """ def __init__(self): super().__init__(generate_nonce) def __bool__(self): return self._wrapped is not empty def generate_nonce(): return secrets.token_urlsafe(16) def build_policy(config, nonce=None): policy = [] for directive, values in config.items(): if values in (None, False): continue if values is True: rendered_value = "" else: if isinstance(values, set): # Sort values for consistency, preventing cache invalidation # between requests and ensuring reliable browser caching. values = sorted(values) elif not isinstance(values, list | tuple): values = [values] # Replace the nonce sentinel with the actual nonce values, if the # sentinel is found and a nonce is provided. Otherwise, remove it. if (has_sentinel := CSP.NONCE in values) and nonce: values = [f"'nonce-{nonce}'" if v == CSP.NONCE else v for v in values] elif has_sentinel: values = [v for v in values if v != CSP.NONCE] if not values: continue rendered_value = " ".join(values) policy.append(f"{directive} {rendered_value}".rstrip()) return "; ".join(policy)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/formats.py
django/utils/formats.py
import datetime import decimal import functools import re import unicodedata from importlib import import_module from django.conf import settings from django.utils import dateformat, numberformat from django.utils.functional import lazy from django.utils.translation import check_for_language, get_language, to_locale # format_cache is a mapping from (format_type, lang) to the format string. # By using the cache, it is possible to avoid running get_format_modules # repeatedly. _format_cache = {} _format_modules_cache = {} ISO_INPUT_FORMATS = { "DATE_INPUT_FORMATS": ["%Y-%m-%d"], "TIME_INPUT_FORMATS": ["%H:%M:%S", "%H:%M:%S.%f", "%H:%M"], "DATETIME_INPUT_FORMATS": [ "%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M:%S.%f", "%Y-%m-%d %H:%M", "%Y-%m-%d", ], } FORMAT_SETTINGS = frozenset( [ "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "FIRST_DAY_OF_WEEK", "MONTH_DAY_FORMAT", "TIME_FORMAT", "DATE_FORMAT", "DATETIME_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "YEAR_MONTH_FORMAT", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ] ) def reset_format_cache(): """Clear any cached formats. This method is provided primarily for testing purposes, so that the effects of cached formats can be removed. """ global _format_cache, _format_modules_cache _format_cache = {} _format_modules_cache = {} def iter_format_modules(lang, format_module_path=None): """Find format modules.""" if not check_for_language(lang): return if format_module_path is None: format_module_path = settings.FORMAT_MODULE_PATH format_locations = [] if format_module_path: if isinstance(format_module_path, str): format_module_path = [format_module_path] for path in format_module_path: format_locations.append(path + ".%s") format_locations.append("django.conf.locale.%s") locale = to_locale(lang) locales = [locale] if "_" in locale: locales.append(locale.split("_")[0]) for location in format_locations: for loc in locales: try: yield import_module("%s.formats" % (location % loc)) except ImportError: pass def get_format_modules(lang=None): """Return a list of the format modules found.""" if lang is None: lang = get_language() if lang not in _format_modules_cache: _format_modules_cache[lang] = list( iter_format_modules(lang, settings.FORMAT_MODULE_PATH) ) return _format_modules_cache[lang] def get_format(format_type, lang=None, use_l10n=None): """ For a specific format type, return the format for the current language (locale). Default to the format in the settings. format_type is the name of the format, e.g. 'DATE_FORMAT'. If use_l10n is provided and is not None, it forces the value to be localized (or not), otherwise it's always localized. """ if use_l10n is None: use_l10n = True if use_l10n and lang is None: lang = get_language() format_type = str(format_type) # format_type may be lazy. cache_key = (format_type, lang) try: return _format_cache[cache_key] except KeyError: pass # The requested format_type has not been cached yet. Try to find it in any # of the format_modules for the given lang if l10n is enabled. If it's not # there or if l10n is disabled, fall back to the project settings. val = None if use_l10n: for module in get_format_modules(lang): val = getattr(module, format_type, None) if val is not None: break if val is None: if format_type not in FORMAT_SETTINGS: return format_type val = getattr(settings, format_type) elif format_type in ISO_INPUT_FORMATS: # If a list of input formats from one of the format_modules was # retrieved, make sure the ISO_INPUT_FORMATS are in this list. val = list(val) for iso_input in ISO_INPUT_FORMATS.get(format_type, ()): if iso_input not in val: val.append(iso_input) _format_cache[cache_key] = val return val get_format_lazy = lazy(get_format, str, list, tuple) def date_format(value, format=None, use_l10n=None): """ Format a datetime.date or datetime.datetime object using a localizable format. If use_l10n is provided and is not None, that will force the value to be localized (or not), otherwise it's always localized. """ return dateformat.format( value, get_format(format or "DATE_FORMAT", use_l10n=use_l10n) ) def time_format(value, format=None, use_l10n=None): """ Format a datetime.time object using a localizable format. If use_l10n is provided and is not None, it forces the value to be localized (or not), otherwise it's always localized. """ return dateformat.time_format( value, get_format(format or "TIME_FORMAT", use_l10n=use_l10n) ) def number_format(value, decimal_pos=None, use_l10n=None, force_grouping=False): """ Format a numeric value using localization settings. If use_l10n is provided and is not None, it forces the value to be localized (or not), otherwise it's always localized. """ if use_l10n is None: use_l10n = True lang = get_language() if use_l10n else None return numberformat.format( value, get_format("DECIMAL_SEPARATOR", lang, use_l10n=use_l10n), decimal_pos, get_format("NUMBER_GROUPING", lang, use_l10n=use_l10n), get_format("THOUSAND_SEPARATOR", lang, use_l10n=use_l10n), force_grouping=force_grouping, use_l10n=use_l10n, ) def localize(value, use_l10n=None): """ Check if value is a localizable type (date, number...) and return it formatted as a string using current locale format. If use_l10n is provided and is not None, it forces the value to be localized (or not), otherwise it's always localized. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Make sure booleans don't get treated as numbers return str(value) elif isinstance(value, (decimal.Decimal, float, int)): if use_l10n is False: return str(value) return number_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.datetime): return date_format(value, "DATETIME_FORMAT", use_l10n=use_l10n) elif isinstance(value, datetime.date): return date_format(value, use_l10n=use_l10n) elif isinstance(value, datetime.time): return time_format(value, use_l10n=use_l10n) return value def localize_input(value, default=None): """ Check if an input value is a localizable type and return it formatted with the appropriate formatting string of the current locale. """ if isinstance(value, str): # Handle strings first for performance reasons. return value elif isinstance(value, bool): # Don't treat booleans as numbers. return str(value) elif isinstance(value, (decimal.Decimal, float, int)): return number_format(value) elif isinstance(value, datetime.datetime): format = default or get_format("DATETIME_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.date): format = default or get_format("DATE_INPUT_FORMATS")[0] format = sanitize_strftime_format(format) return value.strftime(format) elif isinstance(value, datetime.time): format = default or get_format("TIME_INPUT_FORMATS")[0] return value.strftime(format) return value @functools.lru_cache def sanitize_strftime_format(fmt): """ Ensure that certain specifiers are correctly padded with leading zeros. For years < 1000 specifiers %C, %F, %G, and %Y don't work as expected for strftime provided by glibc on Linux as they don't pad the year or century with leading zeros. Support for specifying the padding explicitly is available, however, which can be used to fix this issue. FreeBSD, macOS, and Windows do not support explicitly specifying the padding, but return four digit years (with leading zeros) as expected. This function checks whether the %Y produces a correctly padded string and, if not, makes the following substitutions: - %C → %02C - %F → %010F - %G → %04G - %Y → %04Y See https://bugs.python.org/issue13305 for more details. """ if datetime.date(1, 1, 1).strftime("%Y") == "0001": return fmt mapping = {"C": 2, "F": 10, "G": 4, "Y": 4} return re.sub( r"((?:^|[^%])(?:%%)*)%([CFGY])", lambda m: r"%s%%0%s%s" % (m[1], mapping[m[2]], m[2]), fmt, ) def sanitize_separators(value): """ Sanitize a value according to the current decimal and thousand separator setting. Used with form field input. """ if isinstance(value, str): parts = [] decimal_separator = get_format("DECIMAL_SEPARATOR") if decimal_separator in value: value, decimals = value.split(decimal_separator, 1) parts.append(decimals) if settings.USE_THOUSAND_SEPARATOR: thousand_sep = get_format("THOUSAND_SEPARATOR") if ( thousand_sep == "." and value.count(".") == 1 and len(value.split(".")[-1]) != 3 ): # Special case where we suspect a dot meant decimal separator # (see #22171). pass else: for replacement in { thousand_sep, unicodedata.normalize("NFKD", thousand_sep), }: value = value.replace(replacement, "") parts.append(value) value = ".".join(reversed(parts)) return value
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/numberformat.py
django/utils/numberformat.py
from decimal import Decimal from django.conf import settings from django.utils.safestring import mark_safe def format( number, decimal_sep, decimal_pos=None, grouping=0, thousand_sep="", force_grouping=False, use_l10n=None, ): """ Get a number (as a number or string), and return it as a string, using formats defined as arguments: * decimal_sep: Decimal separator symbol (for example ".") * decimal_pos: Number of decimal positions * grouping: Number of digits in every group limited by thousand separator. For non-uniform digit grouping, it can be a sequence with the number of digit group sizes following the format used by the Python locale module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)). * thousand_sep: Thousand separator symbol (for example ",") """ if number is None or number == "": return mark_safe(number) if use_l10n is None: use_l10n = True use_grouping = use_l10n and settings.USE_THOUSAND_SEPARATOR use_grouping = use_grouping or force_grouping use_grouping = use_grouping and grouping != 0 # Make the common case fast if isinstance(number, int) and not use_grouping and not decimal_pos: return mark_safe(number) # sign sign = "" # Treat potentially very large/small floats as Decimals. if isinstance(number, float) and "e" in str(number).lower(): number = Decimal(str(number)) if isinstance(number, Decimal): if decimal_pos is not None: # If the provided number is too small to affect any of the visible # decimal places, consider it equal to '0'. cutoff = Decimal("0." + "1".rjust(decimal_pos, "0")) if abs(number) < cutoff: number = Decimal("0") if not number.is_finite(): return str(number) # Format values with more than 200 digits (an arbitrary cutoff) using # scientific notation to avoid high memory usage in {:f}'.format(). _, digits, exponent = number.as_tuple() if abs(exponent) + len(digits) > 200: number = "{:e}".format(number) coefficient, exponent = number.split("e") # Format the coefficient. coefficient = format( coefficient, decimal_sep, decimal_pos, grouping, thousand_sep, force_grouping, use_l10n, ) return "{}e{}".format(coefficient, exponent) else: str_number = "{:f}".format(number) else: str_number = str(number) if str_number[0] == "-": sign = "-" str_number = str_number[1:] # decimal part if "." in str_number: int_part, dec_part = str_number.split(".") if decimal_pos is not None: dec_part = dec_part[:decimal_pos] else: int_part, dec_part = str_number, "" if decimal_pos is not None: dec_part += "0" * (decimal_pos - len(dec_part)) dec_part = dec_part and decimal_sep + dec_part # grouping if use_grouping: try: # if grouping is a sequence intervals = list(grouping) except TypeError: # grouping is a single value intervals = [grouping, 0] active_interval = intervals.pop(0) int_part_gd = [] cnt = 0 for digit in int_part[::-1]: if cnt and cnt == active_interval: if intervals: active_interval = intervals.pop(0) or active_interval int_part_gd.append(thousand_sep[::-1]) cnt = 0 int_part_gd.append(digit) cnt += 1 int_part = "".join(int_part_gd)[::-1] return sign + int_part + dec_part
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/http.py
django/utils/http.py
import base64 import re import unicodedata from binascii import Error as BinasciiError from datetime import UTC, datetime from email.utils import formatdate from urllib.parse import quote, unquote from urllib.parse import urlencode as original_urlencode from urllib.parse import urlsplit from django.utils.datastructures import MultiValueDict from django.utils.regex_helper import _lazy_re_compile # Based on RFC 9110 Appendix A. ETAG_MATCH = _lazy_re_compile( r""" \A( # start of string and capture group (?:W/)? # optional weak indicator " # opening quote [^"]* # any sequence of non-quote characters " # end quote )\Z # end of string and capture group """, re.X, ) MAX_HEADER_LENGTH = 10_000 MONTHS = "jan feb mar apr may jun jul aug sep oct nov dec".split() __D = r"(?P<day>[0-9]{2})" __D2 = r"(?P<day>[ 0-9][0-9])" __M = r"(?P<mon>\w{3})" __Y = r"(?P<year>[0-9]{4})" __Y2 = r"(?P<year>[0-9]{2})" __T = r"(?P<hour>[0-9]{2}):(?P<min>[0-9]{2}):(?P<sec>[0-9]{2})" RFC1123_DATE = _lazy_re_compile(r"^\w{3}, %s %s %s %s GMT$" % (__D, __M, __Y, __T)) RFC850_DATE = _lazy_re_compile(r"^\w{6,9}, %s-%s-%s %s GMT$" % (__D, __M, __Y2, __T)) ASCTIME_DATE = _lazy_re_compile(r"^\w{3} %s %s %s %s$" % (__M, __D2, __T, __Y)) RFC3986_GENDELIMS = ":/?#[]@" RFC3986_SUBDELIMS = "!$&'()*+,;=" MAX_URL_LENGTH = 2048 MAX_URL_REDIRECT_LENGTH = 16384 def urlencode(query, doseq=False): """ A version of Python's urllib.parse.urlencode() function that can operate on MultiValueDict and non-string values. """ if isinstance(query, MultiValueDict): query = query.lists() elif hasattr(query, "items"): query = query.items() query_params = [] for key, value in query: if value is None: raise TypeError( "Cannot encode None for key '%s' in a query string. Did you " "mean to pass an empty string or omit the value?" % key ) elif not doseq or isinstance(value, (str, bytes)): query_val = value else: try: itr = iter(value) except TypeError: query_val = value else: # Consume generators and iterators, when doseq=True, to # work around https://bugs.python.org/issue31706. query_val = [] for item in itr: if item is None: raise TypeError( "Cannot encode None for key '%s' in a query " "string. Did you mean to pass an empty string or " "omit the value?" % key ) elif not isinstance(item, bytes): item = str(item) query_val.append(item) query_params.append((key, query_val)) return original_urlencode(query_params, doseq) def http_date(epoch_seconds=None): """ Format the time to match the RFC 5322 date format as specified by RFC 9110 Section 5.6.7. `epoch_seconds` is a floating point number expressed in seconds since the epoch, in UTC - such as that outputted by time.time(). If set to None, it defaults to the current time. Output a string in the format 'Wdy, DD Mon YYYY HH:MM:SS GMT'. """ return formatdate(epoch_seconds, usegmt=True) def parse_http_date(date): """ Parse a date format as specified by HTTP RFC 9110 Section 5.6.7. The three formats allowed by the RFC are accepted, even if only the first one is still in widespread use. Return an integer expressed in seconds since the epoch, in UTC. """ # email.utils.parsedate() does the job for RFC 1123 dates; unfortunately # RFC 9110 makes it mandatory to support RFC 850 dates too. So we roll # our own RFC-compliant parsing. for regex in RFC1123_DATE, RFC850_DATE, ASCTIME_DATE: m = regex.match(date) if m is not None: break else: raise ValueError("%r is not in a valid HTTP date format" % date) try: year = int(m["year"]) if year < 100: current_year = datetime.now(tz=UTC).year current_century = current_year - (current_year % 100) if year - (current_year % 100) > 50: # year that appears to be more than 50 years in the future are # interpreted as representing the past. year += current_century - 100 else: year += current_century month = MONTHS.index(m["mon"].lower()) + 1 day = int(m["day"]) hour = int(m["hour"]) min = int(m["min"]) sec = int(m["sec"]) result = datetime(year, month, day, hour, min, sec, tzinfo=UTC) return int(result.timestamp()) except Exception as exc: raise ValueError("%r is not a valid date" % date) from exc def parse_http_date_safe(date): """ Same as parse_http_date, but return None if the input is invalid. """ try: return parse_http_date(date) except Exception: pass # Base 36 functions: useful for generating compact URLs def base36_to_int(s): """ Convert a base 36 string to an int. Raise ValueError if the input won't fit into an int. """ # To prevent overconsumption of server resources, reject any # base36 string that is longer than 13 base36 digits (13 digits # is sufficient to base36-encode any 64-bit integer) if len(s) > 13: raise ValueError("Base36 input too large") return int(s, 36) def int_to_base36(i): """Convert an integer to a base36 string.""" char_set = "0123456789abcdefghijklmnopqrstuvwxyz" if i < 0: raise ValueError("Negative base36 conversion input.") if i < 36: return char_set[i] b36_parts = [] while i != 0: i, n = divmod(i, 36) b36_parts.append(char_set[n]) return "".join(reversed(b36_parts)) def urlsafe_base64_encode(s): """ Encode a bytestring to a base64 string for use in URLs. Strip any trailing equal signs. """ return base64.urlsafe_b64encode(s).rstrip(b"\n=").decode("ascii") def urlsafe_base64_decode(s): """ Decode a base64 encoded string. Add back any trailing equal signs that might have been stripped. """ s = s.encode() try: return base64.urlsafe_b64decode(s.ljust(len(s) + len(s) % 4, b"=")) except (LookupError, BinasciiError) as e: raise ValueError(e) def parse_etags(etag_str): """ Parse a string of ETags given in an If-None-Match or If-Match header as defined by RFC 9110. Return a list of quoted ETags, or ['*'] if all ETags should be matched. """ if etag_str.strip() == "*": return ["*"] else: # Parse each ETag individually, and return any that are valid. etag_matches = (ETAG_MATCH.match(etag.strip()) for etag in etag_str.split(",")) return [match[1] for match in etag_matches if match] def quote_etag(etag_str): """ If the provided string is already a quoted ETag, return it. Otherwise, wrap the string in quotes, making it a strong ETag. """ if ETAG_MATCH.match(etag_str): return etag_str else: return '"%s"' % etag_str def is_same_domain(host, pattern): """ Return ``True`` if the host is either an exact match or a match to the wildcard pattern. Any pattern beginning with a period matches a domain and all of its subdomains. (e.g. ``.example.com`` matches ``example.com`` and ``foo.example.com``). Anything else is an exact string match. """ if not pattern: return False pattern = pattern.lower() return ( pattern[0] == "." and (host.endswith(pattern) or host == pattern[1:]) or pattern == host ) def url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): """ Return ``True`` if the url uses an allowed host and a safe scheme. Always return ``False`` on an empty url. If ``require_https`` is ``True``, only 'https' will be considered a valid scheme, as opposed to 'http' and 'https' with the default, ``False``. Note: "True" doesn't entail that a URL is "safe". It may still be e.g. quoted incorrectly. Ensure to also use django.utils.encoding.iri_to_uri() on the path component of untrusted URLs. """ if url is not None: url = url.strip() if not url: return False if allowed_hosts is None: allowed_hosts = set() elif isinstance(allowed_hosts, str): allowed_hosts = {allowed_hosts} # Chrome treats \ completely as / in paths but it could be part of some # basic auth credentials so we need to check both URLs. return _url_has_allowed_host_and_scheme( url, allowed_hosts, require_https=require_https ) and _url_has_allowed_host_and_scheme( url.replace("\\", "/"), allowed_hosts, require_https=require_https ) def _url_has_allowed_host_and_scheme(url, allowed_hosts, require_https=False): # Chrome considers any URL with more than two slashes to be absolute, but # urlsplit is not so flexible. Treat any url with three slashes as unsafe. if url.startswith("///") or len(url) > MAX_URL_LENGTH: # urlsplit does not perform validation of inputs. Unicode normalization # is very slow on Windows and can be a DoS attack vector. # https://docs.python.org/3/library/urllib.parse.html#url-parsing-security return False try: url_info = urlsplit(url) except ValueError: # e.g. invalid IPv6 addresses return False # Forbid URLs like http:///example.com - with a scheme, but without a # hostname. In that URL, example.com is not the hostname but, a path # component. However, Chrome will still consider example.com to be the # hostname, so we must not allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == "C": return False scheme = url_info.scheme # Consider URLs without a scheme (e.g. //example.com/p) to be http. if not url_info.scheme and url_info.netloc: scheme = "http" valid_schemes = ["https"] if require_https else ["http", "https"] return (not url_info.netloc or url_info.netloc in allowed_hosts) and ( not scheme or scheme in valid_schemes ) def escape_leading_slashes(url): """ If redirecting to an absolute path (two leading slashes), a slash must be escaped to prevent browsers from handling the path as schemaless and redirecting to another host. """ if url.startswith("//"): url = "/%2F{}".format(url.removeprefix("//")) return url def _parseparam(s): while s[:1] == ";": s = s[1:] end = s.find(";") while end > 0 and (s.count('"', 0, end) - s.count('\\"', 0, end)) % 2: end = s.find(";", end + 1) if end < 0: end = len(s) f = s[:end] yield f.strip() s = s[end:] def parse_header_parameters(line, max_length=MAX_HEADER_LENGTH): """ Parse a Content-type like header. Return the main content-type and a dictionary of options. If `line` is longer than `max_length`, `ValueError` is raised. """ if not line: return "", {} if max_length is not None and len(line) > max_length: raise ValueError("Unable to parse header parameters (value too long).") parts = _parseparam(";" + line) key = parts.__next__().lower() pdict = {} for p in parts: i = p.find("=") if i >= 0: has_encoding = False name = p[:i].strip().lower() if name.endswith("*"): # Embedded lang/encoding, like "filename*=UTF-8''file.ext". # https://tools.ietf.org/html/rfc2231#section-4 name = name[:-1] if p.count("'") == 2: has_encoding = True value = p[i + 1 :].strip() if len(value) >= 2 and value[0] == value[-1] == '"': value = value[1:-1] value = value.replace("\\\\", "\\").replace('\\"', '"') if has_encoding: encoding, lang, value = value.split("'") value = unquote(value, encoding=encoding) pdict[name] = value return key, pdict def content_disposition_header(as_attachment, filename): """ Construct a Content-Disposition HTTP header value from the given filename as specified by RFC 6266. """ if filename: disposition = "attachment" if as_attachment else "inline" try: filename.encode("ascii") is_ascii = True except UnicodeEncodeError: is_ascii = False # Quoted strings can contain horizontal tabs, space characters, and # characters from 0x21 to 0x7e, except 0x22 (`"`) and 0x5C (`\`) which # can still be expressed but must be escaped with their own `\`. # https://datatracker.ietf.org/doc/html/rfc9110#name-quoted-strings quotable_characters = r"^[\t \x21-\x7e]*$" if is_ascii and re.match(quotable_characters, filename): file_expr = 'filename="{}"'.format( filename.replace("\\", "\\\\").replace('"', r"\"") ) else: file_expr = "filename*=utf-8''{}".format(quote(filename)) return f"{disposition}; {file_expr}" elif as_attachment: return "attachment" else: return None
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/crypto.py
django/utils/crypto.py
""" Django's standard crypto functions and utilities. """ import hashlib import hmac import secrets from django.conf import settings from django.utils.encoding import force_bytes class InvalidAlgorithm(ValueError): """Algorithm is not supported by hashlib.""" pass def salted_hmac(key_salt, value, secret=None, *, algorithm="sha1"): """ Return the HMAC of 'value', using a key generated from key_salt and a secret (which defaults to settings.SECRET_KEY). Default algorithm is SHA1, but any algorithm name supported by hashlib can be passed. A different key_salt should be passed in for every application of HMAC. """ if secret is None: secret = settings.SECRET_KEY key_salt = force_bytes(key_salt) secret = force_bytes(secret) try: hasher = getattr(hashlib, algorithm) except AttributeError as e: raise InvalidAlgorithm( "%r is not an algorithm accepted by the hashlib module." % algorithm ) from e # We need to generate a derived key from our base key. We can do this by # passing the key_salt and our base key through a pseudo-random function. key = hasher(key_salt + secret).digest() # If len(key_salt + secret) > block size of the hash algorithm, the above # line is redundant and could be replaced by key = key_salt + secret, since # the hmac module does the same thing for keys longer than the block size. # However, we need to ensure that we *always* do this. return hmac.new(key, msg=force_bytes(value), digestmod=hasher) RANDOM_STRING_CHARS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789" def get_random_string(length, allowed_chars=RANDOM_STRING_CHARS): """ Return a securely generated random string. The bit length of the returned value can be calculated with the formula: log_2(len(allowed_chars)^length) For example, with default `allowed_chars` (26+26+10), this gives: * length: 12, bit length =~ 71 bits * length: 22, bit length =~ 131 bits """ return "".join(secrets.choice(allowed_chars) for i in range(length)) def constant_time_compare(val1, val2): """Return True if the two strings are equal, False otherwise.""" return secrets.compare_digest(force_bytes(val1), force_bytes(val2)) def pbkdf2(password, salt, iterations, dklen=0, digest=None): """Return the hash of password using pbkdf2.""" if digest is None: digest = hashlib.sha256 dklen = dklen or None password = force_bytes(password) salt = force_bytes(salt) return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/tree.py
django/utils/tree.py
""" A class for storing a tree graph. Primarily used for filter constructs in the ORM. """ import copy from django.utils.hashable import make_hashable class Node: """ A single internal node in the tree graph. A Node should be viewed as a connection (the root) with the children being either leaf nodes or other Node instances. """ # Standard connector type. Clients usually won't use this at all and # subclasses will usually override the value. default = "DEFAULT" def __init__(self, children=None, connector=None, negated=False): """Construct a new Node. If no connector is given, use the default.""" self.children = children[:] if children else [] self.connector = connector or self.default self.negated = negated @classmethod def create(cls, children=None, connector=None, negated=False): """ Create a new instance using Node() instead of __init__() as some subclasses, e.g. django.db.models.query_utils.Q, may implement a custom __init__() with a signature that conflicts with the one defined in Node.__init__(). """ obj = Node(children, connector or cls.default, negated) obj.__class__ = cls return obj def __str__(self): template = "(NOT (%s: %s))" if self.negated else "(%s: %s)" return template % (self.connector, ", ".join(str(c) for c in self.children)) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, self) def __copy__(self): obj = self.create(connector=self.connector, negated=self.negated) obj.children = self.children # Don't [:] as .__init__() via .create() does. return obj copy = __copy__ def __deepcopy__(self, memodict): obj = self.create(connector=self.connector, negated=self.negated) obj.children = copy.deepcopy(self.children, memodict) return obj def __len__(self): """Return the number of children this node has.""" return len(self.children) def __bool__(self): """Return whether or not this node has children.""" return bool(self.children) def __contains__(self, other): """Return True if 'other' is a direct child of this instance.""" return other in self.children def __eq__(self, other): return ( self.__class__ == other.__class__ and self.connector == other.connector and self.negated == other.negated and self.children == other.children ) def __hash__(self): return hash( ( self.__class__, self.connector, self.negated, *make_hashable(self.children), ) ) def add(self, data, conn_type): """ Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place of data regardless if the node other got squashed or not. """ if self.connector != conn_type: obj = self.copy() self.connector = conn_type self.children = [obj, data] return data elif ( isinstance(data, Node) and not data.negated and (data.connector == conn_type or len(data) == 1) ): # We can squash the other node's children directly into this node. # We are just doing (AB)(CD) == (ABCD) here, with the addition that # if the length of the other node is 1 the connector doesn't # matter. However, for the len(self) == 1 case we don't want to do # the squashing, as it would alter self.connector. self.children.extend(data.children) return self else: # We could use perhaps additional logic here to see if some # children could be used for pushdown here. self.children.append(data) return data def negate(self): """Negate the sense of the root connector.""" self.negated = not self.negated
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/timesince.py
django/utils/timesince.py
import datetime from django.utils.html import avoid_wrapping from django.utils.timezone import is_aware from django.utils.translation import gettext, ngettext_lazy TIME_STRINGS = { "year": ngettext_lazy("%(num)d year", "%(num)d years", "num"), "month": ngettext_lazy("%(num)d month", "%(num)d months", "num"), "week": ngettext_lazy("%(num)d week", "%(num)d weeks", "num"), "day": ngettext_lazy("%(num)d day", "%(num)d days", "num"), "hour": ngettext_lazy("%(num)d hour", "%(num)d hours", "num"), "minute": ngettext_lazy("%(num)d minute", "%(num)d minutes", "num"), } TIME_STRINGS_KEYS = list(TIME_STRINGS.keys()) TIME_CHUNKS = [ 60 * 60 * 24 * 7, # week 60 * 60 * 24, # day 60 * 60, # hour 60, # minute ] MONTHS_DAYS = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31) def timesince(d, now=None, reversed=False, time_strings=None, depth=2): """ Take two datetime objects and return the time between d and now as a nicely formatted string, e.g. "10 minutes". If d occurs after now, return "0 minutes". Units used are years, months, weeks, days, hours, and minutes. Seconds and microseconds are ignored. The algorithm takes into account the varying duration of years and months. There is exactly "1 year, 1 month" between 2013/02/10 and 2014/03/10, but also between 2007/08/10 and 2008/09/10 despite the delta being 393 days in the former case and 397 in the latter. Up to `depth` adjacent units will be displayed. For example, "2 weeks, 3 days" and "1 year, 3 months" are possible outputs, but "2 weeks, 3 hours" and "1 year, 5 days" are not. `time_strings` is an optional dict of strings to replace the default TIME_STRINGS dict. `depth` is an optional integer to control the number of adjacent time units returned. Originally adapted from https://web.archive.org/web/20060617175230/http://blog.natbat.co.uk/archive/2003/Jun/14/time_since Modified to improve results for years and months. """ if time_strings is None: time_strings = TIME_STRINGS if depth <= 0: raise ValueError("depth must be greater than 0.") # Convert datetime.date to datetime.datetime for comparison. if not isinstance(d, datetime.datetime): d = datetime.datetime(d.year, d.month, d.day) if now and not isinstance(now, datetime.datetime): now = datetime.datetime(now.year, now.month, now.day) # Compared datetimes must be in the same time zone. if not now: now = datetime.datetime.now(d.tzinfo if is_aware(d) else None) elif is_aware(now) and is_aware(d): now = now.astimezone(d.tzinfo) if reversed: d, now = now, d delta = now - d # Ignore microseconds. since = delta.days * 24 * 60 * 60 + delta.seconds if since <= 0: # d is in the future compared to now, stop processing. return avoid_wrapping(time_strings["minute"] % {"num": 0}) # Get years and months. total_months = (now.year - d.year) * 12 + (now.month - d.month) if d.day > now.day or (d.day == now.day and d.time() > now.time()): total_months -= 1 years, months = divmod(total_months, 12) # Calculate the remaining time. # Create a "pivot" datetime shifted from d by years and months, then use # that to determine the other parts. if years or months: pivot_year = d.year + years pivot_month = d.month + months if pivot_month > 12: pivot_month -= 12 pivot_year += 1 pivot = datetime.datetime( pivot_year, pivot_month, min(MONTHS_DAYS[pivot_month - 1], d.day), d.hour, d.minute, d.second, tzinfo=d.tzinfo, ) else: pivot = d remaining_time = (now - pivot).total_seconds() partials = [years, months] for chunk in TIME_CHUNKS: count = int(remaining_time // chunk) partials.append(count) remaining_time -= chunk * count # Find the first non-zero part (if any) and then build the result, until # depth. i = 0 for i, value in enumerate(partials): if value != 0: break else: return avoid_wrapping(time_strings["minute"] % {"num": 0}) result = [] current_depth = 0 while i < len(TIME_STRINGS_KEYS) and current_depth < depth: value = partials[i] if value == 0: break name = TIME_STRINGS_KEYS[i] result.append(avoid_wrapping(time_strings[name] % {"num": value})) current_depth += 1 i += 1 return gettext(", ").join(result) def timeuntil(d, now=None, time_strings=None, depth=2): """ Like timesince, but return a string measuring the time until the given time. """ return timesince(d, now, reversed=True, time_strings=time_strings, depth=depth)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/html.py
django/utils/html.py
"""HTML utilities suitable for global use.""" import html import json import re import warnings from collections import deque from collections.abc import Mapping from html.parser import HTMLParser from itertools import chain from urllib.parse import parse_qsl, quote, unquote, urlencode, urlsplit, urlunsplit from django.conf import settings from django.core.exceptions import SuspiciousOperation, ValidationError from django.core.validators import DomainNameValidator, EmailValidator from django.utils.deprecation import RemovedInDjango70Warning from django.utils.functional import Promise, cached_property, keep_lazy, keep_lazy_text from django.utils.http import MAX_URL_LENGTH, RFC3986_GENDELIMS, RFC3986_SUBDELIMS from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, SafeString, mark_safe from django.utils.text import normalize_newlines # https://html.spec.whatwg.org/#void-elements VOID_ELEMENTS = frozenset( ( "area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "param", "source", "track", "wbr", # Deprecated tags. "frame", "spacer", ) ) MAX_STRIP_TAGS_DEPTH = 50 # HTML tag that opens but has no closing ">" after 1k+ chars. long_open_tag_without_closing_re = _lazy_re_compile(r"<[a-zA-Z][^>]{1000,}") @keep_lazy(SafeString) def escape(text): """ Return the given text with ampersands, quotes and angle brackets encoded for use in HTML. Always escape input, even if it's already escaped and marked as such. This may result in double-escaping. If this is a concern, use conditional_escape() instead. """ return SafeString(html.escape(str(text))) _js_escapes = { ord("\\"): "\\u005C", ord("'"): "\\u0027", ord('"'): "\\u0022", ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", ord("="): "\\u003D", ord("-"): "\\u002D", ord(";"): "\\u003B", ord("`"): "\\u0060", ord("\u2028"): "\\u2028", ord("\u2029"): "\\u2029", } # Escape every ASCII character with a value less than 32 (C0), 127(C0), # or 128-159(C1). _js_escapes.update( (ord("%c" % z), "\\u%04X" % z) for z in chain(range(32), range(0x7F, 0xA0)) ) @keep_lazy(SafeString) def escapejs(value): """Hex encode characters for use in JavaScript strings.""" return mark_safe(str(value).translate(_js_escapes)) _json_script_escapes = { ord(">"): "\\u003E", ord("<"): "\\u003C", ord("&"): "\\u0026", } def json_script(value, element_id=None, encoder=None): """ Escape all the HTML/XML special characters with their unicode escapes, so value is safe to be output anywhere except for inside a tag attribute. Wrap the escaped JSON in a script tag. """ from django.core.serializers.json import DjangoJSONEncoder json_str = json.dumps(value, cls=encoder or DjangoJSONEncoder).translate( _json_script_escapes ) if element_id: template = '<script id="{}" type="application/json">{}</script>' args = (element_id, mark_safe(json_str)) else: template = '<script type="application/json">{}</script>' args = (mark_safe(json_str),) return format_html(template, *args) def conditional_escape(text): """ Similar to escape(), except that it doesn't operate on pre-escaped strings. This function relies on the __html__ convention used both by Django's SafeData class and by third-party libraries like markupsafe. """ if isinstance(text, Promise): text = str(text) if hasattr(text, "__html__"): return text.__html__() else: return escape(text) def format_html(format_string, *args, **kwargs): """ Similar to str.format, but pass all arguments through conditional_escape(), and call mark_safe() on the result. This function should be used instead of str.format or % interpolation to build up small HTML fragments. """ if not (args or kwargs): raise TypeError("args or kwargs must be provided.") args_safe = map(conditional_escape, args) kwargs_safe = {k: conditional_escape(v) for (k, v) in kwargs.items()} return mark_safe(format_string.format(*args_safe, **kwargs_safe)) def format_html_join(sep, format_string, args_generator): """ A wrapper of format_html, for the common case of a group of arguments that need to be formatted using the same format string, and then joined using 'sep'. 'sep' is also passed through conditional_escape. 'args_generator' should be an iterator that returns the sequence of 'args' that will be passed to format_html. Example: format_html_join('\n', "<li>{} {}</li>", ((u.first_name, u.last_name) for u in users)) """ return mark_safe( conditional_escape(sep).join( ( format_html(format_string, **args) if isinstance(args, Mapping) else format_html(format_string, *args) ) for args in args_generator ) ) @keep_lazy_text def linebreaks(value, autoescape=False): """Convert newlines into <p> and <br>s.""" value = normalize_newlines(value) paras = re.split("\n{2,}", str(value)) if autoescape: paras = ["<p>%s</p>" % escape(p).replace("\n", "<br>") for p in paras] else: paras = ["<p>%s</p>" % p.replace("\n", "<br>") for p in paras] return "\n\n".join(paras) class MLStripper(HTMLParser): def __init__(self): super().__init__(convert_charrefs=False) self.reset() self.fed = [] def handle_data(self, d): self.fed.append(d) def handle_entityref(self, name): self.fed.append("&%s;" % name) def handle_charref(self, name): self.fed.append("&#%s;" % name) def get_data(self): return "".join(self.fed) def _strip_once(value): """ Internal tag stripping utility used by strip_tags. """ s = MLStripper() s.feed(value) s.close() return s.get_data() @keep_lazy_text def strip_tags(value): """Return the given HTML with all tags stripped.""" value = str(value) for long_open_tag in long_open_tag_without_closing_re.finditer(value): if long_open_tag.group().count("<") >= MAX_STRIP_TAGS_DEPTH: raise SuspiciousOperation # Note: in typical case this loop executes _strip_once twice (the second # execution does not remove any more tags). strip_tags_depth = 0 while "<" in value and ">" in value: if strip_tags_depth >= MAX_STRIP_TAGS_DEPTH: raise SuspiciousOperation new_value = _strip_once(value) if value.count("<") == new_value.count("<"): # _strip_once wasn't able to detect more tags. break value = new_value strip_tags_depth += 1 return value @keep_lazy_text def strip_spaces_between_tags(value): """Return the given HTML with spaces between tags removed.""" return re.sub(r">\s+<", "><", str(value)) def smart_urlquote(url): """Quote a URL if it isn't already quoted.""" def unquote_quote(segment): segment = unquote(segment) # Tilde is part of RFC 3986 Section 2.3 Unreserved Characters, # see also https://bugs.python.org/issue16285 return quote(segment, safe=RFC3986_SUBDELIMS + RFC3986_GENDELIMS + "~") try: scheme, netloc, path, query, fragment = urlsplit(url) except ValueError: # invalid IPv6 URL (normally square brackets in hostname part). return unquote_quote(url) # Handle IDN as percent-encoded UTF-8 octets, per WHATWG URL Specification # section 3.5 and RFC 3986 section 3.2.2. Defer any IDNA to the user agent. # See #36013. netloc = unquote_quote(netloc) if query: # Separately unquoting key/value, so as to not mix querystring # separators included in query values. See #22267. query_parts = [ (unquote(q[0]), unquote(q[1])) for q in parse_qsl(query, keep_blank_values=True) ] # urlencode will take care of quoting query = urlencode(query_parts) path = unquote_quote(path) fragment = unquote_quote(fragment) return urlunsplit((scheme, netloc, path, query, fragment)) class CountsDict(dict): def __init__(self, *args, word, **kwargs): super().__init__(*args, *kwargs) self.word = word def __missing__(self, key): self[key] = self.word.count(key) return self[key] class Urlizer: """ Convert any URLs in text into clickable links. Work on http://, https://, www. links, and also on links ending in one of the original seven gTLDs (.com, .edu, .gov, .int, .mil, .net, and .org). Links can have trailing punctuation (periods, commas, close-parens) and leading punctuation (opening parens) and it'll still do the right thing. """ trailing_punctuation_chars = ".,:;!" wrapping_punctuation = [("(", ")"), ("[", "]")] simple_url_re = _lazy_re_compile(r"^https?://\[?\w", re.IGNORECASE) simple_url_2_re = _lazy_re_compile( rf"^www\.|^(?!http)(?:{DomainNameValidator.hostname_re})" rf"(?:{DomainNameValidator.domain_re})" r"\.(com|edu|gov|int|mil|net|org)($|/.*)$", re.IGNORECASE, ) word_split_re = _lazy_re_compile(r"""([\s<>"']+)""") mailto_template = "mailto:{local}@{domain}" url_template = '<a href="{href}"{attrs}>{url}</a>' def __call__(self, text, trim_url_limit=None, nofollow=False, autoescape=False): """ If trim_url_limit is not None, truncate the URLs in the link text longer than this limit to trim_url_limit - 1 characters and append an ellipsis. If nofollow is True, give the links a rel="nofollow" attribute. If autoescape is True, autoescape the link text and URLs. """ safe_input = isinstance(text, SafeData) words = self.word_split_re.split(str(text)) local_cache = {} urlized_words = [] for word in words: if (urlized_word := local_cache.get(word)) is None: urlized_word = self.handle_word( word, safe_input=safe_input, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape, ) local_cache[word] = urlized_word urlized_words.append(urlized_word) return "".join(urlized_words) def handle_word( self, word, *, safe_input, trim_url_limit=None, nofollow=False, autoescape=False, ): if "." in word or "@" in word or ":" in word: # lead: Punctuation trimmed from the beginning of the word. # middle: State of the word. # trail: Punctuation trimmed from the end of the word. lead, middle, trail = self.trim_punctuation(word) # Make URL we want to point to. url = None nofollow_attr = ' rel="nofollow"' if nofollow else "" if len(middle) <= MAX_URL_LENGTH and self.simple_url_re.match(middle): url = smart_urlquote(html.unescape(middle)) elif len(middle) <= MAX_URL_LENGTH and self.simple_url_2_re.match(middle): unescaped_middle = html.unescape(middle) # RemovedInDjango70Warning: When the deprecation ends, replace # with: # url = smart_urlquote(f"https://{unescaped_middle}") protocol = ( "https" if getattr(settings, "URLIZE_ASSUME_HTTPS", False) else "http" ) if not settings.URLIZE_ASSUME_HTTPS: warnings.warn( "The default protocol will be changed from HTTP to " "HTTPS in Django 7.0. Set the URLIZE_ASSUME_HTTPS " "transitional setting to True to opt into using HTTPS as the " "new default protocol.", RemovedInDjango70Warning, stacklevel=2, ) url = smart_urlquote(f"{protocol}://{unescaped_middle}") elif ":" not in middle and self.is_email_simple(middle): local, domain = middle.rsplit("@", 1) # Encode per RFC 6068 Section 2 (items 1, 4, 5). Defer any IDNA # to the user agent. See #36013. local = quote(local, safe="") domain = quote(domain, safe="") url = self.mailto_template.format(local=local, domain=domain) nofollow_attr = "" # Make link. if url: trimmed = self.trim_url(middle, limit=trim_url_limit) if autoescape and not safe_input: lead, trail = escape(lead), escape(trail) trimmed = escape(trimmed) middle = self.url_template.format( href=escape(url), attrs=nofollow_attr, url=trimmed, ) return SafeString(f"{lead}{middle}{trail}") else: if safe_input: return mark_safe(word) elif autoescape: return escape(word) elif safe_input: return mark_safe(word) elif autoescape: return escape(word) return word def trim_url(self, x, *, limit): if limit is None or len(x) <= limit: return x return "%s…" % x[: max(0, limit - 1)] @cached_property def wrapping_punctuation_openings(self): return "".join(dict(self.wrapping_punctuation).keys()) @cached_property def trailing_punctuation_chars_no_semicolon(self): return self.trailing_punctuation_chars.replace(";", "") @cached_property def trailing_punctuation_chars_has_semicolon(self): return ";" in self.trailing_punctuation_chars def trim_punctuation(self, word): """ Trim trailing and wrapping punctuation from `word`. Return the items of the new state. """ # Strip all opening wrapping punctuation. middle = word.lstrip(self.wrapping_punctuation_openings) lead = word[: len(word) - len(middle)] trail = deque() # Continue trimming until middle remains unchanged. trimmed_something = True counts = CountsDict(word=middle) while trimmed_something and middle: trimmed_something = False # Trim wrapping punctuation. for opening, closing in self.wrapping_punctuation: if counts[opening] < counts[closing]: rstripped = middle.rstrip(closing) if rstripped != middle: strip = counts[closing] - counts[opening] trail.appendleft(middle[-strip:]) middle = middle[:-strip] trimmed_something = True counts[closing] -= strip amp = middle.rfind("&") if amp == -1: rstripped = middle.rstrip(self.trailing_punctuation_chars) else: rstripped = middle.rstrip(self.trailing_punctuation_chars_no_semicolon) if rstripped != middle: trail.appendleft(middle[len(rstripped) :]) middle = rstripped trimmed_something = True if self.trailing_punctuation_chars_has_semicolon and middle.endswith(";"): # Only strip if not part of an HTML entity. potential_entity = middle[amp:] escaped = html.unescape(potential_entity) if escaped == potential_entity or escaped.endswith(";"): rstripped = middle.rstrip(self.trailing_punctuation_chars) trail_start = len(rstripped) amount_trailing_semicolons = len(middle) - len(middle.rstrip(";")) if amp > -1 and amount_trailing_semicolons > 1: # Leave up to most recent semicolon as might be an # entity. recent_semicolon = middle[trail_start:].index(";") middle_semicolon_index = recent_semicolon + trail_start + 1 trail.appendleft(middle[middle_semicolon_index:]) middle = rstripped + middle[trail_start:middle_semicolon_index] else: trail.appendleft(middle[trail_start:]) middle = rstripped trimmed_something = True trail = "".join(trail) return lead, middle, trail @staticmethod def is_email_simple(value): """Return True if value looks like an email address.""" try: EmailValidator(allowlist=[])(value) except ValidationError: return False return True urlizer = Urlizer() @keep_lazy_text def urlize(text, trim_url_limit=None, nofollow=False, autoescape=False): return urlizer( text, trim_url_limit=trim_url_limit, nofollow=nofollow, autoescape=autoescape ) def avoid_wrapping(value): """ Avoid text wrapping in the middle of a phrase by adding non-breaking spaces where there previously were normal spaces. """ return value.replace(" ", "\xa0") def html_safe(klass): """ A decorator that defines the __html__ method. This helps non-Django templates to detect classes whose __str__ methods return SafeString. """ if "__html__" in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it defines " "__html__()." % klass.__name__ ) if "__str__" not in klass.__dict__: raise ValueError( "can't apply @html_safe to %s because it doesn't " "define __str__()." % klass.__name__ ) klass_str = klass.__str__ klass.__str__ = lambda self: mark_safe(klass_str(self)) klass.__html__ = lambda self: str(self) return klass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/asyncio.py
django/utils/asyncio.py
import os from asyncio import get_running_loop from functools import wraps from django.core.exceptions import SynchronousOnlyOperation def async_unsafe(message): """ Decorator to mark functions as async-unsafe. Someone trying to access the function while in an async context will get an error message. """ def decorator(func): @wraps(func) def inner(*args, **kwargs): # Detect a running event loop in this thread. try: get_running_loop() except RuntimeError: pass else: if not os.environ.get("DJANGO_ALLOW_ASYNC_UNSAFE"): raise SynchronousOnlyOperation(message) # Pass onward. return func(*args, **kwargs) return inner # If the message is actually a function, then be a no-arguments decorator. if callable(message): func = message message = ( "You cannot call this from an async context - use a thread or " "sync_to_async." ) return decorator(func) else: return decorator
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/archive.py
django/utils/archive.py
""" Based on "python-archive" -- https://pypi.org/project/python-archive/ Copyright (c) 2010 Gary Wilson Jr. <gary.wilson@gmail.com> and contributors. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ import os import shutil import stat import tarfile import zipfile from django.core.exceptions import SuspiciousOperation class ArchiveException(Exception): """ Base exception class for all archive errors. """ class UnrecognizedArchiveFormat(ArchiveException): """ Error raised when passed file is not a recognized archive format. """ def extract(path, to_path): """ Unpack the tar or zip file at the specified path to the directory specified by to_path. """ with Archive(path) as archive: archive.extract(to_path) class Archive: """ The external API class that encapsulates an archive implementation. """ def __init__(self, file): self._archive = self._archive_cls(file)(file) @staticmethod def _archive_cls(file): cls = None if isinstance(file, str): filename = file else: try: filename = file.name except AttributeError: raise UnrecognizedArchiveFormat( "File object not a recognized archive format." ) base, tail_ext = os.path.splitext(filename.lower()) cls = extension_map.get(tail_ext) if not cls: base, ext = os.path.splitext(base) cls = extension_map.get(ext) if not cls: raise UnrecognizedArchiveFormat( "Path not a recognized archive format: %s" % filename ) return cls def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): self.close() def extract(self, to_path): self._archive.extract(to_path) def list(self): self._archive.list() def close(self): self._archive.close() class BaseArchive: """ Base Archive class. Implementations should inherit this class. """ @staticmethod def _copy_permissions(mode, filename): """ If the file in the archive has some permissions (this assumes a file won't be writable/executable without being readable), apply those permissions to the unarchived file. """ if mode & stat.S_IROTH: os.chmod(filename, mode) def split_leading_dir(self, path): path = str(path) path = path.lstrip("/").lstrip("\\") if "/" in path and ( ("\\" in path and path.find("/") < path.find("\\")) or "\\" not in path ): return path.split("/", 1) elif "\\" in path: return path.split("\\", 1) else: return path, "" def has_leading_dir(self, paths): """ Return True if all the paths have the same leading path name (i.e., everything is in one subdirectory in an archive). """ common_prefix = None for path in paths: prefix, rest = self.split_leading_dir(path) if not prefix: return False elif common_prefix is None: common_prefix = prefix elif prefix != common_prefix: return False return True def target_filename(self, to_path, name): target_path = os.path.abspath(to_path) filename = os.path.abspath(os.path.join(target_path, name)) try: if os.path.commonpath([target_path, filename]) != target_path: raise SuspiciousOperation("Archive contains invalid path: '%s'" % name) except ValueError: # Different drives on Windows raises ValueError. raise SuspiciousOperation("Archive contains invalid path: '%s'" % name) return filename def extract(self): raise NotImplementedError( "subclasses of BaseArchive must provide an extract() method" ) def list(self): raise NotImplementedError( "subclasses of BaseArchive must provide a list() method" ) class TarArchive(BaseArchive): def __init__(self, file): self._archive = tarfile.open(file) def list(self, *args, **kwargs): self._archive.list(*args, **kwargs) def extract(self, to_path): members = self._archive.getmembers() leading = self.has_leading_dir(x.name for x in members) for member in members: name = member.name if leading: name = self.split_leading_dir(name)[1] filename = self.target_filename(to_path, name) if member.isdir(): if filename: os.makedirs(filename, exist_ok=True) else: try: extracted = self._archive.extractfile(member) except (KeyError, AttributeError) as exc: # Some corrupt tar files seem to produce this # (specifically bad symlinks) print( "In the tar file %s the member %s is invalid: %s" % (name, member.name, exc) ) else: dirname = os.path.dirname(filename) if dirname: os.makedirs(dirname, exist_ok=True) with open(filename, "wb") as outfile: shutil.copyfileobj(extracted, outfile) self._copy_permissions(member.mode, filename) finally: if extracted: extracted.close() def close(self): self._archive.close() class ZipArchive(BaseArchive): def __init__(self, file): self._archive = zipfile.ZipFile(file) def list(self, *args, **kwargs): self._archive.printdir(*args, **kwargs) def extract(self, to_path): namelist = self._archive.namelist() leading = self.has_leading_dir(namelist) for name in namelist: data = self._archive.read(name) info = self._archive.getinfo(name) if leading: name = self.split_leading_dir(name)[1] if not name: continue filename = self.target_filename(to_path, name) if name.endswith(("/", "\\")): # A directory os.makedirs(filename, exist_ok=True) else: dirname = os.path.dirname(filename) if dirname: os.makedirs(dirname, exist_ok=True) with open(filename, "wb") as outfile: outfile.write(data) # Convert ZipInfo.external_attr to mode mode = info.external_attr >> 16 self._copy_permissions(mode, filename) def close(self): self._archive.close() extension_map = dict.fromkeys( ( ".tar", ".tar.bz2", ".tbz2", ".tbz", ".tz2", ".tar.gz", ".tgz", ".taz", ".tar.lzma", ".tlz", ".tar.xz", ".txz", ), TarArchive, ) extension_map[".zip"] = ZipArchive
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/feedgenerator.py
django/utils/feedgenerator.py
""" Syndication feed generation library -- used for generating RSS, etc. Sample usage: >>> from django.utils import feedgenerator >>> feed = feedgenerator.Rss201rev2Feed( ... title="Poynter E-Media Tidbits", ... link="http://www.poynter.org/column.asp?id=31", ... description="A group blog by the sharpest minds in online journalism.", ... language="en", ... ) >>> feed.add_item( ... title="Hello", ... link="http://www.holovaty.com/test/", ... description="Testing." ... ) >>> with open('test.rss', 'w') as fp: ... feed.write(fp, 'utf-8') For definitions of the different versions of RSS, see: https://web.archive.org/web/20110718035220/http://diveintomark.org/archives/2004/02/04/incompatible-rss """ import datetime import email import mimetypes from io import StringIO from urllib.parse import urlparse from django.forms.utils import flatatt from django.utils.encoding import iri_to_uri from django.utils.xmlutils import SimplerXMLGenerator def rfc2822_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return email.utils.format_datetime(date) def rfc3339_date(date): if not isinstance(date, datetime.datetime): date = datetime.datetime.combine(date, datetime.time()) return date.isoformat() + ("Z" if date.utcoffset() is None else "") def get_tag_uri(url, date): """ Create a TagURI. See https://web.archive.org/web/20110514113830/http://diveintomark.org/archives/2004/05/28/howto-atom-id """ bits = urlparse(url) d = "" if date is not None: d = ",%s" % date.strftime("%Y-%m-%d") return "tag:%s%s:%s/%s" % (bits.hostname, d, bits.path, bits.fragment) def _guess_stylesheet_mimetype(url): """ Return the given stylesheet's mimetype tuple, using a slightly custom version of Python's mimetypes.guess_type(). """ mimetypedb = mimetypes.MimeTypes() # The official mimetype for XSLT files is technically # `application/xslt+xml` but as of 2024 almost no browser supports that # (they all expect text/xsl). On top of that, windows seems to assume that # the type for xsl is text/xml. mimetypedb.readfp(StringIO("text/xsl\txsl\ntext/xsl\txslt")) return mimetypedb.guess_type(url) class Stylesheet: """An RSS stylesheet""" def __init__(self, url, mimetype="", media="screen"): self._url = url self._mimetype = mimetype self.media = media # Using a property to delay the evaluation of self._url as late as possible # in case of a lazy object (like reverse_lazy(...) for example). @property def url(self): return iri_to_uri(self._url) @property def mimetype(self): if self._mimetype == "": return _guess_stylesheet_mimetype(self.url)[0] return self._mimetype def __str__(self): attrs = { "href": iri_to_uri(self._url), "type": self.mimetype, "media": self.media, } return flatatt(attrs).strip() def __repr__(self): return repr((self.url, self.mimetype, self.media)) class SyndicationFeed: "Base class for all syndication feeds. Subclasses should provide write()" def __init__( self, title, link, description, language=None, author_email=None, author_name=None, author_link=None, subtitle=None, categories=None, feed_url=None, feed_copyright=None, feed_guid=None, ttl=None, stylesheets=None, **kwargs, ): def to_str(s): return str(s) if s is not None else s def to_stylesheet(s): return s if isinstance(s, Stylesheet) else Stylesheet(s) categories = categories and [str(c) for c in categories] if stylesheets is not None: if isinstance(stylesheets, (Stylesheet, str)): raise TypeError( f"stylesheets should be a list, not {stylesheets.__class__}" ) stylesheets = [to_stylesheet(s) for s in stylesheets] self.feed = { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "language": to_str(language), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "subtitle": to_str(subtitle), "categories": categories or (), "feed_url": iri_to_uri(feed_url), "feed_copyright": to_str(feed_copyright), "id": feed_guid or link, "ttl": to_str(ttl), "stylesheets": stylesheets, **kwargs, } self.items = [] def add_item( self, title, link, description, author_email=None, author_name=None, author_link=None, pubdate=None, comments=None, unique_id=None, unique_id_is_permalink=None, categories=(), item_copyright=None, ttl=None, updateddate=None, enclosures=None, **kwargs, ): """ Add an item to the feed. All args are expected to be strings except pubdate and updateddate, which are datetime.datetime objects, and enclosures, which is an iterable of instances of the Enclosure class. """ def to_str(s): return str(s) if s is not None else s categories = categories and [to_str(c) for c in categories] self.items.append( { "title": to_str(title), "link": iri_to_uri(link), "description": to_str(description), "author_email": to_str(author_email), "author_name": to_str(author_name), "author_link": iri_to_uri(author_link), "pubdate": pubdate, "updateddate": updateddate, "comments": to_str(comments), "unique_id": to_str(unique_id), "unique_id_is_permalink": unique_id_is_permalink, "enclosures": enclosures or (), "categories": categories or (), "item_copyright": to_str(item_copyright), "ttl": to_str(ttl), **kwargs, } ) def num_items(self): return len(self.items) def root_attributes(self): """ Return extra attributes to place on the root (i.e. feed/channel) element. Called from write(). """ return {} def add_root_elements(self, handler): """ Add elements in the root (i.e. feed/channel) element. Called from write(). """ pass def add_stylesheets(self, handler): """ Add stylesheet(s) to the feed. Called from write(). """ pass def item_attributes(self, item): """ Return extra attributes to place on each item (i.e. item/entry) element. """ return {} def add_item_elements(self, handler, item): """ Add elements on each item (i.e. item/entry) element. """ pass def write(self, outfile, encoding): """ Output the feed in the given encoding to outfile, which is a file-like object. Subclasses should override this. """ raise NotImplementedError( "subclasses of SyndicationFeed must provide a write() method" ) def writeString(self, encoding): """ Return the feed in the given encoding as a string. """ s = StringIO() self.write(s, encoding) return s.getvalue() def latest_post_date(self): """ Return the latest item's pubdate or updateddate. If no items have either of these attributes this return the current UTC date/time. """ latest_date = None date_keys = ("updateddate", "pubdate") for item in self.items: for date_key in date_keys: item_date = item.get(date_key) if item_date: if latest_date is None or item_date > latest_date: latest_date = item_date return latest_date or datetime.datetime.now(tz=datetime.UTC) class Enclosure: """An RSS enclosure""" def __init__(self, url, length, mime_type): "All args are expected to be strings" self.length, self.mime_type = length, mime_type self.url = iri_to_uri(url) class RssFeed(SyndicationFeed): content_type = "application/rss+xml; charset=utf-8" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() # Any stylesheet must come after the start of the document but before # any tag. https://www.w3.org/Style/styling-XML.en.html self.add_stylesheets(handler) handler.startElement("rss", self.rss_attributes()) handler.startElement("channel", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) self.endChannelElement(handler) handler.endElement("rss") def rss_attributes(self): return { "version": self._version, "xmlns:atom": "http://www.w3.org/2005/Atom", } def write_items(self, handler): for item in self.items: handler.startElement("item", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("item") def add_stylesheets(self, handler): for stylesheet in self.feed["stylesheets"] or []: handler.processingInstruction("xml-stylesheet", stylesheet) def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement("link", self.feed["link"]) handler.addQuickElement("description", self.feed["description"]) if self.feed["feed_url"] is not None: handler.addQuickElement( "atom:link", None, {"rel": "self", "href": self.feed["feed_url"]} ) if self.feed["language"] is not None: handler.addQuickElement("language", self.feed["language"]) for cat in self.feed["categories"]: handler.addQuickElement("category", cat) if self.feed["feed_copyright"] is not None: handler.addQuickElement("copyright", self.feed["feed_copyright"]) handler.addQuickElement("lastBuildDate", rfc2822_date(self.latest_post_date())) if self.feed["ttl"] is not None: handler.addQuickElement("ttl", self.feed["ttl"]) def endChannelElement(self, handler): handler.endElement("channel") class RssUserland091Feed(RssFeed): _version = "0.91" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) class Rss201rev2Feed(RssFeed): # Spec: https://cyber.harvard.edu/rss/rss.html _version = "2.0" def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", item["link"]) if item["description"] is not None: handler.addQuickElement("description", item["description"]) # Author information. if item["author_name"] and item["author_email"]: handler.addQuickElement( "author", "%s (%s)" % (item["author_email"], item["author_name"]) ) elif item["author_email"]: handler.addQuickElement("author", item["author_email"]) elif item["author_name"]: handler.addQuickElement( "dc:creator", item["author_name"], {"xmlns:dc": "http://purl.org/dc/elements/1.1/"}, ) if item["pubdate"] is not None: handler.addQuickElement("pubDate", rfc2822_date(item["pubdate"])) if item["comments"] is not None: handler.addQuickElement("comments", item["comments"]) if item["unique_id"] is not None: guid_attrs = {} if isinstance(item.get("unique_id_is_permalink"), bool): guid_attrs["isPermaLink"] = str(item["unique_id_is_permalink"]).lower() handler.addQuickElement("guid", item["unique_id"], guid_attrs) if item["ttl"] is not None: handler.addQuickElement("ttl", item["ttl"]) # Enclosure. if item["enclosures"]: enclosures = list(item["enclosures"]) if len(enclosures) > 1: raise ValueError( "RSS feed items may only have one enclosure, see " "http://www.rssboard.org/rss-profile#element-channel-item-enclosure" ) enclosure = enclosures[0] handler.addQuickElement( "enclosure", "", { "url": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", cat) class Atom1Feed(SyndicationFeed): # Spec: https://tools.ietf.org/html/rfc4287 content_type = "application/atom+xml; charset=utf-8" ns = "http://www.w3.org/2005/Atom" def write(self, outfile, encoding): handler = SimplerXMLGenerator(outfile, encoding, short_empty_elements=True) handler.startDocument() handler.startElement("feed", self.root_attributes()) self.add_root_elements(handler) self.write_items(handler) handler.endElement("feed") def root_attributes(self): if self.feed["language"] is not None: return {"xmlns": self.ns, "xml:lang": self.feed["language"]} else: return {"xmlns": self.ns} def add_root_elements(self, handler): handler.addQuickElement("title", self.feed["title"]) handler.addQuickElement( "link", "", {"rel": "alternate", "href": self.feed["link"]} ) if self.feed["feed_url"] is not None: handler.addQuickElement( "link", "", {"rel": "self", "href": self.feed["feed_url"]} ) handler.addQuickElement("id", self.feed["id"]) handler.addQuickElement("updated", rfc3339_date(self.latest_post_date())) if self.feed["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", self.feed["author_name"]) if self.feed["author_email"] is not None: handler.addQuickElement("email", self.feed["author_email"]) if self.feed["author_link"] is not None: handler.addQuickElement("uri", self.feed["author_link"]) handler.endElement("author") if self.feed["subtitle"] is not None: handler.addQuickElement("subtitle", self.feed["subtitle"]) for cat in self.feed["categories"]: handler.addQuickElement("category", "", {"term": cat}) if self.feed["feed_copyright"] is not None: handler.addQuickElement("rights", self.feed["feed_copyright"]) def write_items(self, handler): for item in self.items: handler.startElement("entry", self.item_attributes(item)) self.add_item_elements(handler, item) handler.endElement("entry") def add_item_elements(self, handler, item): handler.addQuickElement("title", item["title"]) handler.addQuickElement("link", "", {"href": item["link"], "rel": "alternate"}) if item["pubdate"] is not None: handler.addQuickElement("published", rfc3339_date(item["pubdate"])) if item["updateddate"] is not None: handler.addQuickElement("updated", rfc3339_date(item["updateddate"])) # Author information. if item["author_name"] is not None: handler.startElement("author", {}) handler.addQuickElement("name", item["author_name"]) if item["author_email"] is not None: handler.addQuickElement("email", item["author_email"]) if item["author_link"] is not None: handler.addQuickElement("uri", item["author_link"]) handler.endElement("author") # Unique ID. if item["unique_id"] is not None: unique_id = item["unique_id"] else: unique_id = get_tag_uri(item["link"], item["pubdate"]) handler.addQuickElement("id", unique_id) # Summary. if item["description"] is not None: handler.addQuickElement("summary", item["description"], {"type": "html"}) # Enclosures. for enclosure in item["enclosures"]: handler.addQuickElement( "link", "", { "rel": "enclosure", "href": enclosure.url, "length": enclosure.length, "type": enclosure.mime_type, }, ) # Categories. for cat in item["categories"]: handler.addQuickElement("category", "", {"term": cat}) # Rights. if item["item_copyright"] is not None: handler.addQuickElement("rights", item["item_copyright"]) # This isolates the decision of what the system default is, so calling code can # do "feedgenerator.DefaultFeed" instead of "feedgenerator.Rss201rev2Feed". DefaultFeed = Rss201rev2Feed
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/functional.py
django/utils/functional.py
import copy import itertools import operator from functools import wraps class cached_property: """ Decorator that converts a method with a single self argument into a property cached on the instance. A cached property can be made out of an existing method: (e.g. ``url = cached_property(get_absolute_url)``). """ name = None @staticmethod def func(instance): raise TypeError( "Cannot use cached_property instance without calling " "__set_name__() on it." ) def __init__(self, func): self.real_func = func self.__doc__ = getattr(func, "__doc__") def __set_name__(self, owner, name): if self.name is None: self.name = name self.func = self.real_func elif name != self.name: raise TypeError( "Cannot assign the same cached_property to two different names " "(%r and %r)." % (self.name, name) ) def __get__(self, instance, cls=None): """ Call the function and put the return value in instance.__dict__ so that subsequent attribute access on the instance returns the cached value instead of calling cached_property.__get__(). """ if instance is None: return self res = instance.__dict__[self.name] = self.func(instance) return res class classproperty: """ Decorator that converts a method with a single cls argument into a property that can be accessed directly from the class. """ def __init__(self, method=None): self.fget = method def __get__(self, instance, cls=None): return self.fget(cls) def getter(self, method): self.fget = method return self class Promise: """ Base class for the proxy class created in the closure of the lazy function. It's used to recognize promises in code. """ pass def lazy(func, *resultclasses): """ Turn any callable into a lazy evaluated callable. result classes or types is required -- at least one is needed so that the automatic forcing of the lazy evaluation code is triggered. Results are not memoized; the function is evaluated on every access. """ class __proxy__(Promise): """ Encapsulate a function call and act as a proxy for methods that are called on the result of that function. The function is not evaluated until one of the methods on the result is called. """ def __init__(self, args, kw): self._args = args self._kw = kw def __reduce__(self): return ( _lazy_proxy_unpickle, (func, self._args, self._kw, *resultclasses), ) def __deepcopy__(self, memo): # Instances of this class are effectively immutable. It's just a # collection of functions. So we don't need to do anything # complicated for copying. memo[id(self)] = self return self def __cast(self): return func(*self._args, **self._kw) # Explicitly wrap methods which are defined on object and hence would # not have been overloaded by the loop over resultclasses below. def __repr__(self): return repr(self.__cast()) def __str__(self): return str(self.__cast()) def __eq__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() == other def __ne__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() != other def __lt__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() < other def __le__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() <= other def __gt__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() > other def __ge__(self, other): if isinstance(other, Promise): other = other.__cast() return self.__cast() >= other def __hash__(self): return hash(self.__cast()) def __format__(self, format_spec): return format(self.__cast(), format_spec) # Explicitly wrap methods which are required for certain operations on # int/str objects to function correctly. def __add__(self, other): return self.__cast() + other def __radd__(self, other): return other + self.__cast() def __mod__(self, other): return self.__cast() % other def __mul__(self, other): return self.__cast() * other # Add wrappers for all methods from resultclasses which haven't been # wrapped explicitly above. for resultclass in resultclasses: for type_ in resultclass.mro(): for method_name in type_.__dict__: # All __promise__ return the same wrapper method, they look up # the correct implementation when called. if hasattr(__proxy__, method_name): continue # Builds a wrapper around some method. Pass method_name to # avoid issues due to late binding. def __wrapper__(self, *args, __method_name=method_name, **kw): # Automatically triggers the evaluation of a lazy value and # applies the given method of the result type. result = func(*self._args, **self._kw) return getattr(result, __method_name)(*args, **kw) setattr(__proxy__, method_name, __wrapper__) @wraps(func) def __wrapper__(*args, **kw): # Creates the proxy object, instead of the actual value. return __proxy__(args, kw) return __wrapper__ def _lazy_proxy_unpickle(func, args, kwargs, *resultclasses): return lazy(func, *resultclasses)(*args, **kwargs) def lazystr(text): """ Shortcut for the common case of a lazy callable that returns str. """ return lazy(str, str)(text) def keep_lazy(*resultclasses): """ A decorator that allows a function to be called with one or more lazy arguments. If none of the args are lazy, the function is evaluated immediately, otherwise a __proxy__ is returned that will evaluate the function when needed. """ if not resultclasses: raise TypeError("You must pass at least one argument to keep_lazy().") def decorator(func): lazy_func = lazy(func, *resultclasses) @wraps(func) def wrapper(*args, **kwargs): if any( isinstance(arg, Promise) for arg in itertools.chain(args, kwargs.values()) ): return lazy_func(*args, **kwargs) return func(*args, **kwargs) return wrapper return decorator def keep_lazy_text(func): """ A decorator for functions that accept lazy arguments and return text. """ return keep_lazy(str)(func) empty = object() def new_method_proxy(func): def inner(self, *args): if (_wrapped := self._wrapped) is empty: self._setup() _wrapped = self._wrapped return func(_wrapped, *args) inner._mask_wrapped = False return inner class LazyObject: """ A wrapper for another class that can be used to delay instantiation of the wrapped class. By subclassing, you have the opportunity to intercept and alter the instantiation. If you don't need to do that, use SimpleLazyObject. """ # Avoid infinite recursion when tracing __init__ (#19456). _wrapped = None def __init__(self): # Note: if a subclass overrides __init__(), it will likely need to # override __copy__() and __deepcopy__() as well. self._wrapped = empty def __getattribute__(self, name): if name == "_wrapped": # Avoid recursion when getting wrapped object. return super().__getattribute__(name) value = super().__getattribute__(name) # If attribute is a proxy method, raise an AttributeError to call # __getattr__() and use the wrapped object method. if not getattr(value, "_mask_wrapped", True): raise AttributeError return value __getattr__ = new_method_proxy(getattr) def __setattr__(self, name, value): if name == "_wrapped": # Assign to __dict__ to avoid infinite __setattr__ loops. self.__dict__["_wrapped"] = value else: if self._wrapped is empty: self._setup() setattr(self._wrapped, name, value) def __delattr__(self, name): if name == "_wrapped": raise TypeError("can't delete _wrapped.") if self._wrapped is empty: self._setup() delattr(self._wrapped, name) def _setup(self): """ Must be implemented by subclasses to initialize the wrapped object. """ raise NotImplementedError( "subclasses of LazyObject must provide a _setup() method" ) # Because we have messed with __class__ below, we confuse pickle as to what # class we are pickling. We're going to have to initialize the wrapped # object to successfully pickle it, so we might as well just pickle the # wrapped object since they're supposed to act the same way. # # Unfortunately, if we try to simply act like the wrapped object, the ruse # will break down when pickle gets our id(). Thus we end up with pickle # thinking, in effect, that we are a distinct object from the wrapped # object, but with the same __dict__. This can cause problems (see #25389). # # So instead, we define our own __reduce__ method and custom unpickler. We # pickle the wrapped object as the unpickler's argument, so that pickle # will pickle it normally, and then the unpickler simply returns its # argument. def __reduce__(self): if self._wrapped is empty: self._setup() return (unpickle_lazyobject, (self._wrapped,)) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use type(self), not # self.__class__, because the latter is proxied. return type(self)() else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use type(self), not self.__class__, because the # latter is proxied. result = type(self)() memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __bytes__ = new_method_proxy(bytes) __str__ = new_method_proxy(str) __bool__ = new_method_proxy(bool) # Introspection support __dir__ = new_method_proxy(dir) # Need to pretend to be the wrapped class, for the sake of objects that # care about this (especially in equality tests) __class__ = property(new_method_proxy(operator.attrgetter("__class__"))) __eq__ = new_method_proxy(operator.eq) __lt__ = new_method_proxy(operator.lt) __gt__ = new_method_proxy(operator.gt) __ne__ = new_method_proxy(operator.ne) __hash__ = new_method_proxy(hash) # List/Tuple/Dictionary methods support __getitem__ = new_method_proxy(operator.getitem) __setitem__ = new_method_proxy(operator.setitem) __delitem__ = new_method_proxy(operator.delitem) __iter__ = new_method_proxy(iter) __len__ = new_method_proxy(len) __contains__ = new_method_proxy(operator.contains) def unpickle_lazyobject(wrapped): """ Used to unpickle lazy objects. Just return its argument, which will be the wrapped object. """ return wrapped class SimpleLazyObject(LazyObject): """ A lazy object initialized from any function. Designed for compound objects of unknown type. For builtins or objects of known type, use django.utils.functional.lazy. """ def __init__(self, func): """ Pass in a callable that returns the object to be wrapped. If copies are made of the resulting SimpleLazyObject, which can happen in various circumstances within Django, then you must ensure that the callable can be safely run more than once and will return the same value. """ self.__dict__["_setupfunc"] = func super().__init__() def _setup(self): self._wrapped = self._setupfunc() # Return a meaningful representation of the lazy object for debugging # without evaluating the wrapped object. def __repr__(self): if self._wrapped is empty: # Avoid recursion if setupfunc is a bound method of this instance. if getattr(self._setupfunc, "__self__", None) is self: repr_attr = f"<bound method {self._setupfunc.__name__}>" else: repr_attr = self._setupfunc else: repr_attr = self._wrapped return "<%s: %r>" % (type(self).__name__, repr_attr) def __copy__(self): if self._wrapped is empty: # If uninitialized, copy the wrapper. Use SimpleLazyObject, not # self.__class__, because the latter is proxied. return SimpleLazyObject(self._setupfunc) else: # If initialized, return a copy of the wrapped object. return copy.copy(self._wrapped) def __deepcopy__(self, memo): if self._wrapped is empty: # We have to use SimpleLazyObject, not self.__class__, because the # latter is proxied. result = SimpleLazyObject(self._setupfunc) memo[id(self)] = result return result return copy.deepcopy(self._wrapped, memo) __add__ = new_method_proxy(operator.add) @new_method_proxy def __radd__(self, other): return other + self def partition(predicate, values): """ Split the values into two sets, based on the return value of the function (True/False). e.g.: >>> partition(lambda x: x > 3, range(5)) [0, 1, 2, 3], [4] """ results = ([], []) for item in values: results[predicate(item)].append(item) return results
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/duration.py
django/utils/duration.py
import datetime def _get_duration_components(duration): days = duration.days seconds = duration.seconds microseconds = duration.microseconds minutes = seconds // 60 seconds %= 60 hours = minutes // 60 minutes %= 60 return days, hours, minutes, seconds, microseconds def duration_string(duration): """Version of str(timedelta) which is not English specific.""" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) string = "{:02d}:{:02d}:{:02d}".format(hours, minutes, seconds) if days: string = "{} ".format(days) + string if microseconds: string += ".{:06d}".format(microseconds) return string def duration_iso_string(duration): if duration < datetime.timedelta(0): sign = "-" duration *= -1 else: sign = "" days, hours, minutes, seconds, microseconds = _get_duration_components(duration) ms = ".{:06d}".format(microseconds) if microseconds else "" return "{}P{}DT{:02d}H{:02d}M{:02d}{}S".format( sign, days, hours, minutes, seconds, ms ) def duration_microseconds(delta): return (24 * 60 * 60 * delta.days + delta.seconds) * 1000000 + delta.microseconds
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/datastructures.py
django/utils/datastructures.py
import copy from collections.abc import Mapping class OrderedSet: """ A set which keeps the ordering of the inserted items. """ def __init__(self, iterable=None): self.dict = dict.fromkeys(iterable or ()) def add(self, item): self.dict[item] = None def remove(self, item): del self.dict[item] def discard(self, item): try: self.remove(item) except KeyError: pass def __iter__(self): return iter(self.dict) def __reversed__(self): return reversed(self.dict) def __contains__(self, item): return item in self.dict def __bool__(self): return bool(self.dict) def __len__(self): return len(self.dict) def __repr__(self): data = repr(list(self.dict)) if self.dict else "" return f"{self.__class__.__qualname__}({data})" class MultiValueDictKeyError(KeyError): pass class MultiValueDict(dict): """ A subclass of dictionary customized to handle multiple values for the same key. >>> d = MultiValueDict( ... {'name': ['Adrian', 'Simon'], 'position': ['Developer']} ... ) >>> d['name'] 'Simon' >>> d.getlist('name') ['Adrian', 'Simon'] >>> d.getlist('doesnotexist') [] >>> d.getlist('doesnotexist', ['Adrian', 'Simon']) ['Adrian', 'Simon'] >>> d.get('lastname', 'nonexistent') 'nonexistent' >>> d.setlist('lastname', ['Holovaty', 'Willison']) This class exists to solve the irritating problem raised by cgi.parse_qs, which returns a list for every key, even though most web forms submit single name-value pairs. """ def __init__(self, key_to_list_mapping=()): super().__init__(key_to_list_mapping) def __repr__(self): return "<%s: %s>" % (self.__class__.__name__, super().__repr__()) def __getitem__(self, key): """ Return the last data value for this key, or [] if it's an empty list; raise KeyError if not found. """ try: list_ = super().__getitem__(key) except KeyError: raise MultiValueDictKeyError(key) try: return list_[-1] except IndexError: return [] def __setitem__(self, key, value): super().__setitem__(key, [value]) def __copy__(self): return self.__class__([(k, v[:]) for k, v in self.lists()]) def __deepcopy__(self, memo): result = self.__class__() memo[id(self)] = result for key, value in dict.items(self): dict.__setitem__( result, copy.deepcopy(key, memo), copy.deepcopy(value, memo) ) return result def __getstate__(self): return {**self.__dict__, "_data": {k: self._getlist(k) for k in self}} def __setstate__(self, obj_dict): data = obj_dict.pop("_data", {}) for k, v in data.items(): self.setlist(k, v) self.__dict__.update(obj_dict) def get(self, key, default=None): """ Return the last data value for the passed key. If key doesn't exist or value is an empty list, return `default`. """ try: val = self[key] except KeyError: return default if val == []: return default return val def _getlist(self, key, default=None, force_list=False): """ Return a list of values for the key. Used internally to manipulate values list. If force_list is True, return a new copy of values. """ try: values = super().__getitem__(key) except KeyError: if default is None: return [] return default else: if force_list: values = list(values) if values is not None else None return values def getlist(self, key, default=None): """ Return the list of values for the key. If key doesn't exist, return a default value. """ return self._getlist(key, default, force_list=True) def setlist(self, key, list_): super().__setitem__(key, list_) def setdefault(self, key, default=None): if key not in self: self[key] = default # Do not return default here because __setitem__() may store # another value -- QueryDict.__setitem__() does. Look it up. return self[key] def setlistdefault(self, key, default_list=None): if key not in self: if default_list is None: default_list = [] self.setlist(key, default_list) # Do not return default_list here because setlist() may store # another value -- QueryDict.setlist() does. Look it up. return self._getlist(key) def appendlist(self, key, value): """Append an item to the internal list associated with key.""" self.setlistdefault(key).append(value) def items(self): """ Yield (key, value) pairs, where value is the last item in the list associated with the key. """ for key in self: yield key, self[key] def lists(self): """Yield (key, list) pairs.""" return iter(super().items()) def values(self): """Yield the last value on every key list.""" for key in self: yield self[key] def copy(self): """Return a shallow copy of this object.""" return copy.copy(self) def update(self, *args, **kwargs): """Extend rather than replace existing key lists.""" if len(args) > 1: raise TypeError("update expected at most 1 argument, got %d" % len(args)) if args: arg = args[0] if isinstance(arg, MultiValueDict): for key, value_list in arg.lists(): self.setlistdefault(key).extend(value_list) else: if isinstance(arg, Mapping): arg = arg.items() for key, value in arg: self.setlistdefault(key).append(value) for key, value in kwargs.items(): self.setlistdefault(key).append(value) def dict(self): """Return current object as a dict with singular values.""" return {key: self[key] for key in self} class ImmutableList(tuple): """ A tuple-like object that raises useful errors when it is asked to mutate. Example:: >>> a = ImmutableList(range(5), warning="You cannot mutate this.") >>> a[3] = '4' Traceback (most recent call last): ... AttributeError: You cannot mutate this. """ def __new__(cls, *args, warning="ImmutableList object is immutable.", **kwargs): self = tuple.__new__(cls, *args, **kwargs) self.warning = warning return self def complain(self, *args, **kwargs): raise AttributeError(self.warning) # All list mutation functions complain. __delitem__ = complain __delslice__ = complain __iadd__ = complain __imul__ = complain __setitem__ = complain __setslice__ = complain append = complain extend = complain insert = complain pop = complain remove = complain sort = complain reverse = complain class DictWrapper(dict): """ Wrap accesses to a dictionary so that certain values (those starting with the specified prefix) are passed through a function before being returned. The prefix is removed before looking up the real value. Used by the SQL construction code to ensure that values are correctly quoted before being used. """ def __init__(self, data, func, prefix): super().__init__(data) self.func = func self.prefix = prefix def __getitem__(self, key): """ Retrieve the real value after stripping the prefix string (if present). If the prefix is present, pass the value through self.func before returning, otherwise return the raw value. """ use_func = key.startswith(self.prefix) key = key.removeprefix(self.prefix) value = super().__getitem__(key) if use_func: return self.func(value) return value class CaseInsensitiveMapping(Mapping): """ Mapping allowing case-insensitive key lookups. Original case of keys is preserved for iteration and string representation. Example:: >>> ci_map = CaseInsensitiveMapping({'name': 'Jane'}) >>> ci_map['Name'] Jane >>> ci_map['NAME'] Jane >>> ci_map['name'] Jane >>> ci_map # original case preserved {'name': 'Jane'} """ def __init__(self, data): self._store = {k.lower(): (k, v) for k, v in self._unpack_items(data)} def __getitem__(self, key): return self._store[key.lower()][1] def __len__(self): return len(self._store) def __eq__(self, other): return isinstance(other, Mapping) and { k.lower(): v for k, v in self.items() } == {k.lower(): v for k, v in other.items()} def __iter__(self): return (original_key for original_key, value in self._store.values()) def __repr__(self): return repr({key: value for key, value in self._store.values()}) def copy(self): return self @staticmethod def _unpack_items(data): # Explicitly test for dict first as the common case for performance, # avoiding abc's __instancecheck__ and _abc_instancecheck for the # general Mapping case. if isinstance(data, (dict, Mapping)): yield from data.items() return for i, elem in enumerate(data): if len(elem) != 2: raise ValueError( "dictionary update sequence element #{} has length {}; " "2 is required.".format(i, len(elem)) ) if not isinstance(elem[0], str): raise ValueError( "Element key %r invalid, only strings are allowed" % elem[0] ) yield elem class DeferredSubDict: """ Wrap a dict, allowing deferred access to a sub-dict under a given key. The value at ``deferred_key`` must itself be a dict. Accessing ``DeferredSubDict(parent_dict, deferred_key)[key]`` retrieves ``parent_dict[deferred_key][key]`` at access time, so updates to the parent dict are reflected. """ def __init__(self, parent_dict, deferred_key): self.parent_dict = parent_dict self.deferred_key = deferred_key def __getitem__(self, key): return self.parent_dict[self.deferred_key][key]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/version.py
django/utils/version.py
import datetime import functools import os import subprocess import sys from django.utils.regex_helper import _lazy_re_compile # Private, stable API for detecting the Python implementation. PYPY = sys.implementation.name == "pypy" # Private, stable API for detecting the Python version. PYXY means "Python X.Y # or later". So that third-party apps can use these values, each constant # should remain as long as the oldest supported Django version supports that # Python version. PY38 = sys.version_info >= (3, 8) PY39 = sys.version_info >= (3, 9) PY310 = sys.version_info >= (3, 10) PY311 = sys.version_info >= (3, 11) PY312 = sys.version_info >= (3, 12) PY313 = sys.version_info >= (3, 13) PY314 = sys.version_info >= (3, 14) PY315 = sys.version_info >= (3, 15) def get_version(version=None): """Return a PEP 440-compliant version number from VERSION.""" version = get_complete_version(version) # Now build the two parts of the version number: # main = X.Y[.Z] # sub = .devN - for pre-alpha releases # | {a|b|rc}N - for alpha, beta, and rc releases main = get_main_version(version) sub = "" if version[3] == "alpha" and version[4] == 0: git_changeset = get_git_changeset() if git_changeset: sub = ".dev%s" % git_changeset elif version[3] != "final": mapping = {"alpha": "a", "beta": "b", "rc": "rc"} sub = mapping[version[3]] + str(version[4]) return main + sub def get_main_version(version=None): """Return main version (X.Y[.Z]) from VERSION.""" version = get_complete_version(version) parts = 2 if version[2] == 0 else 3 return ".".join(str(x) for x in version[:parts]) def get_complete_version(version=None): """ Return a tuple of the django version. If version argument is non-empty, check for correctness of the tuple provided. """ if version is None: from django import VERSION as version else: assert len(version) == 5 assert version[3] in ("alpha", "beta", "rc", "final") return version def get_docs_version(version=None): version = get_complete_version(version) if version[3] != "final": return "dev" else: return "%d.%d" % version[:2] @functools.lru_cache def get_git_changeset(): """Return a numeric identifier of the latest git changeset. The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format. This value isn't guaranteed to be unique, but collisions are very unlikely, so it's sufficient for generating the development version numbers. """ # Repository may not be found if __file__ is undefined, e.g. in a frozen # module. if "__file__" not in globals(): return None repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) git_log = subprocess.run( "git log --pretty=format:%ct --quiet -1 HEAD", capture_output=True, shell=True, cwd=repo_dir, text=True, ) timestamp = git_log.stdout tz = datetime.UTC try: timestamp = datetime.datetime.fromtimestamp(int(timestamp), tz=tz) except ValueError: return None return timestamp.strftime("%Y%m%d%H%M%S") version_component_re = _lazy_re_compile(r"(\d+|[a-z]+|\.)") def get_version_tuple(version): """ Return a tuple of version numbers (e.g. (1, 2, 3)) from the version string (e.g. '1.2.3'). """ version_numbers = [] for item in version_component_re.split(version): if item and item != ".": try: component = int(item) except ValueError: break else: version_numbers.append(component) return tuple(version_numbers)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/decorators.py
django/utils/decorators.py
"Functions that help with dynamically creating decorators for views." from functools import partial, update_wrapper, wraps from asgiref.sync import iscoroutinefunction, markcoroutinefunction class classonlymethod(classmethod): def __get__(self, instance, cls=None): if instance is not None: raise AttributeError( "This method is available only on the class, not on instances." ) return super().__get__(instance, cls) def _update_method_wrapper(_wrapper, decorator): # _multi_decorate()'s bound_method isn't available in this scope. Cheat by # using it on a dummy function. @decorator def dummy(*args, **kwargs): pass update_wrapper(_wrapper, dummy) def _multi_decorate(decorators, method): """ Decorate `method` with one or more function decorators. `decorators` can be a single decorator or an iterable of decorators. """ if hasattr(decorators, "__iter__"): # Apply a list/tuple of decorators if 'decorators' is one. Decorator # functions are applied so that the call order is the same as the # order in which they appear in the iterable. decorators = decorators[::-1] else: decorators = [decorators] def _wrapper(self, *args, **kwargs): # bound_method has the signature that 'decorator' expects i.e. no # 'self' argument, but it's a closure over self so it can call # 'func'. Also, wrap method.__get__() in a function because new # attributes can't be set on bound method objects, only on functions. bound_method = wraps(method)(partial(method.__get__(self, type(self)))) for dec in decorators: bound_method = dec(bound_method) return bound_method(*args, **kwargs) # Copy any attributes that a decorator adds to the function it decorates. for dec in decorators: _update_method_wrapper(_wrapper, dec) # Preserve any existing attributes of 'method', including the name. update_wrapper(_wrapper, method) if iscoroutinefunction(method): markcoroutinefunction(_wrapper) return _wrapper def method_decorator(decorator, name=""): """ Convert a function decorator into a method decorator """ # 'obj' can be a class or a function. If 'obj' is a function at the time it # is passed to _dec, it will eventually be a method of the class it is # defined on. If 'obj' is a class, the 'name' is required to be the name # of the method that will be decorated. def _dec(obj): if not isinstance(obj, type): return _multi_decorate(decorator, obj) if not (name and hasattr(obj, name)): raise ValueError( "The keyword argument `name` must be the name of a method " "of the decorated class: %s. Got '%s' instead." % (obj, name) ) method = getattr(obj, name) if not callable(method): raise TypeError( "Cannot decorate '%s' as it isn't a callable attribute of " "%s (%s)." % (name, obj, method) ) _wrapper = _multi_decorate(decorator, method) setattr(obj, name, _wrapper) return obj # Don't worry about making _dec look similar to a list/tuple as it's rather # meaningless. if not hasattr(decorator, "__iter__"): update_wrapper(_dec, decorator) # Change the name to aid debugging. obj = decorator if hasattr(decorator, "__name__") else decorator.__class__ _dec.__name__ = "method_decorator(%s)" % obj.__name__ return _dec def decorator_from_middleware_with_args(middleware_class): """ Like decorator_from_middleware, but return a function that accepts the arguments to be passed to the middleware_class. Use like:: cache_page = decorator_from_middleware_with_args(CacheMiddleware) # ... @cache_page(3600) def my_view(request): # ... """ return make_middleware_decorator(middleware_class) def decorator_from_middleware(middleware_class): """ Given a middleware class (not an instance), return a view decorator. This lets you use middleware functionality on a per-view basis. The middleware is created with no params passed. """ return make_middleware_decorator(middleware_class)() def make_middleware_decorator(middleware_class): def _make_decorator(*m_args, **m_kwargs): def _decorator(view_func): middleware = middleware_class(view_func, *m_args, **m_kwargs) def _pre_process_request(request, *args, **kwargs): if hasattr(middleware, "process_request"): result = middleware.process_request(request) if result is not None: return result if hasattr(middleware, "process_view"): result = middleware.process_view(request, view_func, args, kwargs) if result is not None: return result return None def _process_exception(request, exception): if hasattr(middleware, "process_exception"): result = middleware.process_exception(request, exception) if result is not None: return result raise def _post_process_request(request, response): if hasattr(response, "render") and callable(response.render): if hasattr(middleware, "process_template_response"): response = middleware.process_template_response( request, response ) # Defer running of process_response until after the # template has been rendered: if hasattr(middleware, "process_response"): def callback(response): return middleware.process_response(request, response) response.add_post_render_callback(callback) else: if hasattr(middleware, "process_response"): return middleware.process_response(request, response) return response if iscoroutinefunction(view_func): async def _view_wrapper(request, *args, **kwargs): result = _pre_process_request(request, *args, **kwargs) if result is not None: return result try: response = await view_func(request, *args, **kwargs) except Exception as e: result = _process_exception(request, e) if result is not None: return result return _post_process_request(request, response) else: def _view_wrapper(request, *args, **kwargs): result = _pre_process_request(request, *args, **kwargs) if result is not None: return result try: response = view_func(request, *args, **kwargs) except Exception as e: result = _process_exception(request, e) if result is not None: return result return _post_process_request(request, response) return wraps(view_func)(_view_wrapper) return _decorator return _make_decorator def sync_and_async_middleware(func): """ Mark a middleware factory as returning a hybrid middleware supporting both types of request. """ func.sync_capable = True func.async_capable = True return func def sync_only_middleware(func): """ Mark a middleware factory as returning a sync middleware. This is the default. """ func.sync_capable = True func.async_capable = False return func def async_only_middleware(func): """Mark a middleware factory as returning an async middleware.""" func.sync_capable = False func.async_capable = True return func
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/deprecation.py
django/utils/deprecation.py
import functools import inspect import os import warnings from collections import Counter from asgiref.sync import iscoroutinefunction, markcoroutinefunction, sync_to_async import django @functools.cache def django_file_prefixes(): try: file = django.__file__ except AttributeError: return () return (os.path.dirname(file),) class RemovedInNextVersionWarning(DeprecationWarning): pass class RemovedInDjango70Warning(PendingDeprecationWarning): pass RemovedAfterNextVersionWarning = RemovedInDjango70Warning class warn_about_renamed_method: def __init__( self, class_name, old_method_name, new_method_name, deprecation_warning ): self.class_name = class_name self.old_method_name = old_method_name self.new_method_name = new_method_name self.deprecation_warning = deprecation_warning def __call__(self, f): def wrapper(*args, **kwargs): warnings.warn( "`%s.%s` is deprecated, use `%s` instead." % (self.class_name, self.old_method_name, self.new_method_name), self.deprecation_warning, 2, ) return f(*args, **kwargs) return wrapper class RenameMethodsBase(type): """ Handles the deprecation paths when renaming a method. It does the following: 1) Define the new method if missing and complain about it. 2) Define the old method if missing. 3) Complain whenever an old method is called. See #15363 for more details. """ renamed_methods = () def __new__(cls, name, bases, attrs): new_class = super().__new__(cls, name, bases, attrs) for base in inspect.getmro(new_class): class_name = base.__name__ for renamed_method in cls.renamed_methods: old_method_name = renamed_method[0] old_method = base.__dict__.get(old_method_name) new_method_name = renamed_method[1] new_method = base.__dict__.get(new_method_name) deprecation_warning = renamed_method[2] wrapper = warn_about_renamed_method(class_name, *renamed_method) # Define the new method if missing and complain about it if not new_method and old_method: warnings.warn( "`%s.%s` method should be renamed `%s`." % (class_name, old_method_name, new_method_name), deprecation_warning, 2, ) setattr(base, new_method_name, old_method) setattr(base, old_method_name, wrapper(old_method)) # Define the old method as a wrapped call to the new method. if not old_method and new_method: setattr(base, old_method_name, wrapper(new_method)) return new_class def deprecate_posargs(deprecation_warning, remappable_names, /): """ Function/method decorator to deprecate some or all positional arguments. The decorated function will map any positional arguments after the ``*`` to the corresponding keyword arguments and issue a deprecation warning. The decorator takes two arguments: a RemovedInDjangoXXWarning warning category and a list of parameter names that have been changed from positional-or-keyword to keyword-only, in their original positional order. Works on both functions and methods. To apply to a class constructor, decorate its __init__() method. To apply to a staticmethod or classmethod, use @deprecate_posargs after @staticmethod or @classmethod. Example: to deprecate passing option1 or option2 as posargs, change:: def some_func(request, option1, option2=True): ... to:: @deprecate_posargs(RemovedInDjangoXXWarning, ["option1", "option2"]) def some_func(request, *, option1, option2=True): ... After the deprecation period, remove the decorator (but keep the ``*``):: def some_func(request, *, option1, option2=True): ... Caution: during the deprecation period, do not add any new *positional* parameters or change the remaining ones. For example, this attempt to add a new param would break code using the deprecated posargs:: @deprecate_posargs(RemovedInDjangoXXWarning, ["option1", "option2"]) def some_func(request, wrong_new_param=None, *, option1, option2=True): # Broken: existing code may pass a value intended as option1 in the # wrong_new_param position. ... However, it's acceptable to add new *keyword-only* parameters and to re-order the existing ones, so long as the list passed to @deprecate_posargs is kept in the original posargs order. This change will work without breaking existing code:: @deprecate_posargs(RemovedInDjangoXXWarning, ["option1", "option2"]) def some_func(request, *, new_param=None, option2=True, option1): ... The @deprecate_posargs decorator adds a small amount of overhead. In most cases it won't be significant, but use with care in performance-critical code paths. """ def decorator(func): if isinstance(func, type): raise TypeError( "@deprecate_posargs cannot be applied to a class. (Apply it " "to the __init__ method.)" ) if isinstance(func, classmethod): raise TypeError("Apply @classmethod before @deprecate_posargs.") if isinstance(func, staticmethod): raise TypeError("Apply @staticmethod before @deprecate_posargs.") params = inspect.signature(func).parameters num_by_kind = Counter(param.kind for param in params.values()) if num_by_kind[inspect.Parameter.VAR_POSITIONAL] > 0: raise TypeError( "@deprecate_posargs() cannot be used with variable positional `*args`." ) num_positional_params = ( num_by_kind[inspect.Parameter.POSITIONAL_ONLY] + num_by_kind[inspect.Parameter.POSITIONAL_OR_KEYWORD] ) num_keyword_only_params = num_by_kind[inspect.Parameter.KEYWORD_ONLY] if num_keyword_only_params < 1: raise TypeError( "@deprecate_posargs() requires at least one keyword-only parameter " "(after a `*` entry in the parameters list)." ) if any( name not in params or params[name].kind != inspect.Parameter.KEYWORD_ONLY for name in remappable_names ): raise TypeError( "@deprecate_posargs() requires all remappable_names to be " "keyword-only parameters." ) num_remappable_args = len(remappable_names) max_positional_args = num_positional_params + num_remappable_args func_name = func.__name__ if func_name == "__init__": # In the warning, show "ClassName()" instead of "__init__()". # The class isn't defined yet, but its name is in __qualname__. # Some examples of __qualname__: # - ClassName.__init__ # - Nested.ClassName.__init__ # - MyTests.test_case.<locals>.ClassName.__init__ local_name = func.__qualname__.rsplit("<locals>.", 1)[-1] class_name = local_name.replace(".__init__", "") func_name = class_name def remap_deprecated_args(args, kwargs): """ Move deprecated positional args to kwargs and issue a warning. Return updated (args, kwargs). """ if (num_positional_args := len(args)) > max_positional_args: raise TypeError( f"{func_name}() takes at most {max_positional_args} positional " f"argument(s) (including {num_remappable_args} deprecated) but " f"{num_positional_args} were given." ) # Identify which of the _potentially remappable_ params are # actually _being remapped_ in this particular call. remapped_names = remappable_names[ : num_positional_args - num_positional_params ] conflicts = set(remapped_names) & set(kwargs) if conflicts: # Report duplicate names in the original parameter order. conflicts_str = ", ".join( f"'{name}'" for name in remapped_names if name in conflicts ) raise TypeError( f"{func_name}() got both deprecated positional and keyword " f"argument values for {conflicts_str}." ) # Do the remapping. remapped_kwargs = dict( zip(remapped_names, args[num_positional_params:], strict=True) ) remaining_args = args[:num_positional_params] updated_kwargs = kwargs | remapped_kwargs # Issue the deprecation warning. remapped_names_str = ", ".join(f"'{name}'" for name in remapped_names) warnings.warn( f"Passing positional argument(s) {remapped_names_str} to {func_name}() " "is deprecated. Use keyword arguments instead.", deprecation_warning, skip_file_prefixes=django_file_prefixes(), ) return remaining_args, updated_kwargs if iscoroutinefunction(func): @functools.wraps(func) async def wrapper(*args, **kwargs): if len(args) > num_positional_params: args, kwargs = remap_deprecated_args(args, kwargs) return await func(*args, **kwargs) else: @functools.wraps(func) def wrapper(*args, **kwargs): if len(args) > num_positional_params: args, kwargs = remap_deprecated_args(args, kwargs) return func(*args, **kwargs) return wrapper return decorator class MiddlewareMixin: sync_capable = True async_capable = True def __init__(self, get_response): if get_response is None: raise ValueError("get_response must be provided.") self.get_response = get_response # If get_response is a coroutine function, turns us into async mode so # a thread is not consumed during a whole request. self.async_mode = iscoroutinefunction(self.get_response) if self.async_mode: # Mark the class as async-capable, but do the actual switch inside # __call__ to avoid swapping out dunder methods. markcoroutinefunction(self) super().__init__() def __repr__(self): return "<%s get_response=%s>" % ( self.__class__.__qualname__, getattr( self.get_response, "__qualname__", self.get_response.__class__.__name__, ), ) def __call__(self, request): # Exit out to async mode, if needed if self.async_mode: return self.__acall__(request) response = None if hasattr(self, "process_request"): response = self.process_request(request) response = response or self.get_response(request) if hasattr(self, "process_response"): response = self.process_response(request, response) return response async def __acall__(self, request): """ Async version of __call__ that is swapped in when an async request is running. """ response = None if hasattr(self, "process_request"): response = await sync_to_async( self.process_request, thread_sensitive=True, )(request) response = response or await self.get_response(request) if hasattr(self, "process_response"): response = await sync_to_async( self.process_response, thread_sensitive=True, )(request, response) return response
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/log.py
django/utils/log.py
import logging import logging.config # needed when logging_config doesn't start with logging.config from copy import copy from django.conf import settings from django.core import mail from django.core.mail import get_connection from django.core.management.color import color_style from django.utils.module_loading import import_string request_logger = logging.getLogger("django.request") # Default logging for Django. This sends an email to the site admins on every # HTTP 500 error. Depending on DEBUG, all other log records are either sent to # the console (DEBUG=True) or discarded (DEBUG=False) by means of the # require_debug_true filter. This configuration is quoted in # docs/ref/logging.txt; please amend it there if edited here. DEFAULT_LOGGING = { "version": 1, "disable_existing_loggers": False, "filters": { "require_debug_false": { "()": "django.utils.log.RequireDebugFalse", }, "require_debug_true": { "()": "django.utils.log.RequireDebugTrue", }, }, "formatters": { "django.server": { "()": "django.utils.log.ServerFormatter", "format": "[{server_time}] {message}", "style": "{", } }, "handlers": { "console": { "level": "INFO", "filters": ["require_debug_true"], "class": "logging.StreamHandler", }, "django.server": { "level": "INFO", "class": "logging.StreamHandler", "formatter": "django.server", }, "mail_admins": { "level": "ERROR", "filters": ["require_debug_false"], "class": "django.utils.log.AdminEmailHandler", }, }, "loggers": { "django": { "handlers": ["console", "mail_admins"], "level": "INFO", }, "django.server": { "handlers": ["django.server"], "level": "INFO", "propagate": False, }, }, } def configure_logging(logging_config, logging_settings): if logging_config: # First find the logging configuration function ... logging_config_func = import_string(logging_config) logging.config.dictConfig(DEFAULT_LOGGING) # ... then invoke it with the logging settings if logging_settings: logging_config_func(logging_settings) class AdminEmailHandler(logging.Handler): """An exception log handler that emails log entries to site admins. If the request is passed as the first argument to the log record, request data will be provided in the email report. """ def __init__(self, include_html=False, email_backend=None, reporter_class=None): super().__init__() self.include_html = include_html self.email_backend = email_backend self.reporter_class = import_string( reporter_class or settings.DEFAULT_EXCEPTION_REPORTER ) def emit(self, record): # Early return when no email will be sent. if ( not settings.ADMINS # Method not overridden. and self.send_mail.__func__ is AdminEmailHandler.send_mail ): return try: request = record.request subject = "%s (%s IP): %s" % ( record.levelname, ( "internal" if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS else "EXTERNAL" ), record.getMessage(), ) except Exception: subject = "%s: %s" % (record.levelname, record.getMessage()) request = None subject = self.format_subject(subject) # Since we add a nicely formatted traceback on our own, create a copy # of the log record without the exception data. no_exc_record = copy(record) no_exc_record.exc_info = None no_exc_record.exc_text = None if record.exc_info: exc_info = record.exc_info else: exc_info = (None, record.getMessage(), None) reporter = self.reporter_class(request, is_email=True, *exc_info) message = "%s\n\n%s" % ( self.format(no_exc_record), reporter.get_traceback_text(), ) html_message = reporter.get_traceback_html() if self.include_html else None self.send_mail(subject, message, fail_silently=True, html_message=html_message) def send_mail(self, subject, message, *args, **kwargs): mail.mail_admins( subject, message, *args, connection=self.connection(), **kwargs ) def connection(self): return get_connection(backend=self.email_backend, fail_silently=True) def format_subject(self, subject): """ Escape CR and LF characters. """ return subject.replace("\n", "\\n").replace("\r", "\\r") class CallbackFilter(logging.Filter): """ A logging filter that checks the return value of a given callable (which takes the record-to-be-logged as its only parameter) to decide whether to log a record. """ def __init__(self, callback): self.callback = callback def filter(self, record): if self.callback(record): return 1 return 0 class RequireDebugFalse(logging.Filter): def filter(self, record): return not settings.DEBUG class RequireDebugTrue(logging.Filter): def filter(self, record): return settings.DEBUG class ServerFormatter(logging.Formatter): default_time_format = "%d/%b/%Y %H:%M:%S" def __init__(self, *args, **kwargs): self.style = color_style() super().__init__(*args, **kwargs) def format(self, record): msg = record.msg status_code = getattr(record, "status_code", None) if status_code: if 200 <= status_code < 300: # Put 2XX first, since it should be the common case msg = self.style.HTTP_SUCCESS(msg) elif 100 <= status_code < 200: msg = self.style.HTTP_INFO(msg) elif status_code == 304: msg = self.style.HTTP_NOT_MODIFIED(msg) elif 300 <= status_code < 400: msg = self.style.HTTP_REDIRECT(msg) elif status_code == 404: msg = self.style.HTTP_NOT_FOUND(msg) elif 400 <= status_code < 500: msg = self.style.HTTP_BAD_REQUEST(msg) else: # Any 5XX, or any other status code msg = self.style.HTTP_SERVER_ERROR(msg) if self.uses_server_time() and not hasattr(record, "server_time"): record.server_time = self.formatTime(record, self.datefmt) record.msg = msg return super().format(record) def uses_server_time(self): return self._fmt.find("{server_time}") >= 0 def log_message( logger, message, *args, level=None, status_code=None, request=None, exception=None, **extra, ): """Log `message` using `logger` based on `status_code` and logger `level`. Pass `request`, `status_code` (if defined) and any provided `extra` as such to the logging method, Arguments from `args` will be escaped to avoid potential log injections. """ extra = {"request": request, **extra} if status_code is not None: extra["status_code"] = status_code if level is None: if status_code >= 500: level = "error" elif status_code >= 400: level = "warning" escaped_args = tuple( a.encode("unicode_escape").decode("ascii") if isinstance(a, str) else a for a in args ) getattr(logger, level or "info")( message, *escaped_args, extra=extra, exc_info=exception, ) def log_response( message, *args, response=None, request=None, logger=request_logger, level=None, exception=None, ): """ Log errors based on HttpResponse status. Log 5xx responses as errors and 4xx responses as warnings (unless a level is given as a keyword argument). The HttpResponse status_code and the request are passed to the logger's extra parameter. """ # Check if the response has already been logged. Multiple requests to log # the same response can be received in some cases, e.g., when the # response is the result of an exception and is logged when the exception # is caught, to record the exception. if getattr(response, "_has_been_logged", False): return log_message( logger, message, *args, level=level, status_code=response.status_code, request=request, exception=exception, ) response._has_been_logged = True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/choices.py
django/utils/choices.py
from collections.abc import Callable, Iterable, Iterator, Mapping from itertools import islice, tee, zip_longest from django.utils.functional import Promise __all__ = [ "BaseChoiceIterator", "BlankChoiceIterator", "CallableChoiceIterator", "flatten_choices", "normalize_choices", ] class BaseChoiceIterator: """Base class for lazy iterators for choices.""" def __eq__(self, other): if isinstance(other, Iterable): return all(a == b for a, b in zip_longest(self, other, fillvalue=object())) return super().__eq__(other) def __getitem__(self, index): if isinstance(index, slice) or index < 0: # Suboptimally consume whole iterator to handle slices and negative # indexes. return list(self)[index] try: return next(islice(self, index, index + 1)) except StopIteration: raise IndexError("index out of range") from None def __iter__(self): raise NotImplementedError( "BaseChoiceIterator subclasses must implement __iter__()." ) class BlankChoiceIterator(BaseChoiceIterator): """Iterator to lazily inject a blank choice.""" def __init__(self, choices, blank_choice): self.choices = choices self.blank_choice = blank_choice def __iter__(self): choices, other = tee(self.choices) if not any(value in ("", None) for value, _ in flatten_choices(other)): yield from self.blank_choice yield from choices class CallableChoiceIterator(BaseChoiceIterator): """Iterator to lazily normalize choices generated by a callable.""" def __init__(self, func): self.func = func def __iter__(self): yield from normalize_choices(self.func()) def flatten_choices(choices): """Flatten choices by removing nested values.""" for value_or_group, label_or_nested in choices or (): if isinstance(label_or_nested, (list, tuple)): yield from label_or_nested else: yield value_or_group, label_or_nested def normalize_choices(value, *, depth=0): """Normalize choices values consistently for fields and widgets.""" # Avoid circular import when importing django.forms. from django.db.models.enums import ChoicesType match value: case BaseChoiceIterator() | Promise() | bytes() | str(): # Avoid prematurely normalizing iterators that should be lazy. # Because string-like types are iterable, return early to avoid # iterating over them in the guard for the Iterable case below. return value case ChoicesType(): # Choices enumeration helpers already output in canonical form. return value.choices case Mapping() if depth < 2: value = value.items() case Iterator() if depth < 2: # Although Iterator would be handled by the Iterable case below, # the iterator would be consumed prematurely while checking that # its elements are not string-like in the guard, so we handle it # separately. pass case Iterable() if depth < 2 and not any( isinstance(x, (Promise, bytes, str)) for x in value ): # String-like types are iterable, so the guard above ensures that # they're handled by the default case below. pass case Callable() if depth == 0: # If at the top level, wrap callables to be evaluated lazily. return CallableChoiceIterator(value) case Callable() if depth < 2: value = value() case _: return value try: # Recursive call to convert any nested values to a list of 2-tuples. return [(k, normalize_choices(v, depth=depth + 1)) for k, v in value] except (TypeError, ValueError): # Return original value for the system check to raise if it has items # that are not iterable or not 2-tuples: # - TypeError: cannot unpack non-iterable <type> object # - ValueError: <not enough / too many> values to unpack return value
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/inspect.py
django/utils/inspect.py
import functools import inspect import threading from contextlib import contextmanager from django.utils.version import PY314 if PY314: import annotationlib lock = threading.Lock() safe_signature_from_callable = functools.partial( inspect._signature_from_callable, annotation_format=annotationlib.Format.FORWARDREF, ) @functools.lru_cache(maxsize=512) def _get_func_parameters(func, remove_first): # As the annotations are not used in any case, inspect the signature with # FORWARDREF to leave any deferred annotations unevaluated. if PY314: signature = inspect.signature( func, annotation_format=annotationlib.Format.FORWARDREF ) else: signature = inspect.signature(func) parameters = tuple(signature.parameters.values()) if remove_first: parameters = parameters[1:] return parameters def _get_callable_parameters(meth_or_func): is_method = inspect.ismethod(meth_or_func) func = meth_or_func.__func__ if is_method else meth_or_func return _get_func_parameters(func, remove_first=is_method) ARG_KINDS = frozenset( { inspect.Parameter.POSITIONAL_ONLY, inspect.Parameter.KEYWORD_ONLY, inspect.Parameter.POSITIONAL_OR_KEYWORD, } ) def get_func_args(func): params = _get_callable_parameters(func) return [param.name for param in params if param.kind in ARG_KINDS] def get_func_full_args(func): """ Return a list of (argument name, default value) tuples. If the argument does not have a default value, omit it in the tuple. Arguments such as *args and **kwargs are also included. """ params = _get_callable_parameters(func) args = [] for param in params: name = param.name # Ignore 'self' if name == "self": continue if param.kind == inspect.Parameter.VAR_POSITIONAL: name = "*" + name elif param.kind == inspect.Parameter.VAR_KEYWORD: name = "**" + name if param.default != inspect.Parameter.empty: args.append((name, param.default)) else: args.append((name,)) return args def func_accepts_kwargs(func): """Return True if function 'func' accepts keyword arguments **kwargs.""" return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_KEYWORD) def func_accepts_var_args(func): """ Return True if function 'func' accepts positional arguments *args. """ return any(p for p in _get_callable_parameters(func) if p.kind == p.VAR_POSITIONAL) def method_has_no_args(meth): """Return True if a method only accepts 'self'.""" count = len([p for p in _get_callable_parameters(meth) if p.kind in ARG_KINDS]) return count == 0 if inspect.ismethod(meth) else count == 1 def func_supports_parameter(func, name): return any(param.name == name for param in _get_callable_parameters(func)) def is_module_level_function(func): if not inspect.isfunction(func) or inspect.isbuiltin(func): return False if "<locals>" in func.__qualname__: return False return True @contextmanager def lazy_annotations(): """ inspect.getfullargspec eagerly evaluates type annotations. To add compatibility with Python 3.14+ deferred evaluation, patch the module-level helper to provide the annotation_format that we are using elsewhere. This private helper could be removed when there is an upstream solution for https://github.com/python/cpython/issues/141560. This context manager is not reentrant. """ if not PY314: yield return with lock: original_helper = inspect._signature_from_callable inspect._signature_from_callable = safe_signature_from_callable try: yield finally: inspect._signature_from_callable = original_helper
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/xmlutils.py
django/utils/xmlutils.py
""" Utilities for XML generation/parsing. """ import re from xml.sax.saxutils import XMLGenerator class UnserializableContentError(ValueError): pass class SimplerXMLGenerator(XMLGenerator): def addQuickElement(self, name, contents=None, attrs=None): "Convenience method for adding an element with no children" if attrs is None: attrs = {} self.startElement(name, attrs) if contents is not None: self.characters(contents) self.endElement(name) def characters(self, content): if content and re.search(r"[\x00-\x08\x0B-\x0C\x0E-\x1F]", content): # Fail loudly when content has control chars (unsupported in XML # 1.0) See https://www.w3.org/International/questions/qa-controls raise UnserializableContentError( "Control characters are not supported in XML 1.0" ) XMLGenerator.characters(self, content) def startElement(self, name, attrs): # Sort attrs for a deterministic output. sorted_attrs = dict(sorted(attrs.items())) if attrs else attrs super().startElement(name, sorted_attrs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/autoreload.py
django/utils/autoreload.py
import itertools import logging import os import signal import subprocess import sys import threading import time import traceback import weakref from collections import defaultdict from functools import lru_cache, wraps from pathlib import Path from types import ModuleType from zipimport import zipimporter import django from django.apps import apps from django.core.signals import request_finished from django.dispatch import Signal from django.utils.functional import cached_property from django.utils.version import get_version_tuple autoreload_started = Signal() file_changed = Signal() DJANGO_AUTORELOAD_ENV = "RUN_MAIN" logger = logging.getLogger("django.utils.autoreload") # If an error is raised while importing a file, it's not placed in sys.modules. # This means that any future modifications aren't caught. Keep a list of these # file paths to allow watching them in the future. _error_files = [] _exception = None try: import termios except ImportError: termios = None try: import pywatchman except ImportError: pywatchman = None def is_django_module(module): """Return True if the given module is nested under Django.""" return module.__name__.startswith("django.") def is_django_path(path): """Return True if the given file path is nested under Django.""" return Path(django.__file__).parent in Path(path).parents def check_errors(fn): @wraps(fn) def wrapper(*args, **kwargs): global _exception try: fn(*args, **kwargs) except Exception: _exception = sys.exc_info() et, ev, tb = _exception if getattr(ev, "filename", None) is None: # get the filename from the last item in the stack filename = traceback.extract_tb(tb)[-1][0] else: filename = ev.filename if filename not in _error_files: _error_files.append(filename) raise return wrapper def raise_last_exception(): if _exception is not None: raise _exception[1] def ensure_echo_on(): """ Ensure that echo mode is enabled. Some tools such as PDB disable it which causes usability issues after reload. """ if not termios or not sys.stdin.isatty(): return attr_list = termios.tcgetattr(sys.stdin) if not attr_list[3] & termios.ECHO: attr_list[3] |= termios.ECHO if hasattr(signal, "SIGTTOU"): old_handler = signal.signal(signal.SIGTTOU, signal.SIG_IGN) else: old_handler = None termios.tcsetattr(sys.stdin, termios.TCSANOW, attr_list) if old_handler is not None: signal.signal(signal.SIGTTOU, old_handler) def iter_all_python_module_files(): # This is a hot path during reloading. Create a stable sorted list of # modules based on the module name and pass it to iter_modules_and_files(). # This ensures cached results are returned in the usual case that modules # aren't loaded on the fly. keys = sorted(sys.modules) modules = tuple( m for m in map(sys.modules.__getitem__, keys) if not isinstance(m, weakref.ProxyTypes) ) return iter_modules_and_files(modules, frozenset(_error_files)) @lru_cache(maxsize=1) def iter_modules_and_files(modules, extra_files): """Iterate through all modules needed to be watched.""" sys_file_paths = [] for module in modules: # During debugging (with PyDev) the 'typing.io' and 'typing.re' objects # are added to sys.modules, however they are types not modules and so # cause issues here. if not isinstance(module, ModuleType): continue if module.__name__ in ("__main__", "__mp_main__"): # __main__ (usually manage.py) doesn't always have a __spec__ set. # Handle this by falling back to using __file__, resolved below. # See https://docs.python.org/reference/import.html#main-spec # __file__ may not exists, e.g. when running ipdb debugger. if hasattr(module, "__file__"): sys_file_paths.append(module.__file__) continue if getattr(module, "__spec__", None) is None: continue spec = module.__spec__ # Modules could be loaded from places without a concrete location. If # this is the case, skip them. if spec.has_location: origin = ( spec.loader.archive if isinstance(spec.loader, zipimporter) else spec.origin ) sys_file_paths.append(origin) results = set() for filename in itertools.chain(sys_file_paths, extra_files): if not filename: continue path = Path(filename) try: if not path.exists(): # The module could have been removed, don't fail loudly if this # is the case. continue except ValueError as e: # Network filesystems may return null bytes in file paths. logger.debug('"%s" raised when resolving path: "%s"', e, path) continue resolved_path = path.resolve().absolute() results.add(resolved_path) return frozenset(results) @lru_cache(maxsize=1) def common_roots(paths): """ Return a tuple of common roots that are shared between the given paths. File system watchers operate on directories and aren't cheap to create. Try to find the minimum set of directories to watch that encompass all of the files that need to be watched. """ # Inspired from Werkzeug: # https://github.com/pallets/werkzeug/blob/7477be2853df70a022d9613e765581b9411c3c39/werkzeug/_reloader.py # Create a sorted list of the path components, longest first. path_parts = sorted([x.parts for x in paths], key=len, reverse=True) tree = {} for chunks in path_parts: node = tree # Add each part of the path to the tree. for chunk in chunks: node = node.setdefault(chunk, {}) # Clear the last leaf in the tree. node.clear() # Turn the tree into a list of Path instances. def _walk(node, path): for prefix, child in node.items(): yield from _walk(child, [*path, prefix]) if not node: yield Path(*path) return tuple(_walk(tree, ())) def sys_path_directories(): """ Yield absolute directories from sys.path, ignoring entries that don't exist. """ for path in sys.path: path = Path(path) if not path.exists(): continue resolved_path = path.resolve().absolute() # If the path is a file (like a zip file), watch the parent directory. if resolved_path.is_file(): yield resolved_path.parent else: yield resolved_path def get_child_arguments(): """ Return the executable. This contains a workaround for Windows if the executable is reported to not have the .exe extension which can cause bugs on reloading. """ import __main__ py_script = Path(sys.argv[0]) exe_entrypoint = py_script.with_suffix(".exe") args = [sys.executable] + ["-W%s" % o for o in sys.warnoptions] if sys.implementation.name in ("cpython", "pypy"): args.extend( f"-X{key}" if value is True else f"-X{key}={value}" for key, value in sys._xoptions.items() ) # __spec__ is set when the server was started with the `-m` option, # see https://docs.python.org/3/reference/import.html#main-spec # __spec__ may not exist, e.g. when running in a Conda env. if getattr(__main__, "__spec__", None) is not None and not exe_entrypoint.exists(): spec = __main__.__spec__ if (spec.name == "__main__" or spec.name.endswith(".__main__")) and spec.parent: name = spec.parent else: name = spec.name args += ["-m", name] args += sys.argv[1:] elif not py_script.exists(): # sys.argv[0] may not exist for several reasons on Windows. # It may exist with a .exe extension or have a -script.py suffix. if exe_entrypoint.exists(): # Should be executed directly, ignoring sys.executable. return [exe_entrypoint, *sys.argv[1:]] script_entrypoint = py_script.with_name("%s-script.py" % py_script.name) if script_entrypoint.exists(): # Should be executed as usual. return [*args, script_entrypoint, *sys.argv[1:]] raise RuntimeError("Script %s does not exist." % py_script) else: args += sys.argv return args def trigger_reload(filename): logger.info("%s changed, reloading.", filename) sys.exit(3) def restart_with_reloader(): new_environ = {**os.environ, DJANGO_AUTORELOAD_ENV: "true"} orig = getattr(sys, "orig_argv", ()) if any( (arg == "-u") or ( arg.startswith("-") and not arg.startswith(("--", "-X", "-W")) and len(arg) > 2 and arg[1:].isalpha() and "u" in arg ) for arg in orig[1:] ): new_environ.setdefault("PYTHONUNBUFFERED", "1") args = get_child_arguments() while True: p = subprocess.run(args, env=new_environ, close_fds=False) if p.returncode != 3: return p.returncode class BaseReloader: def __init__(self): self.extra_files = set() self.directory_globs = defaultdict(set) self._stop_condition = threading.Event() def watch_dir(self, path, glob): path = Path(path) try: path = path.absolute() except FileNotFoundError: logger.debug( "Unable to watch directory %s as it cannot be resolved.", path, exc_info=True, ) return logger.debug("Watching dir %s with glob %s.", path, glob) self.directory_globs[path].add(glob) def watched_files(self, include_globs=True): """ Yield all files that need to be watched, including module files and files within globs. """ yield from iter_all_python_module_files() yield from self.extra_files if include_globs: for directory, patterns in self.directory_globs.items(): for pattern in patterns: yield from directory.glob(pattern) def wait_for_apps_ready(self, app_reg, django_main_thread): """ Wait until Django reports that the apps have been loaded. If the given thread has terminated before the apps are ready, then a SyntaxError or other non-recoverable error has been raised. In that case, stop waiting for the apps_ready event and continue processing. Return True if the thread is alive and the ready event has been triggered, or False if the thread is terminated while waiting for the event. """ while django_main_thread.is_alive(): if app_reg.ready_event.wait(timeout=0.1): return True else: logger.debug("Main Django thread has terminated before apps are ready.") return False def run(self, django_main_thread): logger.debug("Waiting for apps ready_event.") self.wait_for_apps_ready(apps, django_main_thread) from django.urls import get_resolver # Prevent a race condition where URL modules aren't loaded when the # reloader starts by accessing the urlconf_module property. try: get_resolver().urlconf_module except Exception: # Loading the urlconf can result in errors during development. # If this occurs then swallow the error and continue. pass logger.debug("Apps ready_event triggered. Sending autoreload_started signal.") autoreload_started.send(sender=self) self.run_loop() def run_loop(self): ticker = self.tick() while not self.should_stop: try: next(ticker) except StopIteration: break self.stop() def tick(self): """ This generator is called in a loop from run_loop. It's important that the method takes care of pausing or otherwise waiting for a period of time. This split between run_loop() and tick() is to improve the testability of the reloader implementations by decoupling the work they do from the loop. """ raise NotImplementedError("subclasses must implement tick().") @classmethod def check_availability(cls): raise NotImplementedError("subclasses must implement check_availability().") def notify_file_changed(self, path): results = file_changed.send(sender=self, file_path=path) logger.debug("%s notified as changed. Signal results: %s.", path, results) if not any(res[1] for res in results): trigger_reload(path) # These are primarily used for testing. @property def should_stop(self): return self._stop_condition.is_set() def stop(self): self._stop_condition.set() class StatReloader(BaseReloader): SLEEP_TIME = 1 # Check for changes once per second. def tick(self): mtimes = {} while True: for filepath, mtime in self.snapshot_files(): old_time = mtimes.get(filepath) mtimes[filepath] = mtime if old_time is None: logger.debug("File %s first seen with mtime %s", filepath, mtime) continue elif mtime > old_time: logger.debug( "File %s previous mtime: %s, current mtime: %s", filepath, old_time, mtime, ) self.notify_file_changed(filepath) time.sleep(self.SLEEP_TIME) yield def snapshot_files(self): # watched_files may produce duplicate paths if globs overlap. seen_files = set() for file in self.watched_files(): if file in seen_files: continue try: mtime = file.stat().st_mtime except OSError: # This is thrown when the file does not exist. continue seen_files.add(file) yield file, mtime @classmethod def check_availability(cls): return True class WatchmanUnavailable(RuntimeError): pass class WatchmanReloader(BaseReloader): def __init__(self): self.roots = defaultdict(set) self.processed_request = threading.Event() self.client_timeout = int(os.environ.get("DJANGO_WATCHMAN_TIMEOUT", 5)) super().__init__() @cached_property def client(self): return pywatchman.client(timeout=self.client_timeout) def _watch_root(self, root): # In practice this shouldn't occur, however, it's possible that a # directory that doesn't exist yet is being watched. If it's outside of # sys.path then this will end up a new root. How to handle this isn't # clear: Not adding the root will likely break when subscribing to the # changes, however, as this is currently an internal API, no files # will be being watched outside of sys.path. Fixing this by checking # inside watch_glob() and watch_dir() is expensive, instead this could # could fall back to the StatReloader if this case is detected? For # now, watching its parent, if possible, is sufficient. if not root.exists(): if not root.parent.exists(): logger.warning( "Unable to watch root dir %s as neither it or its parent exist.", root, ) return root = root.parent result = self.client.query("watch-project", str(root.absolute())) if "warning" in result: logger.warning("Watchman warning: %s", result["warning"]) logger.debug("Watchman watch-project result: %s", result) return result["watch"], result.get("relative_path") @lru_cache def _get_clock(self, root): return self.client.query("clock", root)["clock"] def _subscribe(self, directory, name, expression): root, rel_path = self._watch_root(directory) # Only receive notifications of files changing, filtering out other # types like special files: # https://facebook.github.io/watchman/docs/type only_files_expression = [ "allof", ["anyof", ["type", "f"], ["type", "l"]], expression, ] query = { "expression": only_files_expression, "fields": ["name"], "since": self._get_clock(root), "dedup_results": True, } if rel_path: query["relative_root"] = rel_path logger.debug( "Issuing watchman subscription %s, for root %s. Query: %s", name, root, query, ) self.client.query("subscribe", root, name, query) def _subscribe_dir(self, directory, filenames): if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "files-parent-%s" % directory.name filenames = ["%s/%s" % (directory.name, filename) for filename in filenames] directory = directory.parent expression = ["name", filenames, "wholename"] else: prefix = "files" expression = ["name", filenames] self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def _watch_glob(self, directory, patterns): """ Watch a directory with a specific glob. If the directory doesn't yet exist, attempt to watch the parent directory and amend the patterns to include this. It's important this method isn't called more than one per directory when updating all subscriptions. Subsequent calls will overwrite the named subscription, so it must include all possible glob expressions. """ prefix = "glob" if not directory.exists(): if not directory.parent.exists(): logger.warning( "Unable to watch directory %s as neither it or its parent exist.", directory, ) return prefix = "glob-parent-%s" % directory.name patterns = ["%s/%s" % (directory.name, pattern) for pattern in patterns] directory = directory.parent expression = ["anyof"] for pattern in patterns: expression.append(["match", pattern, "wholename"]) self._subscribe(directory, "%s:%s" % (prefix, directory), expression) def watched_roots(self, watched_files): extra_directories = self.directory_globs.keys() watched_file_dirs = [f.parent for f in watched_files] sys_paths = list(sys_path_directories()) return frozenset((*extra_directories, *watched_file_dirs, *sys_paths)) def _update_watches(self): watched_files = list(self.watched_files(include_globs=False)) found_roots = common_roots(self.watched_roots(watched_files)) logger.debug("Watching %s files", len(watched_files)) logger.debug("Found common roots: %s", found_roots) # Setup initial roots for performance, shortest roots first. for root in sorted(found_roots): self._watch_root(root) for directory, patterns in self.directory_globs.items(): self._watch_glob(directory, patterns) # Group sorted watched_files by their parent directory. sorted_files = sorted(watched_files, key=lambda p: p.parent) for directory, group in itertools.groupby(sorted_files, key=lambda p: p.parent): # These paths need to be relative to the parent directory. self._subscribe_dir( directory, [str(p.relative_to(directory)) for p in group] ) def update_watches(self): try: self._update_watches() except Exception as ex: # If the service is still available, raise the original exception. if self.check_server_status(ex): raise def _check_subscription(self, sub): subscription = self.client.getSubscription(sub) if not subscription: return logger.debug("Watchman subscription %s has results.", sub) for result in subscription: # When using watch-project, it's not simple to get the relative # directory without storing some specific state. Store the full # path to the directory in the subscription name, prefixed by its # type (glob, files). root_directory = Path(result["subscription"].split(":", 1)[1]) logger.debug("Found root directory %s", root_directory) for file in result.get("files", []): self.notify_file_changed(root_directory / file) def request_processed(self, **kwargs): logger.debug("Request processed. Setting update_watches event.") self.processed_request.set() def tick(self): request_finished.connect(self.request_processed) self.update_watches() while True: if self.processed_request.is_set(): self.update_watches() self.processed_request.clear() try: self.client.receive() except pywatchman.SocketTimeout: pass except pywatchman.WatchmanError as ex: logger.debug("Watchman error: %s, checking server status.", ex) self.check_server_status(ex) else: for sub in list(self.client.subs.keys()): self._check_subscription(sub) yield # Protect against busy loops. time.sleep(0.1) def stop(self): self.client.close() super().stop() def check_server_status(self, inner_ex=None): """Return True if the server is available.""" try: self.client.query("version") except Exception: raise WatchmanUnavailable(str(inner_ex)) from inner_ex return True @classmethod def check_availability(cls): if not pywatchman: raise WatchmanUnavailable("pywatchman not installed.") client = pywatchman.client(timeout=0.1) try: result = client.capabilityCheck() except Exception: # The service is down? raise WatchmanUnavailable("Cannot connect to the watchman service.") version = get_version_tuple(result["version"]) # Watchman 4.9 includes multiple improvements to watching project # directories as well as case insensitive filesystems. logger.debug("Watchman version %s", version) if version < (4, 9): raise WatchmanUnavailable("Watchman 4.9 or later is required.") def get_reloader(): """Return the most suitable reloader for this environment.""" try: WatchmanReloader.check_availability() except WatchmanUnavailable: return StatReloader() return WatchmanReloader() def start_django(reloader, main_func, *args, **kwargs): ensure_echo_on() main_func = check_errors(main_func) django_main_thread = threading.Thread( target=main_func, args=args, kwargs=kwargs, name="django-main-thread" ) django_main_thread.daemon = True django_main_thread.start() while not reloader.should_stop: reloader.run(django_main_thread) def run_with_reloader(main_func, *args, **kwargs): signal.signal(signal.SIGTERM, lambda *args: sys.exit(0)) try: if os.environ.get(DJANGO_AUTORELOAD_ENV) == "true": reloader = get_reloader() logger.info( "Watching for file changes with %s", reloader.__class__.__name__ ) start_django(reloader, main_func, *args, **kwargs) else: exit_code = restart_with_reloader() sys.exit(exit_code) except KeyboardInterrupt: pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/lorem_ipsum.py
django/utils/lorem_ipsum.py
""" Utility functions for generating "lorem ipsum" Latin text. """ import random COMMON_P = ( "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod " "tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim " "veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea " "commodo consequat. Duis aute irure dolor in reprehenderit in voluptate " "velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint " "occaecat cupidatat non proident, sunt in culpa qui officia deserunt " "mollit anim id est laborum." ) WORDS = ( "exercitationem", "perferendis", "perspiciatis", "laborum", "eveniet", "sunt", "iure", "nam", "nobis", "eum", "cum", "officiis", "excepturi", "odio", "consectetur", "quasi", "aut", "quisquam", "vel", "eligendi", "itaque", "non", "odit", "tempore", "quaerat", "dignissimos", "facilis", "neque", "nihil", "expedita", "vitae", "vero", "ipsum", "nisi", "animi", "cumque", "pariatur", "velit", "modi", "natus", "iusto", "eaque", "sequi", "illo", "sed", "ex", "et", "voluptatibus", "tempora", "veritatis", "ratione", "assumenda", "incidunt", "nostrum", "placeat", "aliquid", "fuga", "provident", "praesentium", "rem", "necessitatibus", "suscipit", "adipisci", "quidem", "possimus", "voluptas", "debitis", "sint", "accusantium", "unde", "sapiente", "voluptate", "qui", "aspernatur", "laudantium", "soluta", "amet", "quo", "aliquam", "saepe", "culpa", "libero", "ipsa", "dicta", "reiciendis", "nesciunt", "doloribus", "autem", "impedit", "minima", "maiores", "repudiandae", "ipsam", "obcaecati", "ullam", "enim", "totam", "delectus", "ducimus", "quis", "voluptates", "dolores", "molestiae", "harum", "dolorem", "quia", "voluptatem", "molestias", "magni", "distinctio", "omnis", "illum", "dolorum", "voluptatum", "ea", "quas", "quam", "corporis", "quae", "blanditiis", "atque", "deserunt", "laboriosam", "earum", "consequuntur", "hic", "cupiditate", "quibusdam", "accusamus", "ut", "rerum", "error", "minus", "eius", "ab", "ad", "nemo", "fugit", "officia", "at", "in", "id", "quos", "reprehenderit", "numquam", "iste", "fugiat", "sit", "inventore", "beatae", "repellendus", "magnam", "recusandae", "quod", "explicabo", "doloremque", "aperiam", "consequatur", "asperiores", "commodi", "optio", "dolor", "labore", "temporibus", "repellat", "veniam", "architecto", "est", "esse", "mollitia", "nulla", "a", "similique", "eos", "alias", "dolore", "tenetur", "deleniti", "porro", "facere", "maxime", "corrupti", ) COMMON_WORDS = ( "lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipisicing", "elit", "sed", "do", "eiusmod", "tempor", "incididunt", "ut", "labore", "et", "dolore", "magna", "aliqua", ) def sentence(): """ Return a randomly generated sentence of lorem ipsum text. The first word is capitalized, and the sentence ends in either a period or question mark. Commas are added at random. """ # Determine the number of comma-separated sections and number of words in # each section for this sentence. sections = [ " ".join(random.sample(WORDS, random.randint(3, 12))) for i in range(random.randint(1, 5)) ] s = ", ".join(sections) # Convert to sentence case and add end punctuation. return "%s%s%s" % (s[0].upper(), s[1:], random.choice("?.")) def paragraph(): """ Return a randomly generated paragraph of lorem ipsum text. The paragraph consists of between 1 and 4 sentences, inclusive. """ return " ".join(sentence() for i in range(random.randint(1, 4))) def paragraphs(count, common=True): """ Return a list of paragraphs as returned by paragraph(). If `common` is True, then the first paragraph will be the standard 'lorem ipsum' paragraph. Otherwise, the first paragraph will be random Latin text. Either way, subsequent paragraphs will be random Latin text. """ paras = [] for i in range(count): if common and i == 0: paras.append(COMMON_P) else: paras.append(paragraph()) return paras def words(count, common=True): """ Return a string of `count` lorem ipsum words separated by a single space. If `common` is True, then the first 19 words will be the standard 'lorem ipsum' words. Otherwise, all words will be selected randomly. """ word_list = list(COMMON_WORDS) if common else [] c = len(word_list) if count > c: count -= c while count > 0: c = min(count, len(WORDS)) count -= c word_list += random.sample(WORDS, c) else: word_list = word_list[:count] return " ".join(word_list)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/termcolors.py
django/utils/termcolors.py
""" termcolors.py """ color_names = ("black", "red", "green", "yellow", "blue", "magenta", "cyan", "white") foreground = {color_names[x]: "3%s" % x for x in range(8)} background = {color_names[x]: "4%s" % x for x in range(8)} RESET = "0" opt_dict = { "bold": "1", "underscore": "4", "blink": "5", "reverse": "7", "conceal": "8", } def colorize(text="", opts=(), **kwargs): """ Return your text, enclosed in ANSI graphics codes. Depends on the keyword arguments 'fg' and 'bg', and the contents of the opts tuple/list. Return the RESET code if no parameters are given. Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold' 'underscore' 'blink' 'reverse' 'conceal' 'noreset' - string will not be auto-terminated with the RESET code Examples: colorize('hello', fg='red', bg='blue', opts=('blink',)) colorize() colorize('goodbye', opts=('underscore',)) print(colorize('first line', fg='red', opts=('noreset',))) print('this should be red too') print(colorize('and so should this')) print('this should not be red') """ code_list = [] if text == "" and len(opts) == 1 and opts[0] == "reset": return "\x1b[%sm" % RESET for k, v in kwargs.items(): if k == "fg": code_list.append(foreground[v]) elif k == "bg": code_list.append(background[v]) for o in opts: if o in opt_dict: code_list.append(opt_dict[o]) if "noreset" not in opts: text = "%s\x1b[%sm" % (text or "", RESET) return "%s%s" % (("\x1b[%sm" % ";".join(code_list)), text or "") def make_style(opts=(), **kwargs): """ Return a function with default parameters for colorize() Example: bold_red = make_style(opts=('bold',), fg='red') print(bold_red('hello')) KEYWORD = make_style(fg='yellow') COMMENT = make_style(fg='blue', opts=('bold',)) """ return lambda text: colorize(text, opts, **kwargs) NOCOLOR_PALETTE = "nocolor" DARK_PALETTE = "dark" LIGHT_PALETTE = "light" PALETTES = { NOCOLOR_PALETTE: { "ERROR": {}, "SUCCESS": {}, "WARNING": {}, "NOTICE": {}, "SQL_FIELD": {}, "SQL_COLTYPE": {}, "SQL_KEYWORD": {}, "SQL_TABLE": {}, "HTTP_INFO": {}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {}, "HTTP_NOT_MODIFIED": {}, "HTTP_BAD_REQUEST": {}, "HTTP_NOT_FOUND": {}, "HTTP_SERVER_ERROR": {}, "MIGRATE_HEADING": {}, "MIGRATE_LABEL": {}, }, DARK_PALETTE: { "ERROR": {"fg": "red", "opts": ("bold",)}, "SUCCESS": {"fg": "green", "opts": ("bold",)}, "WARNING": {"fg": "yellow", "opts": ("bold",)}, "NOTICE": {"fg": "red"}, "SQL_FIELD": {"fg": "green", "opts": ("bold",)}, "SQL_COLTYPE": {"fg": "green"}, "SQL_KEYWORD": {"fg": "yellow"}, "SQL_TABLE": {"opts": ("bold",)}, "HTTP_INFO": {"opts": ("bold",)}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {"fg": "green"}, "HTTP_NOT_MODIFIED": {"fg": "cyan"}, "HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)}, "HTTP_NOT_FOUND": {"fg": "yellow"}, "HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)}, "MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)}, "MIGRATE_LABEL": {"opts": ("bold",)}, }, LIGHT_PALETTE: { "ERROR": {"fg": "red", "opts": ("bold",)}, "SUCCESS": {"fg": "green", "opts": ("bold",)}, "WARNING": {"fg": "yellow", "opts": ("bold",)}, "NOTICE": {"fg": "red"}, "SQL_FIELD": {"fg": "green", "opts": ("bold",)}, "SQL_COLTYPE": {"fg": "green"}, "SQL_KEYWORD": {"fg": "blue"}, "SQL_TABLE": {"opts": ("bold",)}, "HTTP_INFO": {"opts": ("bold",)}, "HTTP_SUCCESS": {}, "HTTP_REDIRECT": {"fg": "green", "opts": ("bold",)}, "HTTP_NOT_MODIFIED": {"fg": "green"}, "HTTP_BAD_REQUEST": {"fg": "red", "opts": ("bold",)}, "HTTP_NOT_FOUND": {"fg": "red"}, "HTTP_SERVER_ERROR": {"fg": "magenta", "opts": ("bold",)}, "MIGRATE_HEADING": {"fg": "cyan", "opts": ("bold",)}, "MIGRATE_LABEL": {"opts": ("bold",)}, }, } DEFAULT_PALETTE = DARK_PALETTE def parse_color_setting(config_string): """Parse a DJANGO_COLORS environment variable to produce the system palette The general form of a palette definition is: "palette;role=fg;role=fg/bg;role=fg,option,option;role=fg/bg,option,option" where: palette is a named palette; one of 'light', 'dark', or 'nocolor'. role is a named style used by Django fg is a foreground color. bg is a background color. option is a display options. Specifying a named palette is the same as manually specifying the individual definitions for each role. Any individual definitions following the palette definition will augment the base palette definition. Valid roles: 'error', 'success', 'warning', 'notice', 'sql_field', 'sql_coltype', 'sql_keyword', 'sql_table', 'http_info', 'http_success', 'http_redirect', 'http_not_modified', 'http_bad_request', 'http_not_found', 'http_server_error', 'migrate_heading', 'migrate_label' Valid colors: 'black', 'red', 'green', 'yellow', 'blue', 'magenta', 'cyan', 'white' Valid options: 'bold', 'underscore', 'blink', 'reverse', 'conceal', 'noreset' """ if not config_string: return PALETTES[DEFAULT_PALETTE] # Split the color configuration into parts parts = config_string.lower().split(";") palette = PALETTES[NOCOLOR_PALETTE].copy() for part in parts: if part in PALETTES: # A default palette has been specified palette.update(PALETTES[part]) elif "=" in part: # Process a palette defining string definition = {} # Break the definition into the role, # plus the list of specific instructions. # The role must be in upper case role, instructions = part.split("=") role = role.upper() styles = instructions.split(",") styles.reverse() # The first instruction can contain a slash # to break apart fg/bg. colors = styles.pop().split("/") colors.reverse() fg = colors.pop() if fg in color_names: definition["fg"] = fg if colors and colors[-1] in color_names: definition["bg"] = colors[-1] # All remaining instructions are options opts = tuple(s for s in styles if s in opt_dict) if opts: definition["opts"] = opts # The nocolor palette has all available roles. # Use that palette as the basis for determining # if the role is valid. if role in PALETTES[NOCOLOR_PALETTE] and definition: palette[role] = definition # If there are no colors specified, return the empty palette. if palette == PALETTES[NOCOLOR_PALETTE]: return None return palette
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/regex_helper.py
django/utils/regex_helper.py
""" Functions for reversing a regular expression (used in reverse URL resolving). Used internally by Django and not intended for external use. This is not, and is not intended to be, a complete reg-exp decompiler. It should be good enough for a large class of URLS, however. """ import re from django.utils.functional import SimpleLazyObject # Mapping of an escape character to a representative of that class. So, e.g., # "\w" is replaced by "x" in a reverse URL. A value of None means to ignore # this sequence. Any missing key is mapped to itself. ESCAPE_MAPPINGS = { "A": None, "b": None, "B": None, "d": "0", "D": "x", "s": " ", "S": "x", "w": "x", "W": "!", "Z": None, } class Choice(list): """Represent multiple possibilities at this point in a pattern string.""" class Group(list): """Represent a capturing group in the pattern string.""" class NonCapture(list): """Represent a non-capturing group in the pattern string.""" def normalize(pattern): r""" Given a reg-exp pattern, normalize it to an iterable of forms that suffice for reverse matching. This does the following: (1) For any repeating sections, keeps the minimum number of occurrences permitted (this means zero for optional groups). (2) If an optional group includes parameters, include one occurrence of that group (along with the zero occurrence case from step (1)). (3) Select the first (essentially an arbitrary) element from any character class. Select an arbitrary character for any unordered class (e.g. '.' or '\w') in the pattern. (4) Ignore look-ahead and look-behind assertions. (5) Raise an error on any disjunctive ('|') constructs. Django's URLs for forward resolving are either all positional arguments or all keyword arguments. That is assumed here, as well. Although reverse resolving can be done using positional args when keyword args are specified, the two cannot be mixed in the same reverse() call. """ # Do a linear scan to work out the special features of this pattern. The # idea is that we scan once here and collect all the information we need to # make future decisions. result = [] non_capturing_groups = [] consume_next = True pattern_iter = next_char(iter(pattern)) num_args = 0 # A "while" loop is used here because later on we need to be able to peek # at the next character and possibly go around without consuming another # one at the top of the loop. try: ch, escaped = next(pattern_iter) except StopIteration: return [("", [])] try: while True: if escaped: result.append(ch) elif ch == ".": # Replace "any character" with an arbitrary representative. result.append(".") elif ch == "|": # FIXME: One day we'll should do this, but not in 1.0. raise NotImplementedError("Awaiting Implementation") elif ch == "^": pass elif ch == "$": break elif ch == ")": # This can only be the end of a non-capturing group, since all # other unescaped parentheses are handled by the grouping # section later (and the full group is handled there). # # We regroup everything inside the capturing group so that it # can be quantified, if necessary. start = non_capturing_groups.pop() inner = NonCapture(result[start:]) result = result[:start] + [inner] elif ch == "[": # Replace ranges with the first character in the range. ch, escaped = next(pattern_iter) result.append(ch) ch, escaped = next(pattern_iter) while escaped or ch != "]": ch, escaped = next(pattern_iter) elif ch == "(": # Some kind of group. ch, escaped = next(pattern_iter) if ch != "?" or escaped: # A positional group name = "_%d" % num_args num_args += 1 result.append(Group((("%%(%s)s" % name), name))) walk_to_end(ch, pattern_iter) else: ch, escaped = next(pattern_iter) if ch in "!=<": # All of these are ignorable. Walk to the end of the # group. walk_to_end(ch, pattern_iter) elif ch == ":": # Non-capturing group non_capturing_groups.append(len(result)) elif ch != "P": # Anything else, other than a named group, is something # we cannot reverse. raise ValueError("Non-reversible reg-exp portion: '(?%s'" % ch) else: ch, escaped = next(pattern_iter) if ch not in ("<", "="): raise ValueError( "Non-reversible reg-exp portion: '(?P%s'" % ch ) # We are in a named capturing group. Extra the name and # then skip to the end. if ch == "<": terminal_char = ">" # We are in a named backreference. else: terminal_char = ")" name = [] ch, escaped = next(pattern_iter) while ch != terminal_char: name.append(ch) ch, escaped = next(pattern_iter) param = "".join(name) # Named backreferences have already consumed the # parenthesis. if terminal_char != ")": result.append(Group((("%%(%s)s" % param), param))) walk_to_end(ch, pattern_iter) else: result.append(Group((("%%(%s)s" % param), None))) elif ch in "*?+{": # Quantifiers affect the previous item in the result list. count, ch = get_quantifier(ch, pattern_iter) if ch: # We had to look ahead, but it wasn't need to compute the # quantifier, so use this character next time around the # main loop. consume_next = False if count == 0: if contains(result[-1], Group): # If we are quantifying a capturing group (or # something containing such a group) and the minimum is # zero, we must also handle the case of one occurrence # being present. All the quantifiers (except {0,0}, # which we conveniently ignore) that have a 0 minimum # also allow a single occurrence. result[-1] = Choice([None, result[-1]]) else: result.pop() elif count > 1: result.extend([result[-1]] * (count - 1)) else: # Anything else is a literal. result.append(ch) if consume_next: ch, escaped = next(pattern_iter) consume_next = True except StopIteration: pass except NotImplementedError: # A case of using the disjunctive form. No results for you! return [("", [])] return list(zip(*flatten_result(result))) def next_char(input_iter): r""" An iterator that yields the next character from "pattern_iter", respecting escape sequences. An escaped character is replaced by a representative of its class (e.g. \w -> "x"). If the escaped character is one that is skipped, it is not returned (the next character is returned instead). Yield the next character, along with a boolean indicating whether it is a raw (unescaped) character or not. """ for ch in input_iter: if ch != "\\": yield ch, False continue ch = next(input_iter) representative = ESCAPE_MAPPINGS.get(ch, ch) if representative is None: continue yield representative, True def walk_to_end(ch, input_iter): """ The iterator is currently inside a capturing group. Walk to the close of this group, skipping over any nested groups and handling escaped parentheses correctly. """ if ch == "(": nesting = 1 else: nesting = 0 for ch, escaped in input_iter: if escaped: continue elif ch == "(": nesting += 1 elif ch == ")": if not nesting: return nesting -= 1 def get_quantifier(ch, input_iter): """ Parse a quantifier from the input, where "ch" is the first character in the quantifier. Return the minimum number of occurrences permitted by the quantifier and either None or the next character from the input_iter if the next character is not part of the quantifier. """ if ch in "*?+": try: ch2, escaped = next(input_iter) except StopIteration: ch2 = None if ch2 == "?": ch2 = None if ch == "+": return 1, ch2 return 0, ch2 quant = [] while ch != "}": ch, escaped = next(input_iter) quant.append(ch) quant = quant[:-1] values = "".join(quant).split(",") # Consume the trailing '?', if necessary. try: ch, escaped = next(input_iter) except StopIteration: ch = None if ch == "?": ch = None return int(values[0]), ch def contains(source, inst): """ Return True if the "source" contains an instance of "inst". False, otherwise. """ if isinstance(source, inst): return True if isinstance(source, NonCapture): for elt in source: if contains(elt, inst): return True return False def flatten_result(source): """ Turn the given source sequence into a list of reg-exp possibilities and their arguments. Return a list of strings and a list of argument lists. Each of the two lists will be of the same length. """ if source is None: return [""], [[]] if isinstance(source, Group): if source[1] is None: params = [] else: params = [source[1]] return [source[0]], [params] result = [""] result_args = [[]] pos = last = 0 for pos, elt in enumerate(source): if isinstance(elt, str): continue piece = "".join(source[last:pos]) if isinstance(elt, Group): piece += elt[0] param = elt[1] else: param = None last = pos + 1 for i in range(len(result)): result[i] += piece if param: result_args[i].append(param) if isinstance(elt, (Choice, NonCapture)): if isinstance(elt, NonCapture): elt = [elt] inner_result, inner_args = [], [] for item in elt: res, args = flatten_result(item) inner_result.extend(res) inner_args.extend(args) new_result = [] new_args = [] for item, args in zip(result, result_args): for i_item, i_args in zip(inner_result, inner_args): new_result.append(item + i_item) new_args.append(args[:] + i_args) result = new_result result_args = new_args if pos >= last: piece = "".join(source[last:]) for i in range(len(result)): result[i] += piece return result, result_args def _lazy_re_compile(regex, flags=0): """Lazily compile a regex with flags.""" def _compile(): # Compile the regex if it was not passed pre-compiled. if isinstance(regex, (str, bytes)): return re.compile(regex, flags) else: assert not flags, "flags must be empty if regex is passed pre-compiled" return regex return SimpleLazyObject(_compile)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/timezone.py
django/utils/timezone.py
""" Timezone-related classes and functions. """ import functools import zoneinfo from contextlib import ContextDecorator from datetime import UTC, datetime, timedelta, timezone, tzinfo from asgiref.local import Local from django.conf import settings __all__ = [ "get_fixed_timezone", "get_default_timezone", "get_default_timezone_name", "get_current_timezone", "get_current_timezone_name", "activate", "deactivate", "override", "localtime", "localdate", "now", "is_aware", "is_naive", "make_aware", "make_naive", ] def get_fixed_timezone(offset): """Return a tzinfo instance with a fixed offset from UTC.""" if isinstance(offset, timedelta): offset = offset.total_seconds() // 60 sign = "-" if offset < 0 else "+" hhmm = "%02d%02d" % divmod(abs(offset), 60) name = sign + hhmm return timezone(timedelta(minutes=offset), name) # In order to avoid accessing settings at compile time, # wrap the logic in a function and cache the result. @functools.lru_cache def get_default_timezone(): """ Return the default time zone as a tzinfo instance. This is the time zone defined by settings.TIME_ZONE. """ return zoneinfo.ZoneInfo(settings.TIME_ZONE) # This function exists for consistency with get_current_timezone_name def get_default_timezone_name(): """Return the name of the default time zone.""" return _get_timezone_name(get_default_timezone()) _active = Local() def get_current_timezone(): """Return the currently active time zone as a tzinfo instance.""" return getattr(_active, "value", get_default_timezone()) def get_current_timezone_name(): """Return the name of the currently active time zone.""" return _get_timezone_name(get_current_timezone()) def _get_timezone_name(timezone): """ Return the offset for fixed offset timezones, or the name of timezone if not set. """ return timezone.tzname(None) or str(timezone) # Timezone selection functions. # These functions don't change os.environ['TZ'] and call time.tzset() # because it isn't thread safe. def activate(timezone): """ Set the time zone for the current thread. The ``timezone`` argument must be an instance of a tzinfo subclass or a time zone name. """ if isinstance(timezone, tzinfo): _active.value = timezone elif isinstance(timezone, str): _active.value = zoneinfo.ZoneInfo(timezone) else: raise ValueError("Invalid timezone: %r" % timezone) def deactivate(): """ Unset the time zone for the current thread. Django will then use the time zone defined by settings.TIME_ZONE. """ if hasattr(_active, "value"): del _active.value class override(ContextDecorator): """ Temporarily set the time zone for the current thread. This is a context manager that uses django.utils.timezone.activate() to set the timezone on entry and restores the previously active timezone on exit. The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a time zone name, or ``None``. If it is ``None``, Django enables the default time zone. """ def __init__(self, timezone): self.timezone = timezone def __enter__(self): self.old_timezone = getattr(_active, "value", None) if self.timezone is None: deactivate() else: activate(self.timezone) def __exit__(self, exc_type, exc_value, traceback): if self.old_timezone is None: deactivate() else: _active.value = self.old_timezone # Templates def template_localtime(value, use_tz=None): """ Check if value is a datetime and converts it to local time if necessary. If use_tz is provided and is not None, that will force the value to be converted (or not), overriding the value of settings.USE_TZ. This function is designed for use by the template engine. """ should_convert = ( isinstance(value, datetime) and (settings.USE_TZ if use_tz is None else use_tz) and not is_naive(value) and getattr(value, "convert_to_local_time", True) ) return localtime(value) if should_convert else value # Utilities def localtime(value=None, timezone=None): """ Convert an aware datetime.datetime to local time. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ if value is None: value = now() if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("localtime() cannot be applied to a naive datetime") return value.astimezone(timezone) def localdate(value=None, timezone=None): """ Convert an aware datetime to local time and return the value's date. Only aware datetimes are allowed. When value is omitted, it defaults to now(). Local time is defined by the current time zone, unless another time zone is specified. """ return localtime(value, timezone).date() def now(): """ Return an aware or naive datetime.datetime, depending on settings.USE_TZ. """ return datetime.now(tz=UTC if settings.USE_TZ else None) # By design, these four functions don't perform any checks on their arguments. # The caller should ensure that they don't receive an invalid value like None. def is_aware(value): """ Determine if a given datetime.datetime is aware. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is not None def is_naive(value): """ Determine if a given datetime.datetime is naive. The concept is defined in Python's docs: https://docs.python.org/library/datetime.html#datetime.tzinfo Assuming value.tzinfo is either None or a proper datetime.tzinfo, value.utcoffset() implements the appropriate logic. """ return value.utcoffset() is None def make_aware(value, timezone=None): """Make a naive datetime.datetime in a given time zone aware.""" if timezone is None: timezone = get_current_timezone() # Check that we won't overwrite the timezone of an aware datetime. if is_aware(value): raise ValueError("make_aware expects a naive datetime, got %s" % value) # This may be wrong around DST changes! return value.replace(tzinfo=timezone) def make_naive(value, timezone=None): """Make an aware datetime.datetime naive in a given time zone.""" if timezone is None: timezone = get_current_timezone() # Emulate the behavior of astimezone() on Python < 3.6. if is_naive(value): raise ValueError("make_naive() cannot be applied to a naive datetime") return value.astimezone(timezone).replace(tzinfo=None) def _datetime_ambiguous_or_imaginary(dt, tz): return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/safestring.py
django/utils/safestring.py
""" Functions for working with "safe strings": strings that can be displayed safely without further escaping in HTML. Marking something as a "safe string" means that the producer of the string has already turned characters that should not be interpreted by the HTML engine (e.g. '<') into the appropriate entities. """ from functools import wraps from django.utils.functional import keep_lazy class SafeData: __slots__ = () def __html__(self): """ Return the html representation of a string for interoperability. This allows other template engines to understand Django's SafeData. """ return self class SafeString(str, SafeData): """ A str subclass that has been specifically marked as "safe" for HTML output purposes. """ __slots__ = () def __add__(self, rhs): """ Concatenating a safe string with another safe bytestring or safe string is safe. Otherwise, the result is no longer safe. """ if isinstance(rhs, str): t = super().__add__(rhs) if isinstance(rhs, SafeData): t = SafeString(t) return t # Give the rhs object a chance to handle the addition, for example if # the rhs object's class implements `__radd__`. More details: # https://docs.python.org/3/reference/datamodel.html#object.__radd__ return NotImplemented def __str__(self): return self SafeText = SafeString # For backwards compatibility since Django 2.0. def _safety_decorator(safety_marker, func): @wraps(func) def wrapper(*args, **kwargs): return safety_marker(func(*args, **kwargs)) return wrapper @keep_lazy(SafeString) def mark_safe(s): """ Explicitly mark a string as safe for (HTML) output purposes. The returned object can be used everywhere a string is appropriate. If used on a method as a decorator, mark the returned data as safe. Can be called multiple times on a single string. """ if hasattr(s, "__html__"): return s if callable(s): return _safety_decorator(mark_safe, s) return SafeString(s)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/copy.py
django/utils/copy.py
from django.utils.version import PY313 if PY313: from copy import replace else: # Backport of copy.replace() from Python 3.13. def replace(obj, /, **changes): """Return a new object replacing specified fields with new values. This is especially useful for immutable objects, like named tuples or frozen dataclasses. """ cls = obj.__class__ func = getattr(cls, "__replace__", None) if func is None: raise TypeError(f"replace() does not support {cls.__name__} objects") return func(obj, **changes)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/connection.py
django/utils/connection.py
from asgiref.local import Local from django.conf import settings as django_settings from django.utils.functional import cached_property class ConnectionProxy: """Proxy for accessing a connection object's attributes.""" def __init__(self, connections, alias): self.__dict__["_connections"] = connections self.__dict__["_alias"] = alias def __getattr__(self, item): return getattr(self._connections[self._alias], item) def __setattr__(self, name, value): return setattr(self._connections[self._alias], name, value) def __delattr__(self, name): return delattr(self._connections[self._alias], name) def __contains__(self, key): return key in self._connections[self._alias] def __eq__(self, other): return self._connections[self._alias] == other class ConnectionDoesNotExist(Exception): pass class BaseConnectionHandler: settings_name = None exception_class = ConnectionDoesNotExist thread_critical = False def __init__(self, settings=None): self._settings = settings self._connections = Local(self.thread_critical) @cached_property def settings(self): self._settings = self.configure_settings(self._settings) return self._settings def configure_settings(self, settings): if settings is None: settings = getattr(django_settings, self.settings_name) return settings def create_connection(self, alias): raise NotImplementedError("Subclasses must implement create_connection().") def __getitem__(self, alias): try: return getattr(self._connections, alias) except AttributeError: if alias not in self.settings: raise self.exception_class(f"The connection '{alias}' doesn't exist.") conn = self.create_connection(alias) setattr(self._connections, alias, conn) return conn def __setitem__(self, key, value): setattr(self._connections, key, value) def __delitem__(self, key): delattr(self._connections, key) def __iter__(self): return iter(self.settings) def all(self, initialized_only=False): return [ self[alias] for alias in self # If initialized_only is True, return only initialized connections. if not initialized_only or hasattr(self._connections, alias) ] def close_all(self): for conn in self.all(initialized_only=True): conn.close()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/encoding.py
django/utils/encoding.py
import codecs import datetime import locale from decimal import Decimal from types import NoneType from urllib.parse import quote from django.utils.functional import Promise class DjangoUnicodeDecodeError(UnicodeDecodeError): def __str__(self): return "%s. You passed in %r (%s)" % ( super().__str__(), self.object, type(self.object), ) def smart_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a string representing 's'. Treat bytestrings using the 'encoding' codec. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_str(s, encoding, strings_only, errors) _PROTECTED_TYPES = ( NoneType, int, float, Decimal, datetime.datetime, datetime.date, datetime.time, ) def is_protected_type(obj): """Determine if the object instance is of a protected type. Objects of protected types are preserved as-is when passed to force_str(strings_only=True). """ return isinstance(obj, _PROTECTED_TYPES) def force_str(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_str(), except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if issubclass(type(s), str): return s if strings_only and is_protected_type(s): return s try: if isinstance(s, bytes): s = str(s, encoding, errors) else: s = str(s) except UnicodeDecodeError as e: raise DjangoUnicodeDecodeError(*e.args) from None return s def smart_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Return a bytestring version of 's', encoded as specified in 'encoding'. If strings_only is True, don't convert (some) non-string-like objects. """ if isinstance(s, Promise): # The input is the result of a gettext_lazy() call. return s return force_bytes(s, encoding, strings_only, errors) def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): """ Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects. """ # Handle the common case first for performance reasons. if isinstance(s, bytes): if encoding == "utf-8": return s else: return s.decode("utf-8", errors).encode(encoding, errors) if strings_only and is_protected_type(s): return s if isinstance(s, memoryview): return bytes(s) return str(s).encode(encoding, errors) def iri_to_uri(iri): """ Convert an Internationalized Resource Identifier (IRI) portion to a URI portion that is suitable for inclusion in a URL. This is the algorithm from RFC 3987 Section 3.1, slightly simplified since the input is assumed to be a string rather than an arbitrary byte stream. Take an IRI (string or UTF-8 bytes, e.g. '/I ♥ Django/' or b'/I \xe2\x99\xa5 Django/') and return a string containing the encoded result with ASCII chars only (e.g. '/I%20%E2%99%A5%20Django/'). """ # The list of safe characters here is constructed from the "reserved" and # "unreserved" characters specified in RFC 3986 Sections 2.2 and 2.3: # reserved = gen-delims / sub-delims # gen-delims = ":" / "/" / "?" / "#" / "[" / "]" / "@" # sub-delims = "!" / "$" / "&" / "'" / "(" / ")" # / "*" / "+" / "," / ";" / "=" # unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" # Of the unreserved characters, urllib.parse.quote() already considers all # but the ~ safe. # The % character is also added to the list of safe characters here, as the # end of RFC 3987 Section 3.1 specifically mentions that % must not be # converted. if iri is None: return iri elif isinstance(iri, Promise): iri = str(iri) return quote(iri, safe="/#%[]=:;$&()+,!?*@'~") # List of byte values that uri_to_iri() decodes from percent encoding. # First, the unreserved characters from RFC 3986: _ascii_ranges = [[45, 46, 95, 126], range(65, 91), range(97, 123)] _hextobyte = { (fmt % char).encode(): bytes((char,)) for ascii_range in _ascii_ranges for char in ascii_range for fmt in ["%02x", "%02X"] } # And then everything above 128, because bytes ≥ 128 are part of multibyte # Unicode characters. _hexdig = "0123456789ABCDEFabcdef" _hextobyte.update( {(a + b).encode(): bytes.fromhex(a + b) for a in _hexdig[8:] for b in _hexdig} ) def uri_to_iri(uri): """ Convert a Uniform Resource Identifier(URI) into an Internationalized Resource Identifier(IRI). This is the algorithm from RFC 3987 Section 3.2, excluding step 4. Take an URI in ASCII bytes (e.g. '/I%20%E2%99%A5%20Django/') and return a string containing the encoded result (e.g. '/I%20♥%20Django/'). """ if uri is None: return uri uri = force_bytes(uri) # Fast selective unquote: First, split on '%' and then starting with the # second block, decode the first 2 bytes if they represent a hex code to # decode. The rest of the block is the part after '%AB', not containing # any '%'. Add that to the output without further processing. bits = uri.split(b"%") if len(bits) == 1: iri = uri else: parts = [bits[0]] append = parts.append hextobyte = _hextobyte for item in bits[1:]: hex = item[:2] if hex in hextobyte: append(hextobyte[item[:2]]) append(item[2:]) else: append(b"%") append(item) iri = b"".join(parts) return repercent_broken_unicode(iri).decode() def escape_uri_path(path): """ Escape the unsafe characters from the path portion of a Uniform Resource Identifier (URI). """ # These are the "reserved" and "unreserved" characters specified in RFC # 3986 Sections 2.2 and 2.3: # reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," # unreserved = alphanum | mark # mark = "-" | "_" | "." | "!" | "~" | "*" | "'" | "(" | ")" # The list of safe characters here is constructed subtracting ";", "=", # and "?" according to RFC 3986 Section 3.3. # The reason for not subtracting and escaping "/" is that we are escaping # the entire path, not a path segment. return quote(path, safe="/:@&+$,-_.!~*'()") def punycode(domain): """Return the Punycode of the given domain if it's non-ASCII.""" return domain.encode("idna").decode("ascii") def repercent_broken_unicode(path): """ As per RFC 3987 Section 3.2, step three of converting a URI into an IRI, repercent-encode any octet produced that is not part of a strictly legal UTF-8 octet sequence. """ changed_parts = [] while True: try: path.decode() except UnicodeDecodeError as e: # CVE-2019-14235: A recursion shouldn't be used since the exception # handling uses massive amounts of memory repercent = quote(path[e.start : e.end], safe=b"/#%[]=:;$&()+,!?*@'~") changed_parts.append(path[: e.start] + repercent.encode()) path = path[e.end :] else: return b"".join(changed_parts) + path def filepath_to_uri(path): """Convert a file system path to a URI portion that is suitable for inclusion in a URL. Encode certain chars that would normally be recognized as special chars for URIs. Do not encode the ' character, as it is a valid character within URIs. See the encodeURIComponent() JavaScript function for details. """ if path is None: return path # I know about `os.sep` and `os.altsep` but I want to leave # some flexibility for hardcoding separators. return quote(str(path).replace("\\", "/"), safe="/~!*()'") def get_system_encoding(): """ The encoding for the character type functions. Fallback to 'ascii' if the #encoding is unsupported by Python or could not be determined. See tickets #10335 and #5846. """ try: encoding = locale.getlocale()[1] or "ascii" codecs.lookup(encoding) except Exception: encoding = "ascii" return encoding DEFAULT_LOCALE_ENCODING = get_system_encoding()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/__init__.py
django/utils/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/hashable.py
django/utils/hashable.py
from collections.abc import Iterable def make_hashable(value): """ Attempt to make value hashable or raise a TypeError if it fails. The returned value should generate the same hash for equal values. """ if isinstance(value, dict): return tuple( [ (key, make_hashable(nested_value)) for key, nested_value in sorted(value.items()) ] ) # Try hash to avoid converting a hashable iterable (e.g. string, frozenset) # to a tuple. try: hash(value) except TypeError: if isinstance(value, Iterable): return tuple(map(make_hashable, value)) # Non-hashable, non-iterable. raise return value
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/deconstruct.py
django/utils/deconstruct.py
from importlib import import_module from django.utils.version import get_docs_version def deconstructible(*args, path=None): """ Class decorator that allows the decorated class to be serialized by the migrations subsystem. The `path` kwarg specifies the import path. """ def decorator(klass): def __new__(cls, *args, **kwargs): # We capture the arguments to make returning them trivial obj = super(klass, cls).__new__(cls) obj._constructor_args = (args, kwargs) return obj def deconstruct(obj): """ Return a 3-tuple of class import path, positional arguments, and keyword arguments. """ # Fallback version if path and type(obj) is klass: module_name, _, name = path.rpartition(".") else: module_name = obj.__module__ name = obj.__class__.__name__ # Make sure it's actually there and not an inner class module = import_module(module_name) if not hasattr(module, name): raise ValueError( "Could not find object %s in %s.\n" "Please note that you cannot serialize things like inner " "classes. Please move the object into the main module " "body to use migrations.\n" "For more information, see " "https://docs.djangoproject.com/en/%s/topics/migrations/" "#serializing-values" % (name, module_name, get_docs_version()) ) return ( ( path if path and type(obj) is klass else f"{obj.__class__.__module__}.{name}" ), obj._constructor_args[0], obj._constructor_args[1], ) klass.__new__ = staticmethod(__new__) klass.deconstruct = deconstruct return klass if not args: return decorator return decorator(*args)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/dates.py
django/utils/dates.py
"Commonly-used date structures" from django.utils.translation import gettext_lazy as _ from django.utils.translation import pgettext_lazy WEEKDAYS = { 0: _("Monday"), 1: _("Tuesday"), 2: _("Wednesday"), 3: _("Thursday"), 4: _("Friday"), 5: _("Saturday"), 6: _("Sunday"), } WEEKDAYS_ABBR = { 0: _("Mon"), 1: _("Tue"), 2: _("Wed"), 3: _("Thu"), 4: _("Fri"), 5: _("Sat"), 6: _("Sun"), } MONTHS = { 1: _("January"), 2: _("February"), 3: _("March"), 4: _("April"), 5: _("May"), 6: _("June"), 7: _("July"), 8: _("August"), 9: _("September"), 10: _("October"), 11: _("November"), 12: _("December"), } MONTHS_3 = { 1: _("jan"), 2: _("feb"), 3: _("mar"), 4: _("apr"), 5: _("may"), 6: _("jun"), 7: _("jul"), 8: _("aug"), 9: _("sep"), 10: _("oct"), 11: _("nov"), 12: _("dec"), } MONTHS_AP = { # month names in Associated Press style 1: pgettext_lazy("abbrev. month", "Jan."), 2: pgettext_lazy("abbrev. month", "Feb."), 3: pgettext_lazy("abbrev. month", "March"), 4: pgettext_lazy("abbrev. month", "April"), 5: pgettext_lazy("abbrev. month", "May"), 6: pgettext_lazy("abbrev. month", "June"), 7: pgettext_lazy("abbrev. month", "July"), 8: pgettext_lazy("abbrev. month", "Aug."), 9: pgettext_lazy("abbrev. month", "Sept."), 10: pgettext_lazy("abbrev. month", "Oct."), 11: pgettext_lazy("abbrev. month", "Nov."), 12: pgettext_lazy("abbrev. month", "Dec."), } MONTHS_ALT = { # required for long date representation by some locales 1: pgettext_lazy("alt. month", "January"), 2: pgettext_lazy("alt. month", "February"), 3: pgettext_lazy("alt. month", "March"), 4: pgettext_lazy("alt. month", "April"), 5: pgettext_lazy("alt. month", "May"), 6: pgettext_lazy("alt. month", "June"), 7: pgettext_lazy("alt. month", "July"), 8: pgettext_lazy("alt. month", "August"), 9: pgettext_lazy("alt. month", "September"), 10: pgettext_lazy("alt. month", "October"), 11: pgettext_lazy("alt. month", "November"), 12: pgettext_lazy("alt. month", "December"), }
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/json.py
django/utils/json.py
from collections.abc import Mapping, Sequence def normalize_json(obj): """Recursively normalize an object into JSON-compatible types.""" match obj: case Mapping(): return {normalize_json(k): normalize_json(v) for k, v in obj.items()} case bytes(): try: return obj.decode("utf-8") except UnicodeDecodeError: raise ValueError(f"Unsupported value: {type(obj)}") case str() | int() | float() | bool() | None: return obj case Sequence(): # str and bytes were already handled. return [normalize_json(v) for v in obj] case _: # Other types can't be serialized to JSON raise TypeError(f"Unsupported type: {type(obj)}")
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/text.py
django/utils/text.py
import gzip import re import secrets import textwrap import unicodedata from collections import deque from gzip import GzipFile from gzip import compress as gzip_compress from html import escape from html.parser import HTMLParser from io import BytesIO from django.core.exceptions import SuspiciousFileOperation from django.utils.functional import ( SimpleLazyObject, cached_property, keep_lazy_text, lazy, ) from django.utils.regex_helper import _lazy_re_compile from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy, pgettext @keep_lazy_text def capfirst(x): """Capitalize the first letter of a string.""" if not x: return x if not isinstance(x, str): x = str(x) return x[0].upper() + x[1:] # Set up regular expressions re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))") @keep_lazy_text def wrap(text, width): """ A word-wrap function that preserves existing line breaks. Expects that existing line breaks are posix newlines. Preserve all white space except added line breaks consume the space on which they break the line. Don't wrap long words, thus the output text may have lines longer than ``width``. """ wrapper = textwrap.TextWrapper( width=width, break_long_words=False, break_on_hyphens=False, replace_whitespace=False, ) result = [] for line in text.splitlines(): wrapped = wrapper.wrap(line) if not wrapped: # If `line` contains only whitespaces that are dropped, restore it. result.append(line) else: result.extend(wrapped) if text.endswith("\n"): # If `text` ends with a newline, preserve it. result.append("") return "\n".join(result) def add_truncation_text(text, truncate=None): if truncate is None: truncate = pgettext( "String to return when truncating text", "%(truncated_text)s…" ) if "%(truncated_text)s" in truncate: return truncate % {"truncated_text": text} # The truncation text didn't contain the %(truncated_text)s string # replacement argument so just append it to the text. if text.endswith(truncate): # But don't append the truncation text if the current text already ends # in this. return text return f"{text}{truncate}" def calculate_truncate_chars_length(length, replacement): truncate_len = length for char in add_truncation_text("", replacement): if not unicodedata.combining(char): truncate_len -= 1 if truncate_len == 0: break return truncate_len class TruncateHTMLParser(HTMLParser): class TruncationCompleted(Exception): pass def __init__(self, *, length, replacement, convert_charrefs=True): super().__init__(convert_charrefs=convert_charrefs) self.tags = deque() self.output = [] self.remaining = length self.replacement = replacement @cached_property def void_elements(self): from django.utils.html import VOID_ELEMENTS return VOID_ELEMENTS def handle_startendtag(self, tag, attrs): self.handle_starttag(tag, attrs) if tag not in self.void_elements: self.handle_endtag(tag) def handle_starttag(self, tag, attrs): self.output.append(self.get_starttag_text()) if tag not in self.void_elements: self.tags.appendleft(tag) def handle_endtag(self, tag): if tag not in self.void_elements: self.output.append(f"</{tag}>") try: self.tags.remove(tag) except ValueError: pass def handle_data(self, data): data, output = self.process(data) data_len = len(data) if self.remaining < data_len: self.remaining = 0 self.output.append(add_truncation_text(output, self.replacement)) raise self.TruncationCompleted self.remaining -= data_len self.output.append(output) def feed(self, data): try: super().feed(data) except self.TruncationCompleted: self.output.extend([f"</{tag}>" for tag in self.tags]) self.tags.clear() self.reset() else: # No data was handled. self.reset() class TruncateCharsHTMLParser(TruncateHTMLParser): def __init__(self, *, length, replacement, convert_charrefs=True): self.length = length self.processed_chars = 0 super().__init__( length=calculate_truncate_chars_length(length, replacement), replacement=replacement, convert_charrefs=convert_charrefs, ) def process(self, data): self.processed_chars += len(data) if (self.processed_chars == self.length) and ( sum(len(p) for p in self.output) + len(data) == len(self.rawdata) ): self.output.append(data) raise self.TruncationCompleted output = escape("".join(data[: self.remaining])) return data, output class TruncateWordsHTMLParser(TruncateHTMLParser): def process(self, data): data = re.split(r"(?<=\S)\s+(?=\S)", data) output = escape(" ".join(data[: self.remaining])) return data, output class Truncator(SimpleLazyObject): """ An object used to truncate text, either by characters or words. When truncating HTML text (either chars or words), input will be limited to at most `MAX_LENGTH_HTML` characters. """ # 5 million characters are approximately 4000 text pages or 3 web pages. MAX_LENGTH_HTML = 5_000_000 def __init__(self, text): super().__init__(lambda: str(text)) def chars(self, num, truncate=None, html=False): """ Return the text truncated to be no longer than the specified number of characters. `truncate` specifies what should be used to notify that the string has been truncated, defaulting to a translatable string of an ellipsis. """ self._setup() length = int(num) if length <= 0: return "" text = unicodedata.normalize("NFC", self._wrapped) if html: parser = TruncateCharsHTMLParser(length=length, replacement=truncate) parser.feed(text) parser.close() return "".join(parser.output) return self._text_chars(length, truncate, text) def _text_chars(self, length, truncate, text): """Truncate a string after a certain number of chars.""" truncate_len = calculate_truncate_chars_length(length, truncate) s_len = 0 end_index = None for i, char in enumerate(text): if unicodedata.combining(char): # Don't consider combining characters # as adding to the string length continue s_len += 1 if end_index is None and s_len > truncate_len: end_index = i if s_len > length: # Return the truncated string return add_truncation_text(text[: end_index or 0], truncate) # Return the original string since no truncation was necessary return text def words(self, num, truncate=None, html=False): """ Truncate a string after a certain number of words. `truncate` specifies what should be used to notify that the string has been truncated, defaulting to ellipsis. """ self._setup() length = int(num) if length <= 0: return "" if html: parser = TruncateWordsHTMLParser(length=length, replacement=truncate) parser.feed(self._wrapped) parser.close() return "".join(parser.output) return self._text_words(length, truncate) def _text_words(self, length, truncate): """ Truncate a string after a certain number of words. Strip newlines in the string. """ words = self._wrapped.split() if len(words) > length: words = words[:length] return add_truncation_text(" ".join(words), truncate) return " ".join(words) @keep_lazy_text def get_valid_filename(name): """ Return the given string converted to a string that can be used for a clean filename. Remove leading and trailing spaces; convert other spaces to underscores; and remove anything that is not an alphanumeric, dash, underscore, or dot. >>> get_valid_filename("john's portrait in 2004.jpg") 'johns_portrait_in_2004.jpg' """ s = str(name).strip().replace(" ", "_") s = re.sub(r"(?u)[^-\w.]", "", s) if s in {"", ".", ".."}: raise SuspiciousFileOperation("Could not derive file name from '%s'" % name) return s @keep_lazy_text def get_text_list(list_, last_word=gettext_lazy("or")): """ >>> get_text_list(['a', 'b', 'c', 'd']) 'a, b, c or d' >>> get_text_list(['a', 'b', 'c'], 'and') 'a, b and c' >>> get_text_list(['a', 'b'], 'and') 'a and b' >>> get_text_list(['a']) 'a' >>> get_text_list([]) '' """ if not list_: return "" if len(list_) == 1: return str(list_[0]) return "%s %s %s" % ( # Translators: This string is used as a separator between list elements _(", ").join(str(i) for i in list_[:-1]), str(last_word), str(list_[-1]), ) @keep_lazy_text def normalize_newlines(text): """Normalize CRLF and CR newlines to just LF.""" return re_newlines.sub("\n", str(text)) @keep_lazy_text def phone2numeric(phone): """Convert a phone number with letters into its numeric equivalent.""" char2number = { "a": "2", "b": "2", "c": "2", "d": "3", "e": "3", "f": "3", "g": "4", "h": "4", "i": "4", "j": "5", "k": "5", "l": "5", "m": "6", "n": "6", "o": "6", "p": "7", "q": "7", "r": "7", "s": "7", "t": "8", "u": "8", "v": "8", "w": "9", "x": "9", "y": "9", "z": "9", } return "".join(char2number.get(c, c) for c in phone.lower()) def _get_random_filename(max_random_bytes): return b"a" * secrets.randbelow(max_random_bytes) def compress_string(s, *, max_random_bytes=None): compressed_data = gzip_compress(s, compresslevel=6, mtime=0) if not max_random_bytes: return compressed_data compressed_view = memoryview(compressed_data) header = bytearray(compressed_view[:10]) header[3] = gzip.FNAME filename = _get_random_filename(max_random_bytes) + b"\x00" return bytes(header) + filename + compressed_view[10:] class StreamingBuffer(BytesIO): def read(self): ret = self.getvalue() self.seek(0) self.truncate() return ret # Like compress_string, but for iterators of strings. def compress_sequence(sequence, *, max_random_bytes=None): buf = StreamingBuffer() filename = _get_random_filename(max_random_bytes) if max_random_bytes else None with GzipFile( filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0 ) as zfile: # Output headers... yield buf.read() for item in sequence: zfile.write(item) data = buf.read() if data: yield data yield buf.read() async def acompress_sequence(sequence, *, max_random_bytes=None): buf = StreamingBuffer() filename = _get_random_filename(max_random_bytes) if max_random_bytes else None with GzipFile( filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0 ) as zfile: # Output headers... yield buf.read() async for item in sequence: zfile.write(item) data = buf.read() if data: yield data yield buf.read() # Expression to match some_token and some_token="with spaces" (and similarly # for single-quoted strings). smart_split_re = _lazy_re_compile( r""" ((?: [^\s'"]* (?: (?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*') [^\s'"]* )+ ) | \S+) """, re.VERBOSE, ) def smart_split(text): r""" Generator that splits a string by spaces, leaving quoted phrases together. Supports both single and double quotes, and supports escaping quotes with backslashes. In the output, strings will keep their initial and trailing quote marks and escaped quotes will remain escaped (the results can then be further processed with unescape_string_literal()). >>> list(smart_split(r'This is "a person\'s" test.')) ['This', 'is', '"a person\\\'s"', 'test.'] >>> list(smart_split(r"Another 'person\'s' test.")) ['Another', "'person\\'s'", 'test.'] >>> list(smart_split(r'A "\"funky\" style" test.')) ['A', '"\\"funky\\" style"', 'test.'] """ for bit in smart_split_re.finditer(str(text)): yield bit[0] @keep_lazy_text def unescape_string_literal(s): r""" Convert quoted string literals to unquoted strings with escaped quotes and backslashes unquoted:: >>> unescape_string_literal('"abc"') 'abc' >>> unescape_string_literal("'abc'") 'abc' >>> unescape_string_literal('"a \"bc\""') 'a "bc"' >>> unescape_string_literal("'\'ab\' c'") "'ab' c" """ if not s or s[0] not in "\"'" or s[-1] != s[0]: raise ValueError("Not a string literal: %r" % s) quote = s[0] return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\") @keep_lazy_text def slugify(value, allow_unicode=False): """ Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated dashes to single dashes. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace, dashes, and underscores. """ value = str(value) if allow_unicode: value = unicodedata.normalize("NFKC", value) else: value = ( unicodedata.normalize("NFKD", value) .encode("ascii", "ignore") .decode("ascii") ) value = re.sub(r"[^\w\s-]", "", value.lower()) return re.sub(r"[-\s]+", "-", value).strip("-_") def camel_case_to_spaces(value): """ Split CamelCase and convert to lowercase. Strip surrounding whitespace. """ return re_camel_case.sub(r" \1", value).strip().lower() def _format_lazy(format_string, *args, **kwargs): """ Apply str.format() on 'format_string' where format_string, args, and/or kwargs might be lazy. """ return format_string.format(*args, **kwargs) format_lazy = lazy(_format_lazy, str)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/cache.py
django/utils/cache.py
""" This module contains helper functions for controlling caching. It does so by managing the "Vary" header of responses. It includes functions to patch the header of response objects directly and decorators that change functions to do that header-patching themselves. For information on the Vary header, see RFC 9110 Section 12.5.5. Essentially, the "Vary" HTTP header defines which headers a cache should take into account when building its cache key. Requests with the same path but different header content for headers named in "Vary" need to get different cache keys to prevent delivery of wrong content. An example: i18n middleware would need to distinguish caches by the "Accept-language" header. """ import time from collections import defaultdict from hashlib import md5 from django.conf import settings from django.core.cache import caches from django.http import HttpResponse, HttpResponseNotModified from django.utils.http import http_date, parse_etags, parse_http_date_safe, quote_etag from django.utils.log import log_response from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_current_timezone_name from django.utils.translation import get_language cc_delim_re = _lazy_re_compile(r"\s*,\s*") def patch_cache_control(response, **kwargs): """ Patch the Cache-Control header by adding all keyword arguments to it. The transformation is as follows: * All keyword parameter names are turned to lowercase, and underscores are converted to hyphens. * If the value of a parameter is True (exactly True, not just a true value), only the parameter name is added to the header. * All other parameters are added with their value, after applying str() to it. """ def dictitem(s): t = s.split("=", 1) if len(t) > 1: return (t[0].lower(), t[1]) else: return (t[0].lower(), True) def dictvalue(*t): if t[1] is True: return t[0] else: return "%s=%s" % (t[0], t[1]) cc = defaultdict(set) if response.get("Cache-Control"): for field in cc_delim_re.split(response.headers["Cache-Control"]): directive, value = dictitem(field) if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(value) else: cc[directive] = value # If there's already a max-age header but we're being asked to set a new # max-age, use the minimum of the two ages. In practice this happens when # a decorator and a piece of middleware both operate on a given view. if "max-age" in cc and "max_age" in kwargs: kwargs["max_age"] = min(int(cc["max-age"]), kwargs["max_age"]) # Allow overriding private caching and vice versa if "private" in cc and "public" in kwargs: del cc["private"] elif "public" in cc and "private" in kwargs: del cc["public"] for k, v in kwargs.items(): directive = k.replace("_", "-") if directive == "no-cache": # no-cache supports multiple field names. cc[directive].add(v) else: cc[directive] = v directives = [] for directive, values in cc.items(): if isinstance(values, set): if True in values: # True takes precedence. values = {True} directives.extend([dictvalue(directive, value) for value in values]) else: directives.append(dictvalue(directive, values)) cc = ", ".join(directives) response.headers["Cache-Control"] = cc def get_max_age(response): """ Return the max-age from the response Cache-Control header as an integer, or None if it wasn't found or wasn't an integer. """ if not response.has_header("Cache-Control"): return cc = dict( _to_tuple(el) for el in cc_delim_re.split(response.headers["Cache-Control"]) ) try: return int(cc["max-age"]) except (ValueError, TypeError, KeyError): pass def set_response_etag(response): if not response.streaming and response.content: response.headers["ETag"] = quote_etag( md5(response.content, usedforsecurity=False).hexdigest(), ) return response def _precondition_failed(request): response = HttpResponse(status=412) log_response( "Precondition Failed: %s", request.path, response=response, request=request, ) return response def _not_modified(request, response=None): new_response = HttpResponseNotModified() if response: # Preserve the headers required by RFC 9110 Section 15.4.5, as well as # Last-Modified. for header in ( "Cache-Control", "Content-Location", "Date", "ETag", "Expires", "Last-Modified", "Vary", ): if header in response: new_response.headers[header] = response.headers[header] # Preserve cookies as per the cookie specification: "If a proxy server # receives a response which contains a Set-cookie header, it should # propagate the Set-cookie header to the client, regardless of whether # the response was 304 (Not Modified) or 200 (OK). # https://curl.haxx.se/rfc/cookie_spec.html new_response.cookies = response.cookies return new_response def get_conditional_response(request, etag=None, last_modified=None, response=None): # Only return conditional responses on successful requests. if response and not (200 <= response.status_code < 300): return response # Get HTTP request headers. if_match_etags = parse_etags(request.META.get("HTTP_IF_MATCH", "")) if_unmodified_since = request.META.get("HTTP_IF_UNMODIFIED_SINCE") if_unmodified_since = if_unmodified_since and parse_http_date_safe( if_unmodified_since ) if_none_match_etags = parse_etags(request.META.get("HTTP_IF_NONE_MATCH", "")) if_modified_since = request.META.get("HTTP_IF_MODIFIED_SINCE") if_modified_since = if_modified_since and parse_http_date_safe(if_modified_since) # Evaluation of request preconditions below follows RFC 9110 Section # 13.2.2. # Step 1: Test the If-Match precondition. if if_match_etags and not _if_match_passes(etag, if_match_etags): return _precondition_failed(request) # Step 2: Test the If-Unmodified-Since precondition. if ( not if_match_etags and if_unmodified_since and not _if_unmodified_since_passes(last_modified, if_unmodified_since) ): return _precondition_failed(request) # Step 3: Test the If-None-Match precondition. if if_none_match_etags and not _if_none_match_passes(etag, if_none_match_etags): if request.method in ("GET", "HEAD"): return _not_modified(request, response) else: return _precondition_failed(request) # Step 4: Test the If-Modified-Since precondition. if ( not if_none_match_etags and if_modified_since and not _if_modified_since_passes(last_modified, if_modified_since) and request.method in ("GET", "HEAD") ): return _not_modified(request, response) # Step 5: Test the If-Range precondition (not supported). # Step 6: Return original response since there isn't a conditional # response. return response def _if_match_passes(target_etag, etags): """ Test the If-Match comparison as defined in RFC 9110 Section 13.1.1. """ if not target_etag: # If there isn't an ETag, then there can't be a match. return False elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", even if the ETag is weak, # so there is a match to '*'. return True elif target_etag.startswith("W/"): # A weak ETag can never strongly match another ETag. return False else: # Since the ETag is strong, this will only return True if there's a # strong match. return target_etag in etags def _if_unmodified_since_passes(last_modified, if_unmodified_since): """ Test the If-Unmodified-Since comparison as defined in RFC 9110 Section 13.1.4. """ return last_modified and last_modified <= if_unmodified_since def _if_none_match_passes(target_etag, etags): """ Test the If-None-Match comparison as defined in RFC 9110 Section 13.1.2. """ if not target_etag: # If there isn't an ETag, then there isn't a match. return True elif etags == ["*"]: # The existence of an ETag means that there is "a current # representation for the target resource", so there is a match to '*'. return False else: # The comparison should be weak, so look for a match after stripping # off any weak indicators. target_etag = target_etag.strip("W/") etags = (etag.strip("W/") for etag in etags) return target_etag not in etags def _if_modified_since_passes(last_modified, if_modified_since): """ Test the If-Modified-Since comparison as defined in RFC 9110 Section 13.1.3. """ return not last_modified or last_modified > if_modified_since def patch_response_headers(response, cache_timeout=None): """ Add HTTP caching headers to the given HttpResponse: Expires and Cache-Control. Each header is only added if it isn't already set. cache_timeout is in seconds. The CACHE_MIDDLEWARE_SECONDS setting is used by default. """ if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS if cache_timeout < 0: cache_timeout = 0 # Can't have max-age negative if not response.has_header("Expires"): response.headers["Expires"] = http_date(time.time() + cache_timeout) patch_cache_control(response, max_age=cache_timeout) def add_never_cache_headers(response): """ Add headers to a response to indicate that a page should never be cached. """ patch_response_headers(response, cache_timeout=-1) patch_cache_control( response, no_cache=True, no_store=True, must_revalidate=True, private=True ) def patch_vary_headers(response, newheaders): """ Add (or update) the "Vary" header in the given HttpResponse object. newheaders is a list of header names that should be in "Vary". If headers contains an asterisk, then "Vary" header will consist of a single asterisk '*'. Otherwise, existing headers in "Vary" aren't removed. """ # Note that we need to keep the original order intact, because cache # implementations may rely on the order of the Vary contents in, say, # computing an MD5 hash. if response.has_header("Vary"): vary_headers = cc_delim_re.split(response.headers["Vary"]) else: vary_headers = [] # Use .lower() here so we treat headers as case-insensitive. existing_headers = {header.lower() for header in vary_headers} additional_headers = [ newheader for newheader in newheaders if newheader.lower() not in existing_headers ] vary_headers += additional_headers if "*" in vary_headers: response.headers["Vary"] = "*" else: response.headers["Vary"] = ", ".join(vary_headers) def has_vary_header(response, header_query): """ Check to see if the response has a given header name in its Vary header. """ if not response.has_header("Vary"): return False vary_headers = cc_delim_re.split(response.headers["Vary"]) existing_headers = {header.lower() for header in vary_headers} return header_query.lower() in existing_headers def _i18n_cache_key_suffix(request, cache_key): """If necessary, add the current locale or time zone to the cache key.""" if settings.USE_I18N: # first check if LocaleMiddleware or another middleware added # LANGUAGE_CODE to request, then fall back to the active language # which in turn can also fall back to settings.LANGUAGE_CODE cache_key += ".%s" % getattr(request, "LANGUAGE_CODE", get_language()) if settings.USE_TZ: cache_key += ".%s" % get_current_timezone_name() return cache_key def _generate_cache_key(request, method, headerlist, key_prefix): """Return a cache key from the headers given in the header list.""" ctx = md5(usedforsecurity=False) for header in headerlist: value = request.META.get(header) if value is not None: ctx.update(value.encode()) url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_page.%s.%s.%s.%s" % ( key_prefix, method, url.hexdigest(), ctx.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def _generate_cache_header_key(key_prefix, request): """Return a cache key for the header cache.""" url = md5(request.build_absolute_uri().encode("ascii"), usedforsecurity=False) cache_key = "views.decorators.cache.cache_header.%s.%s" % ( key_prefix, url.hexdigest(), ) return _i18n_cache_key_suffix(request, cache_key) def get_cache_key(request, key_prefix=None, method="GET", cache=None): """ Return a cache key based on the request URL and query. It can be used in the request phase because it pulls the list of headers to take into account from the global URL registry and uses those to build a cache key to check against. If there isn't a headerlist stored, return None, indicating that the page needs to be rebuilt. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] headerlist = cache.get(cache_key) if headerlist is not None: return _generate_cache_key(request, method, headerlist, key_prefix) else: return None def learn_cache_key(request, response, cache_timeout=None, key_prefix=None, cache=None): """ Learn what headers to take into account for some request URL from the response object. Store those headers in a global URL registry so that later access to that URL will know what headers to take into account without building the response object itself. The headers are named in the Vary header of the response, but we want to prevent response generation. The list of headers to use for cache key generation is stored in the same cache as the pages themselves. If the cache ages some data out of the cache, this just means that we have to build the response once to get at the Vary header and so at the list of headers to use for the cache key. """ if key_prefix is None: key_prefix = settings.CACHE_MIDDLEWARE_KEY_PREFIX if cache_timeout is None: cache_timeout = settings.CACHE_MIDDLEWARE_SECONDS cache_key = _generate_cache_header_key(key_prefix, request) if cache is None: cache = caches[settings.CACHE_MIDDLEWARE_ALIAS] if response.has_header("Vary"): is_accept_language_redundant = settings.USE_I18N # If i18n is used, the generated cache key will be suffixed with the # current locale. Adding the raw value of Accept-Language is redundant # in that case and would result in storing the same content under # multiple keys in the cache. See #18191 for details. headerlist = [] for header in cc_delim_re.split(response.headers["Vary"]): header = header.upper().replace("-", "_") if header != "ACCEPT_LANGUAGE" or not is_accept_language_redundant: headerlist.append("HTTP_" + header) headerlist.sort() cache.set(cache_key, headerlist, cache_timeout) return _generate_cache_key(request, request.method, headerlist, key_prefix) else: # if there is no Vary header, we still need a cache key # for the request.build_absolute_uri() cache.set(cache_key, [], cache_timeout) return _generate_cache_key(request, request.method, [], key_prefix) def _to_tuple(s): t = s.split("=", 1) if len(t) == 2: return t[0].lower(), t[1] return t[0].lower(), True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/dateformat.py
django/utils/dateformat.py
""" PHP date() style date formatting See https://www.php.net/date for format strings Usage: >>> from datetime import datetime >>> d = datetime.now() >>> df = DateFormat(d) >>> print(df.format('jS F Y H:i')) 7th October 2003 11:39 >>> """ import calendar from datetime import date, datetime, time from email.utils import format_datetime as format_datetime_rfc5322 from django.utils.dates import ( MONTHS, MONTHS_3, MONTHS_ALT, MONTHS_AP, WEEKDAYS, WEEKDAYS_ABBR, ) from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import ( _datetime_ambiguous_or_imaginary, get_default_timezone, is_naive, make_aware, ) from django.utils.translation import gettext as _ re_formatchars = _lazy_re_compile(r"(?<!\\)([aAbcdDeEfFgGhHiIjlLmMnNoOPrsStTUuwWyYzZ])") re_escaped = _lazy_re_compile(r"\\(.)") class Formatter: def format(self, formatstr): pieces = [] for i, piece in enumerate(re_formatchars.split(str(formatstr))): if i % 2: if type(self.data) is date and hasattr(TimeFormat, piece): raise TypeError( "The format for date objects may not contain " "time-related format specifiers (found '%s')." % piece ) pieces.append(str(getattr(self, piece)())) elif piece: pieces.append(re_escaped.sub(r"\1", piece)) return "".join(pieces) class TimeFormat(Formatter): def __init__(self, obj): self.data = obj self.timezone = None if isinstance(obj, datetime): # Timezone is only supported when formatting datetime objects, not # date objects (timezone information not appropriate), or time # objects (against established django policy). if is_naive(obj): timezone = get_default_timezone() else: timezone = obj.tzinfo if not _datetime_ambiguous_or_imaginary(obj, timezone): self.timezone = timezone def a(self): "'a.m.' or 'p.m.'" if self.data.hour > 11: return _("p.m.") return _("a.m.") def A(self): "'AM' or 'PM'" if self.data.hour > 11: return _("PM") return _("AM") def e(self): """ Timezone name. If timezone information is not available, return an empty string. """ if not self.timezone: return "" try: if getattr(self.data, "tzinfo", None): return self.data.tzname() or "" except NotImplementedError: pass return "" def f(self): """ Time, in 12-hour hours and minutes, with minutes left off if they're zero. Examples: '1', '1:30', '2:05', '2' Proprietary extension. """ hour = self.data.hour % 12 or 12 minute = self.data.minute return "%d:%02d" % (hour, minute) if minute else hour def g(self): "Hour, 12-hour format without leading zeros; i.e. '1' to '12'" return self.data.hour % 12 or 12 def G(self): "Hour, 24-hour format without leading zeros; i.e. '0' to '23'" return self.data.hour def h(self): "Hour, 12-hour format; i.e. '01' to '12'" return "%02d" % (self.data.hour % 12 or 12) def H(self): "Hour, 24-hour format; i.e. '00' to '23'" return "%02d" % self.data.hour def i(self): "Minutes; i.e. '00' to '59'" return "%02d" % self.data.minute def O(self): # NOQA: E743, E741 """ Difference to Greenwich time in hours; e.g. '+0200', '-0430'. If timezone information is not available, return an empty string. """ if self.timezone is None: return "" offset = self.timezone.utcoffset(self.data) seconds = offset.days * 86400 + offset.seconds sign = "-" if seconds < 0 else "+" seconds = abs(seconds) return "%s%02d%02d" % (sign, seconds // 3600, (seconds // 60) % 60) def P(self): """ Time, in 12-hour hours, minutes and 'a.m.'/'p.m.', with minutes left off if they're zero and the strings 'midnight' and 'noon' if appropriate. Examples: '1 a.m.', '1:30 p.m.', 'midnight', 'noon', '12:30 p.m.' Proprietary extension. """ if self.data.minute == 0 and self.data.hour == 0: return _("midnight") if self.data.minute == 0 and self.data.hour == 12: return _("noon") return "%s %s" % (self.f(), self.a()) def s(self): "Seconds; i.e. '00' to '59'" return "%02d" % self.data.second def T(self): """ Time zone of this machine; e.g. 'EST' or 'MDT'. If timezone information is not available, return an empty string. """ if self.timezone is None: return "" return str(self.timezone.tzname(self.data)) def u(self): "Microseconds; i.e. '000000' to '999999'" return "%06d" % self.data.microsecond def Z(self): """ Time zone offset in seconds (i.e. '-43200' to '43200'). The offset for timezones west of UTC is always negative, and for those east of UTC is always positive. If timezone information is not available, return an empty string. """ if self.timezone is None: return "" offset = self.timezone.utcoffset(self.data) # `offset` is a datetime.timedelta. For negative values (to the west of # UTC) only days can be negative (days=-1) and seconds are always # positive. # e.g.: UTC-1 -> timedelta(days=-1, seconds=82800, microseconds=0) # Positive offsets have days=0 return offset.days * 86400 + offset.seconds class DateFormat(TimeFormat): def b(self): "Month, textual, 3 letters, lowercase; e.g. 'jan'" return MONTHS_3[self.data.month] def c(self): """ ISO 8601 Format Example : '2008-01-02T10:30:00.000123' """ return self.data.isoformat() def d(self): "Day of the month, 2 digits with leading zeros; i.e. '01' to '31'" return "%02d" % self.data.day def D(self): "Day of the week, textual, 3 letters; e.g. 'Fri'" return WEEKDAYS_ABBR[self.data.weekday()] def E(self): """ Alternative month names as required by some locales. Proprietary extension. """ return MONTHS_ALT[self.data.month] def F(self): "Month, textual, long; e.g. 'January'" return MONTHS[self.data.month] def I(self): # NOQA: E743, E741 "'1' if daylight saving time, '0' otherwise." if self.timezone is None: return "" return "1" if self.timezone.dst(self.data) else "0" def j(self): "Day of the month without leading zeros; i.e. '1' to '31'" return self.data.day def l(self): # NOQA: E743, E741 "Day of the week, textual, long; e.g. 'Friday'" return WEEKDAYS[self.data.weekday()] def L(self): "Boolean for whether it is a leap year; i.e. True or False" return calendar.isleap(self.data.year) def m(self): "Month; i.e. '01' to '12'" return "%02d" % self.data.month def M(self): "Month, textual, 3 letters; e.g. 'Jan'" return MONTHS_3[self.data.month].title() def n(self): "Month without leading zeros; i.e. '1' to '12'" return self.data.month def N(self): "Month abbreviation in Associated Press style. Proprietary extension." return MONTHS_AP[self.data.month] def o(self): "ISO 8601 year number matching the ISO week number (W)" return self.data.isocalendar().year def r(self): "RFC 5322 formatted date; e.g. 'Thu, 21 Dec 2000 16:01:07 +0200'" value = self.data if not isinstance(value, datetime): # Assume midnight in default timezone if datetime.date provided. default_timezone = get_default_timezone() value = datetime.combine(value, time.min).replace(tzinfo=default_timezone) elif is_naive(value): value = make_aware(value, timezone=self.timezone) return format_datetime_rfc5322(value) def S(self): """ English ordinal suffix for the day of the month, 2 characters; i.e. 'st', 'nd', 'rd' or 'th'. """ if self.data.day in (11, 12, 13): # Special case return "th" last = self.data.day % 10 if last == 1: return "st" if last == 2: return "nd" if last == 3: return "rd" return "th" def t(self): "Number of days in the given month; i.e. '28' to '31'" return calendar.monthrange(self.data.year, self.data.month)[1] def U(self): "Seconds since the Unix epoch (January 1 1970 00:00:00 GMT)" value = self.data if not isinstance(value, datetime): value = datetime.combine(value, time.min) return int(value.timestamp()) def w(self): "Day of the week, numeric, i.e. '0' (Sunday) to '6' (Saturday)" return (self.data.weekday() + 1) % 7 def W(self): "ISO-8601 week number of year, weeks starting on Monday" return self.data.isocalendar().week def y(self): """Year, 2 digits with leading zeros; e.g. '99'.""" return "%02d" % (self.data.year % 100) def Y(self): """Year, 4 digits with leading zeros; e.g. '1999'.""" return "%04d" % self.data.year def z(self): """Day of the year, i.e. 1 to 366.""" return self.data.timetuple().tm_yday def format(value, format_string): "Convenience function" df = DateFormat(value) return df.format(format_string) def time_format(value, format_string): "Convenience function" tf = TimeFormat(value) return tf.format(format_string)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/_os.py
django/utils/_os.py
import os import tempfile from os.path import abspath, dirname, join, normcase, sep from pathlib import Path from django.core.exceptions import SuspiciousFileOperation def safe_join(base, *paths): """ Join one or more path components to the base path component intelligently. Return a normalized, absolute version of the final path. Raise SuspiciousFileOperation if the final path isn't located inside of the base path component. """ final_path = abspath(join(base, *paths)) base_path = abspath(base) # Ensure final_path starts with base_path (using normcase to ensure we # don't false-negative on case insensitive operating systems like Windows), # further, one of the following conditions must be true: # a) The next character is the path separator (to prevent conditions like # safe_join("/dir", "/../d")) # b) The final path must be the same as the base path. # c) The base path must be the most root path (meaning either "/" or # "C:\\") if ( not normcase(final_path).startswith(normcase(base_path + sep)) and normcase(final_path) != normcase(base_path) and dirname(normcase(base_path)) != normcase(base_path) ): raise SuspiciousFileOperation( "The joined path ({}) is located outside of the base path " "component ({})".format(final_path, base_path) ) return final_path def symlinks_supported(): """ Return whether or not creating symlinks are supported in the host platform and/or if they are allowed to be created (e.g. on Windows it requires admin permissions). """ with tempfile.TemporaryDirectory() as temp_dir: original_path = os.path.join(temp_dir, "original") symlink_path = os.path.join(temp_dir, "symlink") os.makedirs(original_path) try: os.symlink(original_path, symlink_path) supported = True except (OSError, NotImplementedError): supported = False return supported def to_path(value): """Convert value to a pathlib.Path instance, if not already a Path.""" if isinstance(value, Path): return value elif not isinstance(value, str): raise TypeError("Invalid path type: %s" % type(value).__name__) return Path(value)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/dateparse.py
django/utils/dateparse.py
"""Functions to parse datetime objects.""" # We're using regular expressions rather than time.strptime because: # - They provide both validation and parsing. # - They're more flexible for datetimes. # - The date/datetime/time constructors produce friendlier error messages. import datetime from django.utils.regex_helper import _lazy_re_compile from django.utils.timezone import get_fixed_timezone date_re = _lazy_re_compile(r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})$") time_re = _lazy_re_compile( r"(?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?$" ) datetime_re = _lazy_re_compile( r"(?P<year>\d{4})-(?P<month>\d{1,2})-(?P<day>\d{1,2})" r"[T ](?P<hour>\d{1,2}):(?P<minute>\d{1,2})" r"(?::(?P<second>\d{1,2})(?:[.,](?P<microsecond>\d{1,6})\d{0,6})?)?" r"\s*(?P<tzinfo>Z|[+-]\d{2}(?::?\d{2})?)?$" ) standard_duration_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days?, )?)?" r"(?P<sign>-?)" r"((?:(?P<hours>\d+):)(?=\d+:\d+))?" r"(?:(?P<minutes>\d+):)?" r"(?P<seconds>\d+)" r"(?:[.,](?P<microseconds>\d{1,6})\d{0,6})?" r"$" ) # Support the sections of ISO 8601 date representation that are accepted by # timedelta iso8601_duration_re = _lazy_re_compile( r"^(?P<sign>[-+]?)" r"P" r"(?:(?P<weeks>\d+([.,]\d+)?)W)?" r"(?:(?P<days>\d+([.,]\d+)?)D)?" r"(?:T" r"(?:(?P<hours>\d+([.,]\d+)?)H)?" r"(?:(?P<minutes>\d+([.,]\d+)?)M)?" r"(?:(?P<seconds>\d+([.,]\d+)?)S)?" r")?" r"$" ) # Support PostgreSQL's day-time interval format, e.g. "3 days 04:05:06". The # year-month and mixed intervals cannot be converted to a timedelta and thus # aren't accepted. postgres_interval_re = _lazy_re_compile( r"^" r"(?:(?P<days>-?\d+) (days? ?))?" r"(?:(?P<sign>[-+])?" r"(?P<hours>\d+):" r"(?P<minutes>\d\d):" r"(?P<seconds>\d\d)" r"(?:\.(?P<microseconds>\d{1,6}))?" r")?$" ) def parse_date(value): """Parse a string and return a datetime.date. Raise ValueError if the input is well formatted but not a valid date. Return None if the input isn't well formatted. """ try: return datetime.date.fromisoformat(value) except ValueError: if match := date_re.match(value): kw = {k: int(v) for k, v in match.groupdict().items()} return datetime.date(**kw) def parse_time(value): """Parse a string and return a datetime.time. This function doesn't support time zone offsets. Raise ValueError if the input is well formatted but not a valid time. Return None if the input isn't well formatted, in particular if it contains an offset. """ try: # The fromisoformat() method takes time zone info into account and # returns a time with a tzinfo component, if possible. However, there # are no circumstances where aware datetime.time objects make sense, so # remove the time zone offset. return datetime.time.fromisoformat(value).replace(tzinfo=None) except ValueError: if match := time_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.time(**kw) def parse_datetime(value): """Parse a string and return a datetime.datetime. This function supports time zone offsets. When the input contains one, the output uses a timezone with a fixed offset from UTC. Raise ValueError if the input is well formatted but not a valid datetime. Return None if the input isn't well formatted. """ try: return datetime.datetime.fromisoformat(value) except ValueError: if match := datetime_re.match(value): kw = match.groupdict() kw["microsecond"] = kw["microsecond"] and kw["microsecond"].ljust(6, "0") tzinfo = kw.pop("tzinfo") if tzinfo == "Z": tzinfo = datetime.UTC elif tzinfo is not None: offset_mins = int(tzinfo[-2:]) if len(tzinfo) > 3 else 0 offset = 60 * int(tzinfo[1:3]) + offset_mins if tzinfo[0] == "-": offset = -offset tzinfo = get_fixed_timezone(offset) kw = {k: int(v) for k, v in kw.items() if v is not None} return datetime.datetime(**kw, tzinfo=tzinfo) def parse_duration(value): """Parse a duration string and return a datetime.timedelta. The preferred format for durations in Django is '%d %H:%M:%S.%f'. Also supports ISO 8601 representation (excluding years and months) and PostgreSQL's day-time interval format. """ match = ( standard_duration_re.match(value) or iso8601_duration_re.match(value) or postgres_interval_re.match(value) ) if match: kw = match.groupdict() sign = -1 if kw.pop("sign", "+") == "-" else 1 if kw.get("microseconds"): kw["microseconds"] = kw["microseconds"].ljust(6, "0") kw = {k: float(v.replace(",", ".")) for k, v in kw.items() if v is not None} days = datetime.timedelta(kw.pop("days", 0.0) or 0.0) if match.re == iso8601_duration_re: days *= sign return days + sign * datetime.timedelta(**kw)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/translation/trans_real.py
django/utils/translation/trans_real.py
"""Translation helper functions.""" import functools import gettext as gettext_module import os import re import sys import warnings from asgiref.local import Local from django.apps import apps from django.conf import settings from django.conf.locale import LANG_INFO from django.core.exceptions import AppRegistryNotReady from django.core.signals import setting_changed from django.dispatch import receiver from django.utils.regex_helper import _lazy_re_compile from django.utils.safestring import SafeData, mark_safe from . import to_language, to_locale # Translations are cached in a dictionary for every language. # The active translations are stored by threadid to make them thread local. _translations = {} _active = Local() # The default translation is based on the settings file. _default = None # magic gettext number to separate context from message CONTEXT_SEPARATOR = "\x04" # Maximum number of characters that will be parsed from the Accept-Language # header or cookie to prevent possible denial of service or memory exhaustion # attacks. About 10x longer than the longest value shown on MDN’s # Accept-Language page. LANGUAGE_CODE_MAX_LENGTH = 500 # Format of Accept-Language header values. From RFC 9110 Sections 12.4.2 and # 12.5.4, and RFC 5646 Section 2.1. accept_language_re = _lazy_re_compile( r""" # "en", "en-au", "x-y-z", "es-419", "*" ([A-Za-z]{1,8}(?:-[A-Za-z0-9]{1,8})*|\*) # Optional "q=1.00", "q=0.8" (?:\s*;\s*q=(0(?:\.[0-9]{,3})?|1(?:\.0{,3})?))? # Multiple accepts per header. (?:\s*,\s*|$) """, re.VERBOSE, ) language_code_re = _lazy_re_compile( r"^[a-z]{1,8}(?:-[a-z0-9]{1,8})*(?:@[a-z0-9]{1,20})?$", re.IGNORECASE ) language_code_prefix_re = _lazy_re_compile(r"^/(\w+([@-]\w+){0,2})(/|$)") @receiver(setting_changed) def reset_cache(*, setting, **kwargs): """ Reset global state when LANGUAGES setting has been changed, as some languages should no longer be accepted. """ if setting in ("LANGUAGES", "LANGUAGE_CODE"): check_for_language.cache_clear() get_languages.cache_clear() get_supported_language_variant.cache_clear() class TranslationCatalog: """ Simulate a dict for DjangoTranslation._catalog so as multiple catalogs with different plural equations are kept separate. """ def __init__(self, trans=None): self._catalogs = [trans._catalog.copy()] if trans else [{}] self._plurals = [trans.plural] if trans else [lambda n: int(n != 1)] def __getitem__(self, key): for cat in self._catalogs: try: return cat[key] except KeyError: pass raise KeyError(key) def __setitem__(self, key, value): self._catalogs[0][key] = value def __contains__(self, key): return any(key in cat for cat in self._catalogs) def items(self): for cat in self._catalogs: yield from cat.items() def keys(self): for cat in self._catalogs: yield from cat.keys() def update(self, trans): # Merge if plural function is the same as the top catalog, else # prepend. if trans.plural.__code__ == self._plurals[0]: self._catalogs[0].update(trans._catalog) else: self._catalogs.insert(0, trans._catalog.copy()) self._plurals.insert(0, trans.plural) def get(self, key, default=None): missing = object() for cat in self._catalogs: result = cat.get(key, missing) if result is not missing: return result return default def plural(self, msgid, num): for cat, plural in zip(self._catalogs, self._plurals): tmsg = cat.get((msgid, plural(num))) if tmsg is not None: return tmsg raise KeyError class DjangoTranslation(gettext_module.GNUTranslations): """ Set up the GNUTranslations context with regard to output charset. This translation object will be constructed out of multiple GNUTranslations objects by merging their catalogs. It will construct an object for the requested language and add a fallback to the default language, if it's different from the requested language. """ domain = "django" def __init__(self, language, domain=None, localedirs=None): """Create a GNUTranslations() using many locale directories""" gettext_module.GNUTranslations.__init__(self) if domain is not None: self.domain = domain self.__language = language self.__to_language = to_language(language) self.__locale = to_locale(language) self._catalog = None # If a language doesn't have a catalog, use the Germanic default for # pluralization: anything except one is pluralized. self.plural = lambda n: int(n != 1) if self.domain == "django": if localedirs is not None: # A module-level cache is used for caching 'django' # translations warnings.warn( "localedirs is ignored when domain is 'django'.", RuntimeWarning ) localedirs = None self._init_translation_catalog() if localedirs: for localedir in localedirs: translation = self._new_gnu_trans(localedir) self.merge(translation) else: self._add_installed_apps_translations() self._add_local_translations() if ( self.__language == settings.LANGUAGE_CODE and self.domain == "django" and self._catalog is None ): # default lang should have at least one translation file available. raise OSError( "No translation files found for default language %s." % settings.LANGUAGE_CODE ) self._add_fallback(localedirs) if self._catalog is None: # No catalogs found for this language, set an empty catalog. self._catalog = TranslationCatalog() def __repr__(self): return "<DjangoTranslation lang:%s>" % self.__language def _new_gnu_trans(self, localedir, use_null_fallback=True): """ Return a mergeable gettext.GNUTranslations instance. A convenience wrapper. By default gettext uses 'fallback=False'. Using param `use_null_fallback` to avoid confusion with any other references to 'fallback'. """ return gettext_module.translation( domain=self.domain, localedir=localedir, languages=[self.__locale], fallback=use_null_fallback, ) def _init_translation_catalog(self): """Create a base catalog using global django translations.""" settingsfile = sys.modules[settings.__module__].__file__ localedir = os.path.join(os.path.dirname(settingsfile), "locale") translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_installed_apps_translations(self): """Merge translations from each installed app.""" try: app_configs = reversed(apps.get_app_configs()) except AppRegistryNotReady: raise AppRegistryNotReady( "The translation infrastructure cannot be initialized before the " "apps registry is ready. Check that you don't make non-lazy " "gettext calls at import time." ) for app_config in app_configs: localedir = os.path.join(app_config.path, "locale") if os.path.exists(localedir): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_local_translations(self): """Merge translations defined in LOCALE_PATHS.""" for localedir in reversed(settings.LOCALE_PATHS): translation = self._new_gnu_trans(localedir) self.merge(translation) def _add_fallback(self, localedirs=None): """Set the GNUTranslations() fallback with the default language.""" # Don't set a fallback for the default language or any English variant # (as it's empty, so it'll ALWAYS fall back to the default language) if self.__language == settings.LANGUAGE_CODE or self.__language.startswith( "en" ): return if self.domain == "django": # Get from cache default_translation = translation(settings.LANGUAGE_CODE) else: default_translation = DjangoTranslation( settings.LANGUAGE_CODE, domain=self.domain, localedirs=localedirs ) self.add_fallback(default_translation) def merge(self, other): """Merge another translation into this catalog.""" if not getattr(other, "_catalog", None): return # NullTranslations() has no _catalog if self._catalog is None: # Take plural and _info from first catalog found (generally # Django's). self.plural = other.plural self._info = other._info.copy() self._catalog = TranslationCatalog(other) else: self._catalog.update(other) if other._fallback: self.add_fallback(other._fallback) def language(self): """Return the translation language.""" return self.__language def to_language(self): """Return the translation language name.""" return self.__to_language def ngettext(self, msgid1, msgid2, n): try: tmsg = self._catalog.plural(msgid1, n) except KeyError: if self._fallback: return self._fallback.ngettext(msgid1, msgid2, n) if n == 1: tmsg = msgid1 else: tmsg = msgid2 return tmsg def translation(language): """ Return a translation object in the default 'django' domain. """ if language not in _translations: _translations[language] = DjangoTranslation(language) return _translations[language] def activate(language): """ Fetch the translation object for a given language and install it as the current translation object for the current thread. """ if not language: return _active.value = translation(language) def deactivate(): """ Uninstall the active translation object so that further _() calls resolve to the default translation object. """ if hasattr(_active, "value"): del _active.value def deactivate_all(): """ Make the active translation object a NullTranslations() instance. This is useful when we want delayed translations to appear as the original string for some reason. """ _active.value = gettext_module.NullTranslations() _active.value.to_language = lambda *args: None def get_language(): """Return the currently selected language.""" t = getattr(_active, "value", None) if t is not None: try: return t.to_language() except AttributeError: pass # If we don't have a real translation object, assume it's the default # language. return settings.LANGUAGE_CODE def get_language_bidi(): """ Return selected language's BiDi layout. * False = left-to-right layout * True = right-to-left layout """ lang = get_language() if lang is None: return False else: base_lang = get_language().split("-")[0] return base_lang in settings.LANGUAGES_BIDI def catalog(): """ Return the current active catalog for further processing. This can be used if you need to modify the catalog or want to access the whole message catalog instead of just translating one string. """ global _default t = getattr(_active, "value", None) if t is not None: return t if _default is None: _default = translation(settings.LANGUAGE_CODE) return _default def gettext(message): """ Translate the 'message' string. It uses the current thread to find the translation object to use. If no current translation is activated, the message will be run through the default translation object. """ global _default eol_message = message.replace("\r\n", "\n").replace("\r", "\n") if eol_message: _default = _default or translation(settings.LANGUAGE_CODE) translation_object = getattr(_active, "value", _default) result = translation_object.gettext(eol_message) else: # Return an empty value of the corresponding type if an empty message # is given, instead of metadata, which is the default gettext behavior. result = type(message)("") if isinstance(message, SafeData): return mark_safe(result) return result def pgettext(context, message): msg_with_ctxt = "%s%s%s" % (context, CONTEXT_SEPARATOR, message) result = gettext(msg_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = message elif isinstance(message, SafeData): result = mark_safe(result) return result def gettext_noop(message): """ Mark strings for translation but don't translate them now. This can be used to store strings in global variables that should stay in the base language (because they might be used externally) and will be translated later. """ return message def do_ntranslate(singular, plural, number, translation_function): global _default t = getattr(_active, "value", None) if t is not None: return getattr(t, translation_function)(singular, plural, number) if _default is None: _default = translation(settings.LANGUAGE_CODE) return getattr(_default, translation_function)(singular, plural, number) def ngettext(singular, plural, number): """ Return a string of the translation of either the singular or plural, based on the number. """ return do_ntranslate(singular, plural, number, "ngettext") def npgettext(context, singular, plural, number): msgs_with_ctxt = ( "%s%s%s" % (context, CONTEXT_SEPARATOR, singular), "%s%s%s" % (context, CONTEXT_SEPARATOR, plural), number, ) result = ngettext(*msgs_with_ctxt) if CONTEXT_SEPARATOR in result: # Translation not found result = ngettext(singular, plural, number) return result def all_locale_paths(): """ Return a list of paths to user-provides languages files. """ globalpath = os.path.join( os.path.dirname(sys.modules[settings.__module__].__file__), "locale" ) app_paths = [] for app_config in apps.get_app_configs(): locale_path = os.path.join(app_config.path, "locale") if os.path.exists(locale_path): app_paths.append(locale_path) return [globalpath, *settings.LOCALE_PATHS, *app_paths] @functools.lru_cache(maxsize=1000) def check_for_language(lang_code): """ Check whether there is a global language file for the given language code. This is used to decide whether a user-provided language is available. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ # First, a quick check to make sure lang_code is well-formed (#21458) if lang_code is None or not language_code_re.search(lang_code): return False return any( gettext_module.find("django", path, [to_locale(lang_code)]) is not None for path in all_locale_paths() ) @functools.lru_cache def get_languages(): """ Cache of settings.LANGUAGES in a dictionary for easy lookups by key. Convert keys to lowercase as they should be treated as case-insensitive. """ return {key.lower(): value for key, value in dict(settings.LANGUAGES).items()} @functools.lru_cache(maxsize=1000) def get_supported_language_variant(lang_code, strict=False): """ Return the language code that's listed in supported languages, possibly selecting a more generic variant. Raise LookupError if nothing is found. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. The language code is truncated to a maximum length to avoid potential denial of service attacks. lru_cache should have a maxsize to prevent from memory exhaustion attacks, as the provided language codes are taken from the HTTP request. See also <https://www.djangoproject.com/weblog/2007/oct/26/security-fix/>. """ if lang_code: # Truncate the language code to a maximum length to avoid potential # denial of service attacks. if len(lang_code) > LANGUAGE_CODE_MAX_LENGTH: if ( not strict and (index := lang_code.rfind("-", 0, LANGUAGE_CODE_MAX_LENGTH)) > 0 ): # There is a generic variant under the maximum length accepted # length. lang_code = lang_code[:index] else: raise LookupError(lang_code) # If 'zh-hant-tw' is not supported, try special fallback or subsequent # language codes i.e. 'zh-hant' and 'zh'. possible_lang_codes = [lang_code] try: possible_lang_codes.extend(LANG_INFO[lang_code]["fallback"]) except KeyError: pass i = None while (i := lang_code.rfind("-", 0, i)) > -1: possible_lang_codes.append(lang_code[:i]) generic_lang_code = possible_lang_codes[-1] supported_lang_codes = get_languages() for code in possible_lang_codes: if code.lower() in supported_lang_codes and check_for_language(code): return code if not strict: # if fr-fr is not supported, try fr-ca. for supported_code in supported_lang_codes: if supported_code.startswith(generic_lang_code + "-"): return supported_code raise LookupError(lang_code) def get_language_from_path(path, strict=False): """ Return the language code if there's a valid language code found in `path`. If `strict` is False (the default), look for a country-specific variant when neither the language code nor its generic variant is found. """ regex_match = language_code_prefix_re.match(path) if not regex_match: return None lang_code = regex_match[1] try: return get_supported_language_variant(lang_code, strict=strict) except LookupError: return None def get_language_from_request(request, check_path=False): """ Analyze the request to find what language the user wants the system to show. Only languages listed in settings.LANGUAGES are taken into account. If the user requests a sublanguage where we have a main language, we send out the main language. If check_path is True, the URL path prefix will be checked for a language code, otherwise this is skipped for backwards compatibility. """ if check_path: lang_code = get_language_from_path(request.path_info) if lang_code is not None: return lang_code lang_code = request.COOKIES.get(settings.LANGUAGE_COOKIE_NAME) if ( lang_code is not None and lang_code in get_languages() and check_for_language(lang_code) ): return lang_code try: return get_supported_language_variant(lang_code) except LookupError: pass accept = request.META.get("HTTP_ACCEPT_LANGUAGE", "") for accept_lang, unused in parse_accept_lang_header(accept): if accept_lang == "*": break if not language_code_re.search(accept_lang): continue try: return get_supported_language_variant(accept_lang) except LookupError: continue try: return get_supported_language_variant(settings.LANGUAGE_CODE) except LookupError: return settings.LANGUAGE_CODE @functools.lru_cache(maxsize=1000) def _parse_accept_lang_header(lang_string): """ Parse the lang_string, which is the body of an HTTP Accept-Language header, and return a tuple of (lang, q-value), ordered by 'q' values. Return an empty tuple if there are any format errors in lang_string. """ result = [] pieces = accept_language_re.split(lang_string.lower()) if pieces[-1]: return () for i in range(0, len(pieces) - 1, 3): first, lang, priority = pieces[i : i + 3] if first: return () if priority: priority = float(priority) else: priority = 1.0 result.append((lang, priority)) result.sort(key=lambda k: k[1], reverse=True) return tuple(result) def parse_accept_lang_header(lang_string): """ Parse the value of the Accept-Language header up to a maximum length. The value of the header is truncated to a maximum length to avoid potential denial of service and memory exhaustion attacks. Excessive memory could be used if the raw value is very large as it would be cached due to the use of functools.lru_cache() to avoid repetitive parsing of common header values. """ # If the header value doesn't exceed the maximum allowed length, parse it. if len(lang_string) <= LANGUAGE_CODE_MAX_LENGTH: return _parse_accept_lang_header(lang_string) # If there is at least one comma in the value, parse up to the last comma # before the max length, skipping any truncated parts at the end of the # header value. if (index := lang_string.rfind(",", 0, LANGUAGE_CODE_MAX_LENGTH)) > 0: return _parse_accept_lang_header(lang_string[:index]) # Don't attempt to parse if there is only one language-range value which is # longer than the maximum allowed length and so truncated. return ()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/translation/template.py
django/utils/translation/template.py
import warnings from io import StringIO from django.template.base import Lexer, TokenType from django.utils.regex_helper import _lazy_re_compile from . import TranslatorCommentWarning, trim_whitespace TRANSLATOR_COMMENT_MARK = "Translators" dot_re = _lazy_re_compile(r"\S") def blankout(src, char): """ Change every non-whitespace character to the given char. Used in the templatize function. """ return dot_re.sub(char, src) context_re = _lazy_re_compile(r"""^\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?'))\s*""") inline_re = _lazy_re_compile( # Match the trans/translate 'some text' part. r"""^\s*trans(?:late)?\s+((?:"[^"]*?")|(?:'[^']*?'))""" # Match and ignore optional filters r"""(?:\s*\|\s*[^\s:]+(?::(?:[^\s'":]+|(?:"[^"]*?")|(?:'[^']*?')))?)*""" # Match the optional context part r"""(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?\s*""" ) block_re = _lazy_re_compile( r"""^\s*blocktrans(?:late)?(\s+.*context\s+((?:"[^"]*?")|(?:'[^']*?')))?(?:\s+|$)""" ) endblock_re = _lazy_re_compile(r"""^\s*endblocktrans(?:late)?$""") plural_re = _lazy_re_compile(r"""^\s*plural$""") constant_re = _lazy_re_compile(r"""_\(((?:".*?")|(?:'.*?'))\)""") def templatize(src, origin=None): """ Turn a Django template into something that is understood by xgettext. It does so by translating the Django translation tags into standard gettext function invocations. """ out = StringIO("") message_context = None intrans = False inplural = False trimmed = False singular = [] plural = [] incomment = False comment = [] lineno_comment_map = {} comment_lineno_cache = None # Adding the u prefix allows gettext to recognize the string (#26093). raw_prefix = "u" def join_tokens(tokens, trim=False): message = "".join(tokens) if trim: message = trim_whitespace(message) return message for t in Lexer(src).tokenize(): if incomment: if t.token_type == TokenType.BLOCK and t.contents == "endcomment": content = "".join(comment) translators_comment_start = None for lineno, line in enumerate(content.splitlines(True)): if line.lstrip().startswith(TRANSLATOR_COMMENT_MARK): translators_comment_start = lineno for lineno, line in enumerate(content.splitlines(True)): if ( translators_comment_start is not None and lineno >= translators_comment_start ): out.write(" # %s" % line) else: out.write(" #\n") incomment = False comment = [] else: comment.append(t.contents) elif intrans: if t.token_type == TokenType.BLOCK: endbmatch = endblock_re.match(t.contents) pluralmatch = plural_re.match(t.contents) if endbmatch: if inplural: if message_context: out.write( " npgettext({p}{!r}, {p}{!r}, {p}{!r},count) ".format( message_context, join_tokens(singular, trimmed), join_tokens(plural, trimmed), p=raw_prefix, ) ) else: out.write( " ngettext({p}{!r}, {p}{!r}, count) ".format( join_tokens(singular, trimmed), join_tokens(plural, trimmed), p=raw_prefix, ) ) for part in singular: out.write(blankout(part, "S")) for part in plural: out.write(blankout(part, "P")) else: if message_context: out.write( " pgettext({p}{!r}, {p}{!r}) ".format( message_context, join_tokens(singular, trimmed), p=raw_prefix, ) ) else: out.write( " gettext({p}{!r}) ".format( join_tokens(singular, trimmed), p=raw_prefix, ) ) for part in singular: out.write(blankout(part, "S")) message_context = None intrans = False inplural = False singular = [] plural = [] elif pluralmatch: inplural = True else: filemsg = "" if origin: filemsg = "file %s, " % origin raise SyntaxError( "Translation blocks must not include other block tags: " "%s (%sline %d)" % (t.contents, filemsg, t.lineno) ) elif t.token_type == TokenType.VAR: if inplural: plural.append("%%(%s)s" % t.contents) else: singular.append("%%(%s)s" % t.contents) elif t.token_type == TokenType.TEXT: contents = t.contents.replace("%", "%%") if inplural: plural.append(contents) else: singular.append(contents) else: # Handle comment tokens (`{# ... #}`) plus other constructs on # the same line: if comment_lineno_cache is not None: cur_lineno = t.lineno + t.contents.count("\n") if comment_lineno_cache == cur_lineno: if t.token_type != TokenType.COMMENT: for c in lineno_comment_map[comment_lineno_cache]: filemsg = "" if origin: filemsg = "file %s, " % origin warn_msg = ( "The translator-targeted comment '%s' " "(%sline %d) was ignored, because it wasn't " "the last item on the line." ) % (c, filemsg, comment_lineno_cache) warnings.warn(warn_msg, TranslatorCommentWarning) lineno_comment_map[comment_lineno_cache] = [] else: out.write( "# %s" % " | ".join(lineno_comment_map[comment_lineno_cache]) ) comment_lineno_cache = None if t.token_type == TokenType.BLOCK: imatch = inline_re.match(t.contents) bmatch = block_re.match(t.contents) cmatches = constant_re.findall(t.contents) if imatch: g = imatch[1] if g[0] == '"': g = g.strip('"') elif g[0] == "'": g = g.strip("'") g = g.replace("%", "%%") if imatch[2]: # A context is provided context_match = context_re.match(imatch[2]) message_context = context_match[1] if message_context[0] == '"': message_context = message_context.strip('"') elif message_context[0] == "'": message_context = message_context.strip("'") out.write( " pgettext({p}{!r}, {p}{!r}) ".format( message_context, g, p=raw_prefix ) ) message_context = None else: out.write(" gettext({p}{!r}) ".format(g, p=raw_prefix)) elif bmatch: for fmatch in constant_re.findall(t.contents): out.write(" _(%s) " % fmatch) if bmatch[1]: # A context is provided context_match = context_re.match(bmatch[1]) message_context = context_match[1] if message_context[0] == '"': message_context = message_context.strip('"') elif message_context[0] == "'": message_context = message_context.strip("'") intrans = True inplural = False trimmed = "trimmed" in t.split_contents() singular = [] plural = [] elif cmatches: for cmatch in cmatches: out.write(" _(%s) " % cmatch) elif t.contents == "comment": incomment = True else: out.write(blankout(t.contents, "B")) elif t.token_type == TokenType.VAR: parts = t.contents.split("|") cmatch = constant_re.match(parts[0]) if cmatch: out.write(" _(%s) " % cmatch[1]) for p in parts[1:]: if p.find(":_(") >= 0: out.write(" %s " % p.split(":", 1)[1]) else: out.write(blankout(p, "F")) elif t.token_type == TokenType.COMMENT: if t.contents.lstrip().startswith(TRANSLATOR_COMMENT_MARK): lineno_comment_map.setdefault(t.lineno, []).append(t.contents) comment_lineno_cache = t.lineno else: out.write(blankout(t.contents, "X")) return out.getvalue()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/translation/__init__.py
django/utils/translation/__init__.py
""" Internationalization support. """ from contextlib import ContextDecorator from decimal import ROUND_UP, Decimal from django.utils.autoreload import autoreload_started, file_changed from django.utils.functional import lazy from django.utils.regex_helper import _lazy_re_compile __all__ = [ "activate", "deactivate", "override", "deactivate_all", "get_language", "get_language_from_request", "get_language_info", "get_language_bidi", "check_for_language", "to_language", "to_locale", "templatize", "gettext", "gettext_lazy", "gettext_noop", "ngettext", "ngettext_lazy", "pgettext", "pgettext_lazy", "npgettext", "npgettext_lazy", ] class TranslatorCommentWarning(SyntaxWarning): pass # Here be dragons, so a short explanation of the logic won't hurt: # We are trying to solve two problems: (1) access settings, in particular # settings.USE_I18N, as late as possible, so that modules can be imported # without having to first configure Django, and (2) if some other code creates # a reference to one of these functions, don't break that reference when we # replace the functions with their real counterparts (once we do access the # settings). class Trans: """ The purpose of this class is to store the actual translation function upon receiving the first call to that function. After this is done, changes to USE_I18N will have no effect to which function is served upon request. If your tests rely on changing USE_I18N, you can delete all the functions from _trans.__dict__. Note that storing the function with setattr will have a noticeable performance effect, as access to the function goes the normal path, instead of using __getattr__. """ def __getattr__(self, real_name): from django.conf import settings if settings.USE_I18N: from django.utils.translation import trans_real as trans from django.utils.translation.reloader import ( translation_file_changed, watch_for_translation_changes, ) autoreload_started.connect( watch_for_translation_changes, dispatch_uid="translation_file_changed" ) file_changed.connect( translation_file_changed, dispatch_uid="translation_file_changed" ) else: from django.utils.translation import trans_null as trans setattr(self, real_name, getattr(trans, real_name)) return getattr(trans, real_name) _trans = Trans() # The Trans class is no more needed, so remove it from the namespace. del Trans def gettext_noop(message): return _trans.gettext_noop(message) def gettext(message): return _trans.gettext(message) def ngettext(singular, plural, number): return _trans.ngettext(singular, plural, number) def pgettext(context, message): return _trans.pgettext(context, message) def npgettext(context, singular, plural, number): return _trans.npgettext(context, singular, plural, number) gettext_lazy = lazy(gettext, str) pgettext_lazy = lazy(pgettext, str) def lazy_number(func, resultclass, number=None, **kwargs): if isinstance(number, int): kwargs["number"] = number proxy = lazy(func, resultclass)(**kwargs) else: original_kwargs = kwargs.copy() class NumberAwareString(resultclass): def __bool__(self): return bool(kwargs["singular"]) def _get_number_value(self, values): try: return values[number] except KeyError: raise KeyError( "Your dictionary lacks key '%s'. Please provide " "it, because it is required to determine whether " "string is singular or plural." % number ) def _translate(self, number_value): kwargs["number"] = number_value return func(**kwargs) def format(self, *args, **kwargs): number_value = ( self._get_number_value(kwargs) if kwargs and number else args[0] ) return self._translate(number_value).format(*args, **kwargs) def __mod__(self, rhs): if isinstance(rhs, dict) and number: number_value = self._get_number_value(rhs) else: number_value = rhs translated = self._translate(number_value) try: translated %= rhs except TypeError: # String doesn't contain a placeholder for the number. pass return translated proxy = lazy(lambda **kwargs: NumberAwareString(), NumberAwareString)(**kwargs) proxy.__reduce__ = lambda: ( _lazy_number_unpickle, (func, resultclass, number, original_kwargs), ) return proxy def _lazy_number_unpickle(func, resultclass, number, kwargs): return lazy_number(func, resultclass, number=number, **kwargs) def ngettext_lazy(singular, plural, number=None): return lazy_number(ngettext, str, singular=singular, plural=plural, number=number) def npgettext_lazy(context, singular, plural, number=None): return lazy_number( npgettext, str, context=context, singular=singular, plural=plural, number=number ) def activate(language): return _trans.activate(language) def deactivate(): return _trans.deactivate() class override(ContextDecorator): def __init__(self, language, deactivate=False): self.language = language self.deactivate = deactivate def __enter__(self): self.old_language = get_language() if self.language is not None: activate(self.language) else: deactivate_all() def __exit__(self, exc_type, exc_value, traceback): if self.old_language is None: deactivate_all() elif self.deactivate: deactivate() else: activate(self.old_language) def get_language(): return _trans.get_language() def get_language_bidi(): return _trans.get_language_bidi() def check_for_language(lang_code): return _trans.check_for_language(lang_code) def to_language(locale): """Turn a locale name (en_US) into a language name (en-us).""" p = locale.find("_") if p >= 0: return locale[:p].lower() + "-" + locale[p + 1 :].lower() else: return locale.lower() def to_locale(language): """Turn a language name (en-us) into a locale name (en_US).""" lang, _, country = language.lower().partition("-") if not country: return language[:3].lower() + language[3:] # A language with > 2 characters after the dash only has its first # character after the dash capitalized; e.g. sr-latn becomes sr_Latn. # A language with 2 characters after the dash has both characters # capitalized; e.g. en-us becomes en_US. country, _, tail = country.partition("-") country = country.title() if len(country) > 2 else country.upper() if tail: country += "-" + tail return lang + "_" + country def get_language_from_request(request, check_path=False): return _trans.get_language_from_request(request, check_path) def get_language_from_path(path): return _trans.get_language_from_path(path) def get_supported_language_variant(lang_code, *, strict=False): return _trans.get_supported_language_variant(lang_code, strict) def templatize(src, **kwargs): from .template import templatize return templatize(src, **kwargs) def deactivate_all(): return _trans.deactivate_all() def get_language_info(lang_code): from django.conf.locale import LANG_INFO try: lang_info = LANG_INFO[lang_code] if "fallback" in lang_info and "name" not in lang_info: info = get_language_info(lang_info["fallback"][0]) else: info = lang_info except KeyError: if "-" not in lang_code: raise KeyError("Unknown language code %s." % lang_code) generic_lang_code = lang_code.split("-")[0] try: info = LANG_INFO[generic_lang_code] except KeyError: raise KeyError( "Unknown language code %s and %s." % (lang_code, generic_lang_code) ) if info: info["name_translated"] = gettext_lazy(info["name"]) return info trim_whitespace_re = _lazy_re_compile(r"\s*\n\s*") def trim_whitespace(s): return trim_whitespace_re.sub(" ", s.strip()) def round_away_from_one(value): return int(Decimal(value - 1).quantize(Decimal("0"), rounding=ROUND_UP)) + 1
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/translation/reloader.py
django/utils/translation/reloader.py
from pathlib import Path from asgiref.local import Local from django.apps import apps from django.utils.autoreload import is_django_module def watch_for_translation_changes(sender, **kwargs): """Register file watchers for .mo files in potential locale paths.""" from django.conf import settings if settings.USE_I18N: directories = [Path("locale")] directories.extend( Path(config.path) / "locale" for config in apps.get_app_configs() if not is_django_module(config.module) ) directories.extend(Path(p) for p in settings.LOCALE_PATHS) for path in directories: sender.watch_dir(path, "**/*.mo") def translation_file_changed(sender, file_path, **kwargs): """Clear the internal translations cache if a .mo file is modified.""" if file_path.suffix == ".mo": import gettext from django.utils.translation import trans_real gettext._translations = {} trans_real._translations = {} trans_real._default = None trans_real._active = Local() return True
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/utils/translation/trans_null.py
django/utils/translation/trans_null.py
# These are versions of the functions in django.utils.translation.trans_real # that don't actually do anything. This is purely for performance, so that # settings.USE_I18N = False can use this module rather than trans_real.py. from django.conf import settings def gettext(message): return message gettext_noop = gettext_lazy = _ = gettext def ngettext(singular, plural, number): if number == 1: return singular return plural ngettext_lazy = ngettext def pgettext(context, message): return gettext(message) def npgettext(context, singular, plural, number): return ngettext(singular, plural, number) def activate(x): return None def deactivate(): return None deactivate_all = deactivate def get_language(): return settings.LANGUAGE_CODE def get_language_bidi(): return settings.LANGUAGE_CODE in settings.LANGUAGES_BIDI def check_for_language(x): return True def get_language_from_request(request, check_path=False): return settings.LANGUAGE_CODE def get_language_from_path(request): return None def get_supported_language_variant(lang_code, strict=False): if lang_code and lang_code.lower() == settings.LANGUAGE_CODE.lower(): return lang_code else: raise LookupError(lang_code)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/defaults.py
django/views/defaults.py
from urllib.parse import quote from django.http import ( HttpResponseBadRequest, HttpResponseForbidden, HttpResponseNotFound, HttpResponseServerError, ) from django.template import Context, Engine, TemplateDoesNotExist, loader from django.views.decorators.csrf import requires_csrf_token ERROR_404_TEMPLATE_NAME = "404.html" ERROR_403_TEMPLATE_NAME = "403.html" ERROR_400_TEMPLATE_NAME = "400.html" ERROR_500_TEMPLATE_NAME = "500.html" ERROR_PAGE_TEMPLATE = """ <!doctype html> <html lang="en"> <head> <title>%(title)s</title> </head> <body> <h1>%(title)s</h1><p>%(details)s</p> </body> </html> """ # These views can be called when CsrfViewMiddleware.process_view() not run, # therefore need @requires_csrf_token in case the template needs # {% csrf_token %}. @requires_csrf_token def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME): """ Default 404 handler. Templates: :template:`404.html` Context: request_path The path of the requested URL (e.g., '/app/pages/bad_page/'). It's quoted to prevent a content injection attack. exception The message from the exception which triggered the 404 (if one was supplied), or the exception class name """ exception_repr = exception.__class__.__name__ # Try to get an "interesting" exception message, if any (and not the ugly # Resolver404 dictionary) try: message = exception.args[0] except (AttributeError, IndexError): pass else: if isinstance(message, str): exception_repr = message context = { "request_path": quote(request.path), "exception": exception_repr, } try: template = loader.get_template(template_name) body = template.render(context, request) except TemplateDoesNotExist: if template_name != ERROR_404_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise # Render template (even though there are no substitutions) to allow # inspecting the context in tests. template = Engine().from_string( ERROR_PAGE_TEMPLATE % { "title": "Not Found", "details": "The requested resource was not found on this server.", }, ) body = template.render(Context(context)) return HttpResponseNotFound(body) @requires_csrf_token def server_error(request, template_name=ERROR_500_TEMPLATE_NAME): """ 500 error handler. Templates: :template:`500.html` Context: None """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_500_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseServerError( ERROR_PAGE_TEMPLATE % {"title": "Server Error (500)", "details": ""}, ) return HttpResponseServerError(template.render()) @requires_csrf_token def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME): """ 400 error handler. Templates: :template:`400.html` Context: None """ try: template = loader.get_template(template_name) body = template.render(request=request) except TemplateDoesNotExist: if template_name != ERROR_400_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseBadRequest( ERROR_PAGE_TEMPLATE % {"title": "Bad Request (400)", "details": ""}, ) # No exception content is passed to the template, to not disclose any # sensitive information. return HttpResponseBadRequest(body) @requires_csrf_token def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME): """ Permission denied (403) handler. Templates: :template:`403.html` Context: exception The message from the exception which triggered the 403 (if one was supplied). If the template does not exist, an Http403 response containing the text "403 Forbidden" (as per RFC 9110 Section 15.5.4) will be returned. """ try: template = loader.get_template(template_name) except TemplateDoesNotExist: if template_name != ERROR_403_TEMPLATE_NAME: # Reraise if it's a missing custom template. raise return HttpResponseForbidden( ERROR_PAGE_TEMPLATE % {"title": "403 Forbidden", "details": ""}, ) return HttpResponseForbidden( template.render(request=request, context={"exception": str(exception)}) )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/debug.py
django/views/debug.py
import functools import inspect import itertools import re import sys import types import warnings from pathlib import Path from django.conf import settings from django.http import Http404, HttpResponse, HttpResponseNotFound from django.template import Context, Engine, TemplateDoesNotExist from django.template.defaultfilters import pprint from django.urls import URLResolver, resolve from django.utils import timezone from django.utils.datastructures import MultiValueDict from django.utils.encoding import force_str from django.utils.module_loading import import_string from django.utils.regex_helper import _lazy_re_compile from django.utils.version import get_docs_version from django.views.decorators.csp import csp_override, csp_report_only_override from django.views.decorators.debug import coroutine_functions_to_sensitive_variables # Minimal Django templates engine to render the error templates # regardless of the project's TEMPLATES setting. Templates are # read directly from the filesystem so that the error handler # works even if the template loader is broken. DEBUG_ENGINE = Engine( debug=True, libraries={"i18n": "django.templatetags.i18n"}, ) def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name class ExceptionCycleWarning(UserWarning): pass class CallableSettingWrapper: """ Object to wrap callable appearing in settings. * Not to call in the debug page (#21345). * Not to break the debug page if the callable forbidding to set attributes (#23070). """ def __init__(self, callable_setting): self._wrapped = callable_setting def __repr__(self): return repr(self._wrapped) @csp_override({}) @csp_report_only_override({}) def technical_500_response(request, exc_type, exc_value, tb, status_code=500): """ Create a technical server error response. The last three arguments are the values returned from sys.exc_info() and friends. """ reporter = get_exception_reporter_class(request)(request, exc_type, exc_value, tb) preferred_type = request.get_preferred_type(["text/html", "text/plain"]) if preferred_type == "text/html": html = reporter.get_traceback_html() return HttpResponse(html, status=status_code, content_type="text/html") else: text = reporter.get_traceback_text() return HttpResponse( text, status=status_code, content_type="text/plain; charset=utf-8" ) @functools.lru_cache def get_default_exception_reporter_filter(): # Instantiate the default filter for the first time and cache it. return import_string(settings.DEFAULT_EXCEPTION_REPORTER_FILTER)() def get_exception_reporter_filter(request): default_filter = get_default_exception_reporter_filter() return getattr(request, "exception_reporter_filter", default_filter) def get_exception_reporter_class(request): default_exception_reporter_class = import_string( settings.DEFAULT_EXCEPTION_REPORTER ) return getattr( request, "exception_reporter_class", default_exception_reporter_class ) def get_caller(request): resolver_match = request.resolver_match if resolver_match is None: try: resolver_match = resolve(request.path) except Http404: pass return "" if resolver_match is None else resolver_match._func_path class SafeExceptionReporterFilter: """ Use annotations made by the sensitive_post_parameters and sensitive_variables decorators to filter out sensitive information. """ cleansed_substitute = "********************" hidden_settings = _lazy_re_compile( "API|AUTH|TOKEN|KEY|SECRET|PASS|SIGNATURE|HTTP_COOKIE", flags=re.I ) def cleanse_setting(self, key, value): """ Cleanse an individual setting key/value of sensitive content. If the value is a dictionary, recursively cleanse the keys in that dictionary. """ if key == settings.SESSION_COOKIE_NAME: is_sensitive = True else: try: is_sensitive = self.hidden_settings.search(key) except TypeError: is_sensitive = False if is_sensitive: cleansed = self.cleansed_substitute elif isinstance(value, dict): cleansed = {k: self.cleanse_setting(k, v) for k, v in value.items()} elif isinstance(value, list): cleansed = [self.cleanse_setting("", v) for v in value] elif isinstance(value, tuple): cleansed = tuple([self.cleanse_setting("", v) for v in value]) else: cleansed = value if callable(cleansed): cleansed = CallableSettingWrapper(cleansed) return cleansed def get_safe_settings(self): """ Return a dictionary of the settings module with values of sensitive settings replaced with stars (*********). """ settings_dict = {} for k in dir(settings): if k.isupper(): settings_dict[k] = self.cleanse_setting(k, getattr(settings, k)) return settings_dict def get_safe_request_meta(self, request): """ Return a dictionary of request.META with sensitive values redacted. """ if not hasattr(request, "META"): return {} return {k: self.cleanse_setting(k, v) for k, v in request.META.items()} def get_safe_cookies(self, request): """ Return a dictionary of request.COOKIES with sensitive values redacted. """ if not hasattr(request, "COOKIES"): return {} return {k: self.cleanse_setting(k, v) for k, v in request.COOKIES.items()} def is_active(self, request): """ This filter is to add safety in production environments (i.e. DEBUG is False). If DEBUG is True then your site is not safe anyway. This hook is provided as a convenience to easily activate or deactivate the filter on a per request basis. """ return settings.DEBUG is False def get_cleansed_multivaluedict(self, request, multivaluedict): """ Replace the keys in a MultiValueDict marked as sensitive with stars. This mitigates leaking sensitive POST parameters if something like request.POST['nonexistent_key'] throws an exception (#21098). """ sensitive_post_parameters = getattr(request, "sensitive_post_parameters", []) if self.is_active(request) and sensitive_post_parameters: multivaluedict = multivaluedict.copy() for param in sensitive_post_parameters: if param in multivaluedict: multivaluedict[param] = self.cleansed_substitute return multivaluedict def get_post_parameters(self, request): """ Replace the values of POST parameters marked as sensitive with stars (*********). """ if request is None: return {} else: sensitive_post_parameters = getattr( request, "sensitive_post_parameters", [] ) if self.is_active(request) and sensitive_post_parameters: cleansed = request.POST.copy() if sensitive_post_parameters == "__ALL__": # Cleanse all parameters. for k in cleansed: cleansed[k] = self.cleansed_substitute return cleansed else: # Cleanse only the specified parameters. for param in sensitive_post_parameters: if param in cleansed: cleansed[param] = self.cleansed_substitute return cleansed else: return request.POST def cleanse_special_types(self, request, value): try: # If value is lazy or a complex object of another kind, this check # might raise an exception. isinstance checks that lazy # MultiValueDicts will have a return value. is_multivalue_dict = isinstance(value, MultiValueDict) except Exception as e: return "{!r} while evaluating {!r}".format(e, value) if is_multivalue_dict: # Cleanse MultiValueDicts (request.POST is the one we usually care # about) value = self.get_cleansed_multivaluedict(request, value) return value def get_traceback_frame_variables(self, request, tb_frame): """ Replace the values of variables marked as sensitive with stars (*********). """ sensitive_variables = None # Coroutines don't have a proper `f_back` so they need to be inspected # separately. Handle this by stashing the registered sensitive # variables in a global dict indexed by `hash(file_path:line_number)`. if ( tb_frame.f_code.co_flags & inspect.CO_COROUTINE != 0 and tb_frame.f_code.co_name != "sensitive_variables_wrapper" ): key = hash( f"{tb_frame.f_code.co_filename}:{tb_frame.f_code.co_firstlineno}" ) sensitive_variables = coroutine_functions_to_sensitive_variables.get( key, None ) if sensitive_variables is None: # Loop through the frame's callers to see if the # sensitive_variables decorator was used. current_frame = tb_frame while current_frame is not None: if ( current_frame.f_code.co_name == "sensitive_variables_wrapper" and "sensitive_variables_wrapper" in current_frame.f_locals ): # The sensitive_variables decorator was used, so take note # of the sensitive variables' names. wrapper = current_frame.f_locals["sensitive_variables_wrapper"] sensitive_variables = getattr(wrapper, "sensitive_variables", None) break current_frame = current_frame.f_back cleansed = {} if self.is_active(request) and sensitive_variables: if sensitive_variables == "__ALL__": # Cleanse all variables for name in tb_frame.f_locals: cleansed[name] = self.cleansed_substitute else: # Cleanse specified variables for name, value in tb_frame.f_locals.items(): if name in sensitive_variables: value = self.cleansed_substitute else: value = self.cleanse_special_types(request, value) cleansed[name] = value else: # Potentially cleanse the request and any MultiValueDicts if they # are one of the frame variables. for name, value in tb_frame.f_locals.items(): cleansed[name] = self.cleanse_special_types(request, value) if ( tb_frame.f_code.co_name == "sensitive_variables_wrapper" and "sensitive_variables_wrapper" in tb_frame.f_locals ): # For good measure, obfuscate the decorated function's arguments in # the sensitive_variables decorator's frame, in case the variables # associated with those arguments were meant to be obfuscated from # the decorated function's frame. cleansed["func_args"] = self.cleansed_substitute cleansed["func_kwargs"] = self.cleansed_substitute return cleansed.items() class ExceptionReporter: """Organize and coordinate reporting on exceptions.""" @property def html_template_path(self): return builtin_template_path("technical_500.html") @property def text_template_path(self): return builtin_template_path("technical_500.txt") def __init__(self, request, exc_type, exc_value, tb, is_email=False): self.request = request self.filter = get_exception_reporter_filter(self.request) self.exc_type = exc_type self.exc_value = exc_value self.tb = tb self.is_email = is_email self.template_info = getattr(self.exc_value, "template_debug", None) self.template_does_not_exist = False self.postmortem = None def _get_raw_insecure_uri(self): """ Return an absolute URI from variables available in this request. Skip allowed hosts protection, so may return insecure URI. """ return "{scheme}://{host}{path}".format( scheme=self.request.scheme, host=self.request._get_raw_host(), path=self.request.get_full_path(), ) def get_traceback_data(self): """Return a dictionary containing traceback information.""" if self.exc_type and issubclass(self.exc_type, TemplateDoesNotExist): self.template_does_not_exist = True self.postmortem = self.exc_value.chain or [self.exc_value] frames = self.get_traceback_frames() for i, frame in enumerate(frames): if "vars" in frame: frame_vars = [] for k, v in frame["vars"]: v = pprint(v) # Trim large blobs of data if len(v) > 4096: v = "%s… <trimmed %d bytes string>" % (v[0:4096], len(v)) frame_vars.append((k, v)) frame["vars"] = frame_vars frames[i] = frame unicode_hint = "" if self.exc_type and issubclass(self.exc_type, UnicodeError): start = getattr(self.exc_value, "start", None) end = getattr(self.exc_value, "end", None) if start is not None and end is not None: unicode_str = self.exc_value.args[1] unicode_hint = force_str( unicode_str[max(start - 5, 0) : min(end + 5, len(unicode_str))], "ascii", errors="replace", ) from django import get_version if self.request is None: user_str = None else: try: user_str = str(self.request.user) except Exception: # request.user may raise OperationalError if the database is # unavailable, for example. user_str = "[unable to retrieve the current user]" c = { "is_email": self.is_email, "unicode_hint": unicode_hint, "frames": frames, "request": self.request, "request_meta": self.filter.get_safe_request_meta(self.request), "request_COOKIES_items": self.filter.get_safe_cookies(self.request).items(), "user_str": user_str, "filtered_POST_items": list( self.filter.get_post_parameters(self.request).items() ), "settings": self.filter.get_safe_settings(), "sys_executable": sys.executable, "sys_version_info": "%d.%d.%d" % sys.version_info[0:3], "server_time": timezone.now(), "django_version_info": get_version(), "sys_path": sys.path, "template_info": self.template_info, "template_does_not_exist": self.template_does_not_exist, "postmortem": self.postmortem, } if self.request is not None: c["request_GET_items"] = self.request.GET.items() c["request_FILES_items"] = self.request.FILES.items() c["request_insecure_uri"] = self._get_raw_insecure_uri() c["raising_view_name"] = get_caller(self.request) # Check whether exception info is available if self.exc_type: c["exception_type"] = self.exc_type.__name__ if self.exc_value: c["exception_value"] = getattr( self.exc_value, "raw_error_message", self.exc_value ) if exc_notes := getattr(self.exc_value, "__notes__", None): c["exception_notes"] = "\n" + "\n".join(exc_notes) if frames: c["lastframe"] = frames[-1] return c def get_traceback_html(self): """Return HTML version of debug 500 HTTP error page.""" with self.html_template_path.open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context(self.get_traceback_data(), use_l10n=False) return t.render(c) def get_traceback_text(self): """Return plain text version of debug 500 HTTP error page.""" with self.text_template_path.open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context(self.get_traceback_data(), autoescape=False, use_l10n=False) return t.render(c) def _get_source(self, filename, loader, module_name): source = None if hasattr(loader, "get_source"): try: source = loader.get_source(module_name) except ImportError: pass if source is not None: source = source.splitlines() if source is None: try: with open(filename, "rb") as fp: source = fp.read().splitlines() except OSError: pass return source def _get_lines_from_file( self, filename, lineno, context_lines, loader=None, module_name=None ): """ Return context_lines before and after lineno from file. Return (pre_context_lineno, pre_context, context_line, post_context). """ source = self._get_source(filename, loader, module_name) if source is None: return None, [], None, [] # If we just read the source from a file, or if the loader did not # apply tokenize.detect_encoding to decode the source into a # string, then we should do that ourselves. if isinstance(source[0], bytes): encoding = "ascii" for line in source[:2]: # File coding may be specified. Match pattern from PEP-263 # (https://www.python.org/dev/peps/pep-0263/) match = re.search(rb"coding[:=]\s*([-\w.]+)", line) if match: encoding = match[1].decode("ascii") break source = [str(sline, encoding, "replace") for sline in source] lower_bound = max(0, lineno - context_lines) upper_bound = lineno + context_lines try: pre_context = source[lower_bound:lineno] context_line = source[lineno] post_context = source[lineno + 1 : upper_bound] except IndexError: return None, [], None, [] return lower_bound, pre_context, context_line, post_context def _get_explicit_or_implicit_cause(self, exc_value): explicit = getattr(exc_value, "__cause__", None) suppress_context = getattr(exc_value, "__suppress_context__", None) implicit = getattr(exc_value, "__context__", None) return explicit or (None if suppress_context else implicit) def get_traceback_frames(self): # Get the exception and all its causes exceptions = [] exc_value = self.exc_value while exc_value: exceptions.append(exc_value) exc_value = self._get_explicit_or_implicit_cause(exc_value) if exc_value in exceptions: warnings.warn( "Cycle in the exception chain detected: exception '%s' " "encountered again." % exc_value, ExceptionCycleWarning, ) # Avoid infinite loop if there's a cyclic reference (#29393). break frames = [] # No exceptions were supplied to ExceptionReporter if not exceptions: return frames # In case there's just one exception, take the traceback from self.tb exc_value = exceptions.pop() tb = self.tb if not exceptions else exc_value.__traceback__ while True: frames.extend(self.get_exception_traceback_frames(exc_value, tb)) try: exc_value = exceptions.pop() except IndexError: break tb = exc_value.__traceback__ return frames def get_exception_traceback_frames(self, exc_value, tb): exc_cause = self._get_explicit_or_implicit_cause(exc_value) exc_cause_explicit = getattr(exc_value, "__cause__", True) if tb is None: yield { "exc_cause": exc_cause, "exc_cause_explicit": exc_cause_explicit, "tb": None, "type": "user", } while tb is not None: # Support for __traceback_hide__ which is used by a few libraries # to hide internal frames. if tb.tb_frame.f_locals.get("__traceback_hide__"): tb = tb.tb_next continue filename = tb.tb_frame.f_code.co_filename function = tb.tb_frame.f_code.co_name lineno = tb.tb_lineno - 1 loader = tb.tb_frame.f_globals.get("__loader__") module_name = tb.tb_frame.f_globals.get("__name__") or "" ( pre_context_lineno, pre_context, context_line, post_context, ) = self._get_lines_from_file( filename, lineno, 7, loader, module_name, ) if pre_context_lineno is None: pre_context_lineno = lineno pre_context = [] context_line = "<source code not available>" post_context = [] colno = tb_area_colno = "" _, _, start_column, end_column = next( itertools.islice( tb.tb_frame.f_code.co_positions(), tb.tb_lasti // 2, None ) ) if start_column and end_column: underline = "^" * (end_column - start_column) spaces = " " * (start_column + len(str(lineno + 1)) + 2) colno = f"\n{spaces}{underline}" tb_area_spaces = " " * ( 4 + start_column - (len(context_line) - len(context_line.lstrip())) ) tb_area_colno = f"\n{tb_area_spaces}{underline}" yield { "exc_cause": exc_cause, "exc_cause_explicit": exc_cause_explicit, "tb": tb, "type": "django" if module_name.startswith("django.") else "user", "filename": filename, "function": function, "lineno": lineno + 1, "vars": self.filter.get_traceback_frame_variables( self.request, tb.tb_frame ), "id": id(tb), "pre_context": pre_context, "context_line": context_line, "post_context": post_context, "pre_context_lineno": pre_context_lineno + 1, "colno": colno, "tb_area_colno": tb_area_colno, } tb = tb.tb_next @csp_override({}) @csp_report_only_override({}) def technical_404_response(request, exception): """Create a technical 404 error response. `exception` is the Http404.""" try: error_url = exception.args[0]["path"] except (IndexError, TypeError, KeyError): error_url = request.path_info[1:] # Trim leading slash try: tried = exception.args[0]["tried"] except (IndexError, TypeError, KeyError): resolved = True tried = request.resolver_match.tried if request.resolver_match else None else: resolved = False if not tried or ( # empty URLconf request.path_info == "/" and len(tried) == 1 and len(tried[0]) == 1 # default URLconf and getattr(tried[0][0], "app_name", "") == getattr(tried[0][0], "namespace", "") == "admin" ): return default_urlconf(request) patterns_with_debug_info = [] for urlpattern in tried or (): patterns = [] for inner_pattern in urlpattern: wrapper = {"tried": inner_pattern} if isinstance(inner_pattern, URLResolver): wrapper["debug_key"] = "namespace" wrapper["debug_val"] = inner_pattern.namespace else: wrapper["debug_key"] = "name" wrapper["debug_val"] = inner_pattern.name patterns.append(wrapper) patterns_with_debug_info.append(patterns) urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF) if isinstance(urlconf, types.ModuleType): urlconf = urlconf.__name__ with builtin_template_path("technical_404.html").open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) reporter_filter = get_default_exception_reporter_filter() c = Context( { "urlconf": urlconf, "root_urlconf": settings.ROOT_URLCONF, "request_path": error_url, "urlpatterns": tried, # Unused, left for compatibility. "urlpatterns_debug": patterns_with_debug_info, "resolved": resolved, "reason": str(exception), "request": request, "settings": reporter_filter.get_safe_settings(), "raising_view_name": get_caller(request), } ) return HttpResponseNotFound(t.render(c)) def default_urlconf(request): """Create an empty URLconf 404 error response.""" with builtin_template_path("default_urlconf.html").open(encoding="utf-8") as fh: t = DEBUG_ENGINE.from_string(fh.read()) c = Context( { "version": get_docs_version(), } ) return HttpResponse(t.render(c))
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/i18n.py
django/views/i18n.py
import json import os import re from pathlib import Path from django.apps import apps from django.conf import settings from django.http import HttpResponse, HttpResponseRedirect, JsonResponse from django.template import Context, Engine from django.urls import translate_url from django.utils.formats import get_format from django.utils.http import url_has_allowed_host_and_scheme from django.utils.translation import check_for_language, get_language from django.utils.translation.trans_real import DjangoTranslation from django.views.generic import View LANGUAGE_QUERY_PARAMETER = "language" def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def set_language(request): """ Redirect to a given URL while setting the chosen language in the language cookie. The URL and the language code need to be specified in the request parameters. Since this view changes how the user will see the rest of the site, it must only be accessed as a POST request. If called as a GET request, it will redirect to the page in the request (the 'next' parameter) without changing any state. """ next_url = request.POST.get("next", request.GET.get("next")) if ( next_url or request.accepts("text/html") ) and not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = request.META.get("HTTP_REFERER") if not url_has_allowed_host_and_scheme( url=next_url, allowed_hosts={request.get_host()}, require_https=request.is_secure(), ): next_url = "/" response = HttpResponseRedirect(next_url) if next_url else HttpResponse(status=204) if request.method == "POST": lang_code = request.POST.get(LANGUAGE_QUERY_PARAMETER) if lang_code and check_for_language(lang_code): if next_url: next_trans = translate_url(next_url, lang_code) if next_trans != next_url: response = HttpResponseRedirect(next_trans) response.set_cookie( settings.LANGUAGE_COOKIE_NAME, lang_code, max_age=settings.LANGUAGE_COOKIE_AGE, path=settings.LANGUAGE_COOKIE_PATH, domain=settings.LANGUAGE_COOKIE_DOMAIN, secure=settings.LANGUAGE_COOKIE_SECURE, httponly=settings.LANGUAGE_COOKIE_HTTPONLY, samesite=settings.LANGUAGE_COOKIE_SAMESITE, ) return response def get_formats(): """Return all formats strings required for i18n to work.""" FORMAT_SETTINGS = ( "DATE_FORMAT", "DATETIME_FORMAT", "TIME_FORMAT", "YEAR_MONTH_FORMAT", "MONTH_DAY_FORMAT", "SHORT_DATE_FORMAT", "SHORT_DATETIME_FORMAT", "FIRST_DAY_OF_WEEK", "DECIMAL_SEPARATOR", "THOUSAND_SEPARATOR", "NUMBER_GROUPING", "DATE_INPUT_FORMATS", "TIME_INPUT_FORMATS", "DATETIME_INPUT_FORMATS", ) return {attr: get_format(attr) for attr in FORMAT_SETTINGS} class JavaScriptCatalog(View): """ Return the selected language catalog as a JavaScript library. Receive the list of packages to check for translations in the `packages` kwarg either from the extra dictionary passed to the path() function or as a plus-sign delimited string from the request. Default is 'django.conf'. You can override the gettext domain for this view, but usually you don't want to do that as JavaScript messages go to the djangojs domain. This might be needed if you deliver your JavaScript source from Django templates. """ domain = "djangojs" packages = None def get(self, request, *args, **kwargs): locale = get_language() domain = kwargs.get("domain", self.domain) # If packages are not provided, default to all installed packages, as # DjangoTranslation without localedirs harvests them all. packages = kwargs.get("packages", "") packages = packages.split("+") if packages else self.packages paths = self.get_paths(packages) if packages else None self.translation = DjangoTranslation(locale, domain=domain, localedirs=paths) context = self.get_context_data(**kwargs) return self.render_to_response(context) def get_paths(self, packages): allowable_packages = { app_config.name: app_config for app_config in apps.get_app_configs() } app_configs = [ allowable_packages[p] for p in packages if p in allowable_packages ] if len(app_configs) < len(packages): excluded = [p for p in packages if p not in allowable_packages] raise ValueError( "Invalid package(s) provided to JavaScriptCatalog: %s" % ",".join(excluded) ) # paths of requested packages return [os.path.join(app.path, "locale") for app in app_configs] @property def _num_plurals(self): """ Return the number of plurals for this catalog language, or 2 if no plural string is available. """ match = re.search(r"nplurals=\s*(\d+)", self._plural_string or "") if match: return int(match[1]) return 2 @property def _plural_string(self): """ Return the plural string (including nplurals) for this catalog language, or None if no plural string is available. """ if "" in self.translation._catalog: for line in self.translation._catalog[""].split("\n"): if line.startswith("Plural-Forms:"): return line.split(":", 1)[1].strip() return None def get_plural(self): plural = self._plural_string if plural is not None: # This should be a compiled function of a typical plural-form: # Plural-Forms: nplurals=3; plural=n%10==1 && n%100!=11 ? 0 : # n%10>=2 && n%10<=4 && (n%100<10 || n%100>=20) # ? 1 : 2; plural = [ el.strip() for el in plural.split(";") if el.strip().startswith("plural=") ][0].split("=", 1)[1] return plural def get_catalog(self): pdict = {} catalog = {} translation = self.translation seen_keys = set() while True: for key, value in translation._catalog.items(): if key == "" or key in seen_keys: continue if isinstance(key, str): catalog[key] = value elif isinstance(key, tuple): msgid, cnt = key pdict.setdefault(msgid, {})[cnt] = value else: raise TypeError(key) seen_keys.add(key) if translation._fallback: translation = translation._fallback else: break num_plurals = self._num_plurals for k, v in pdict.items(): catalog[k] = [v.get(i, "") for i in range(num_plurals)] return catalog def get_context_data(self, **kwargs): return { "catalog": self.get_catalog(), "formats": get_formats(), "plural": self.get_plural(), } def render_to_response(self, context, **response_kwargs): def indent(s): return s.replace("\n", "\n ") with builtin_template_path("i18n_catalog.js").open(encoding="utf-8") as fh: template = Engine().from_string(fh.read()) context["catalog_str"] = ( indent(json.dumps(context["catalog"], sort_keys=True, indent=2)) if context["catalog"] else None ) context["formats_str"] = indent( json.dumps(context["formats"], sort_keys=True, indent=2) ) return HttpResponse( template.render(Context(context)), 'text/javascript; charset="utf-8"' ) class JSONCatalog(JavaScriptCatalog): """ Return the selected language catalog as a JSON object. Receive the same parameters as JavaScriptCatalog and return a response with a JSON object of the following format: { "catalog": { # Translations catalog }, "formats": { # Language formats for date, time, etc. }, "plural": '...' # Expression for plural forms, or null. } """ def render_to_response(self, context, **response_kwargs): return JsonResponse(context)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/__init__.py
django/views/__init__.py
from django.views.generic.base import View __all__ = ["View"]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/csrf.py
django/views/csrf.py
from pathlib import Path from django.conf import settings from django.http import HttpResponseForbidden from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils.translation import gettext as _ from django.utils.version import get_docs_version CSRF_FAILURE_TEMPLATE_NAME = "403_csrf.html" def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def csrf_failure(request, reason="", template_name=CSRF_FAILURE_TEMPLATE_NAME): """ Default view used when request fails CSRF protection """ from django.middleware.csrf import REASON_NO_CSRF_COOKIE, REASON_NO_REFERER c = { "title": _("Forbidden"), "main": _("CSRF verification failed. Request aborted."), "reason": reason, "no_referer": reason == REASON_NO_REFERER, "no_referer1": _( "You are seeing this message because this HTTPS site requires a " "“Referer header” to be sent by your web browser, but none was " "sent. This header is required for security reasons, to ensure " "that your browser is not being hijacked by third parties." ), "no_referer2": _( "If you have configured your browser to disable “Referer” headers, " "please re-enable them, at least for this site, or for HTTPS " "connections, or for “same-origin” requests." ), "no_referer3": _( 'If you are using the <meta name="referrer" ' 'content="no-referrer"> tag or including the “Referrer-Policy: ' "no-referrer” header, please remove them. The CSRF protection " "requires the “Referer” header to do strict referer checking. If " "you’re concerned about privacy, use alternatives like " '<a rel="noreferrer" …> for links to third-party sites.' ), "no_cookie": reason == REASON_NO_CSRF_COOKIE, "no_cookie1": _( "You are seeing this message because this site requires a CSRF " "cookie when submitting forms. This cookie is required for " "security reasons, to ensure that your browser is not being " "hijacked by third parties." ), "no_cookie2": _( "If you have configured your browser to disable cookies, please " "re-enable them, at least for this site, or for “same-origin” " "requests." ), "DEBUG": settings.DEBUG, "docs_version": get_docs_version(), "more": _("More information is available with DEBUG=True."), } try: t = loader.get_template(template_name) body = t.render(request=request) except TemplateDoesNotExist: if template_name == CSRF_FAILURE_TEMPLATE_NAME: # If the default template doesn't exist, use the fallback template. with builtin_template_path("csrf_403.html").open(encoding="utf-8") as fh: t = Engine().from_string(fh.read()) body = t.render(Context(c)) else: # Raise if a developer-specified template doesn't exist. raise return HttpResponseForbidden(body)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/static.py
django/views/static.py
""" Views and functions for serving static files. These are only to be used during development, and SHOULD NOT be used in a production setting. """ import mimetypes import posixpath from pathlib import Path from django.http import FileResponse, Http404, HttpResponse, HttpResponseNotModified from django.template import Context, Engine, TemplateDoesNotExist, loader from django.utils._os import safe_join from django.utils.http import http_date, parse_http_date from django.utils.translation import gettext as _ from django.utils.translation import gettext_lazy def builtin_template_path(name): """ Return a path to a builtin template. Avoid calling this function at the module level or in a class-definition because __file__ may not exist, e.g. in frozen environments. """ return Path(__file__).parent / "templates" / name def serve(request, path, document_root=None, show_indexes=False): """ Serve static files below a given point in the directory structure. To use, put a URL pattern such as:: from django.views.static import serve path('<path:path>', serve, {'document_root': '/path/to/my/files/'}) in your URLconf. You must provide the ``document_root`` param. You may also set ``show_indexes`` to ``True`` if you'd like to serve a basic index of the directory. This index view will use the template hardcoded below, but if you'd like to override it, you can create a template called ``static/directory_index.html``. """ path = posixpath.normpath(path).lstrip("/") fullpath = Path(safe_join(document_root, path)) if fullpath.is_dir(): if show_indexes: return directory_index(path, fullpath) raise Http404(_("Directory indexes are not allowed here.")) if not fullpath.exists(): raise Http404(_("“%(path)s” does not exist") % {"path": fullpath}) # Respect the If-Modified-Since header. statobj = fullpath.stat() if not was_modified_since( request.META.get("HTTP_IF_MODIFIED_SINCE"), statobj.st_mtime ): return HttpResponseNotModified() content_type, encoding = mimetypes.guess_type(str(fullpath)) content_type = content_type or "application/octet-stream" response = FileResponse(fullpath.open("rb"), content_type=content_type) response.headers["Last-Modified"] = http_date(statobj.st_mtime) if encoding: response.headers["Content-Encoding"] = encoding return response # Translatable string for static directory index template title. template_translatable = gettext_lazy("Index of %(directory)s") def directory_index(path, fullpath): try: t = loader.select_template( [ "static/directory_index.html", "static/directory_index", ] ) except TemplateDoesNotExist: with builtin_template_path("directory_index.html").open(encoding="utf-8") as fh: t = Engine(libraries={"i18n": "django.templatetags.i18n"}).from_string( fh.read() ) c = Context() else: c = {} files = [] for f in fullpath.iterdir(): if not f.name.startswith("."): url = str(f.relative_to(fullpath)) if f.is_dir(): url += "/" files.append(url) c.update( { "directory": path + "/", "file_list": files, } ) return HttpResponse(t.render(c)) def was_modified_since(header=None, mtime=0): """ Was something modified since the user last downloaded it? header This is the value of the If-Modified-Since header. If this is None, I'll just return True. mtime This is the modification time of the item we're talking about. """ try: if header is None: raise ValueError header_mtime = parse_http_date(header) if int(mtime) > header_mtime: raise ValueError except (ValueError, OverflowError): return True return False
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/vary.py
django/views/decorators/vary.py
from functools import wraps from asgiref.sync import iscoroutinefunction from django.utils.cache import patch_vary_headers def vary_on_headers(*headers): """ A view decorator that adds the specified headers to the Vary header of the response. Usage: @vary_on_headers('Cookie', 'Accept-language') def index(request): ... Note that the header names are not case-sensitive. """ def decorator(func): if iscoroutinefunction(func): async def _view_wrapper(request, *args, **kwargs): response = await func(request, *args, **kwargs) patch_vary_headers(response, headers) return response else: def _view_wrapper(request, *args, **kwargs): response = func(request, *args, **kwargs) patch_vary_headers(response, headers) return response return wraps(func)(_view_wrapper) return decorator vary_on_cookie = vary_on_headers("Cookie") vary_on_cookie.__doc__ = ( 'A view decorator that adds "Cookie" to the Vary header of a response. This ' "indicates that a page's contents depends on cookies." )
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/csp.py
django/views/decorators/csp.py
from functools import wraps from asgiref.sync import iscoroutinefunction def _make_csp_decorator(config_attr_name, config_attr_value): """General CSP override decorator factory.""" if not isinstance(config_attr_value, dict): raise TypeError("CSP config should be a mapping.") def decorator(view_func): @wraps(view_func) async def _wrapped_async_view(request, *args, **kwargs): response = await view_func(request, *args, **kwargs) setattr(response, config_attr_name, config_attr_value) return response @wraps(view_func) def _wrapped_sync_view(request, *args, **kwargs): response = view_func(request, *args, **kwargs) setattr(response, config_attr_name, config_attr_value) return response if iscoroutinefunction(view_func): return _wrapped_async_view return _wrapped_sync_view return decorator def csp_override(config): """Override the Content-Security-Policy header for a view.""" return _make_csp_decorator("_csp_config", config) def csp_report_only_override(config): """Override the Content-Security-Policy-Report-Only header for a view.""" return _make_csp_decorator("_csp_ro_config", config)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/http.py
django/views/decorators/http.py
""" Decorators for views based on HTTP headers. """ import datetime from functools import wraps from asgiref.sync import iscoroutinefunction from django.http import HttpResponseNotAllowed from django.middleware.http import ConditionalGetMiddleware from django.utils import timezone from django.utils.cache import get_conditional_response from django.utils.decorators import decorator_from_middleware from django.utils.http import http_date, quote_etag from django.utils.log import log_response conditional_page = decorator_from_middleware(ConditionalGetMiddleware) def require_http_methods(request_method_list): """ Decorator to make a view only accept particular request methods. Usage:: @require_http_methods(["GET", "POST"]) def my_view(request): # I can assume now that only GET or POST requests make it this far # ... Note that request methods should be in uppercase. """ def decorator(func): if iscoroutinefunction(func): @wraps(func) async def inner(request, *args, **kwargs): if request.method not in request_method_list: response = HttpResponseNotAllowed(request_method_list) log_response( "Method Not Allowed (%s): %s", request.method, request.path, response=response, request=request, ) return response return await func(request, *args, **kwargs) else: @wraps(func) def inner(request, *args, **kwargs): if request.method not in request_method_list: response = HttpResponseNotAllowed(request_method_list) log_response( "Method Not Allowed (%s): %s", request.method, request.path, response=response, request=request, ) return response return func(request, *args, **kwargs) return inner return decorator require_GET = require_http_methods(["GET"]) require_GET.__doc__ = "Decorator to require that a view only accepts the GET method." require_POST = require_http_methods(["POST"]) require_POST.__doc__ = "Decorator to require that a view only accepts the POST method." require_safe = require_http_methods(["GET", "HEAD"]) require_safe.__doc__ = ( "Decorator to require that a view only accepts safe methods: GET and HEAD." ) def condition(etag_func=None, last_modified_func=None): """ Decorator to support conditional retrieval (or change) for a view function. The parameters are callables to compute the ETag and last modified time for the requested resource, respectively. The callables are passed the same parameters as the view itself. The ETag function should return a string (or None if the resource doesn't exist), while the last_modified function should return a datetime object (or None if the resource doesn't exist). The ETag function should return a complete ETag, including quotes (e.g. '"etag"'), since that's the only way to distinguish between weak and strong ETags. If an unquoted ETag is returned (e.g. 'etag'), it will be converted to a strong ETag by adding quotes. This decorator will either pass control to the wrapped view function or return an HTTP 304 response (unmodified) or 412 response (precondition failed), depending upon the request method. In either case, the decorator will add the generated ETag and Last-Modified headers to the response if the headers aren't already set and if the request's method is safe. """ def decorator(func): def _pre_process_request(request, *args, **kwargs): # Compute values (if any) for the requested resource. res_last_modified = None if last_modified_func: if dt := last_modified_func(request, *args, **kwargs): if not timezone.is_aware(dt): dt = timezone.make_aware(dt, datetime.UTC) res_last_modified = int(dt.timestamp()) # The value from etag_func() could be quoted or unquoted. res_etag = etag_func(request, *args, **kwargs) if etag_func else None res_etag = quote_etag(res_etag) if res_etag is not None else None response = get_conditional_response( request, etag=res_etag, last_modified=res_last_modified, ) return response, res_etag, res_last_modified def _post_process_request(request, response, res_etag, res_last_modified): # Set relevant headers on the response if they don't already exist # and if the request method is safe. if request.method in ("GET", "HEAD"): if res_last_modified and not response.has_header("Last-Modified"): response.headers["Last-Modified"] = http_date(res_last_modified) if res_etag: response.headers.setdefault("ETag", res_etag) if iscoroutinefunction(func): @wraps(func) async def inner(request, *args, **kwargs): response, res_etag, res_last_modified = _pre_process_request( request, *args, **kwargs ) if response is None: response = await func(request, *args, **kwargs) _post_process_request(request, response, res_etag, res_last_modified) return response else: @wraps(func) def inner(request, *args, **kwargs): response, res_etag, res_last_modified = _pre_process_request( request, *args, **kwargs ) if response is None: response = func(request, *args, **kwargs) _post_process_request(request, response, res_etag, res_last_modified) return response return inner return decorator # Shortcut decorators for common cases based on ETag or Last-Modified only def etag(etag_func): return condition(etag_func=etag_func) def last_modified(last_modified_func): return condition(last_modified_func=last_modified_func)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/debug.py
django/views/decorators/debug.py
import inspect from functools import wraps from asgiref.sync import iscoroutinefunction from django.http import HttpRequest coroutine_functions_to_sensitive_variables = {} def sensitive_variables(*variables): """ Indicate which variables used in the decorated function are sensitive so that those variables can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified variable names: @sensitive_variables('user', 'password', 'credit_card') def my_function(user): password = user.pass_word credit_card = user.credit_card_number ... * without any specified variable names, in which case consider all variables are sensitive: @sensitive_variables() def my_function() ... """ if len(variables) == 1 and callable(variables[0]): raise TypeError( "sensitive_variables() must be called to use it as a decorator, " "e.g., use @sensitive_variables(), not @sensitive_variables." ) def decorator(func): if iscoroutinefunction(func): sensitive_variables_wrapper = func wrapped_func = func while getattr(wrapped_func, "__wrapped__", None) is not None: wrapped_func = wrapped_func.__wrapped__ try: file_path = inspect.getfile(wrapped_func) except TypeError: # Raises for builtins or native functions. raise ValueError( f"{func.__name__} cannot safely be wrapped by " "@sensitive_variables, make it either non-async or defined in a " "Python file (not a builtin or from a native extension)." ) else: # A source file may not be available (e.g. in .pyc-only # builds), use the first line number instead. first_line_number = wrapped_func.__code__.co_firstlineno key = hash(f"{file_path}:{first_line_number}") if variables: coroutine_functions_to_sensitive_variables[key] = variables else: coroutine_functions_to_sensitive_variables[key] = "__ALL__" else: @wraps(func) def sensitive_variables_wrapper(*func_args, **func_kwargs): if variables: sensitive_variables_wrapper.sensitive_variables = variables else: sensitive_variables_wrapper.sensitive_variables = "__ALL__" return func(*func_args, **func_kwargs) return sensitive_variables_wrapper return decorator def sensitive_post_parameters(*parameters): """ Indicate which POST parameters used in the decorated view are sensitive, so that those parameters can later be treated in a special way, for example by hiding them when logging unhandled exceptions. Accept two forms: * with specified parameters: @sensitive_post_parameters('password', 'credit_card') def my_view(request): pw = request.POST['password'] cc = request.POST['credit_card'] ... * without any specified parameters, in which case consider all variables are sensitive: @sensitive_post_parameters() def my_view(request) ... """ if len(parameters) == 1 and callable(parameters[0]): raise TypeError( "sensitive_post_parameters() must be called to use it as a " "decorator, e.g., use @sensitive_post_parameters(), not " "@sensitive_post_parameters." ) def decorator(view): if iscoroutinefunction(view): @wraps(view) async def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure to use " "@method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = "__ALL__" return await view(request, *args, **kwargs) else: @wraps(view) def sensitive_post_parameters_wrapper(request, *args, **kwargs): if not isinstance(request, HttpRequest): raise TypeError( "sensitive_post_parameters didn't receive an HttpRequest " "object. If you are decorating a classmethod, make sure to use " "@method_decorator." ) if parameters: request.sensitive_post_parameters = parameters else: request.sensitive_post_parameters = "__ALL__" return view(request, *args, **kwargs) return sensitive_post_parameters_wrapper return decorator
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/common.py
django/views/decorators/common.py
from functools import wraps from asgiref.sync import iscoroutinefunction def no_append_slash(view_func): """ Mark a view function as excluded from CommonMiddleware's APPEND_SLASH redirection. """ # view_func.should_append_slash = False would also work, but decorators are # nicer if they don't have side effects, so return a new function. if iscoroutinefunction(view_func): async def _view_wrapper(request, *args, **kwargs): return await view_func(request, *args, **kwargs) else: def _view_wrapper(request, *args, **kwargs): return view_func(request, *args, **kwargs) _view_wrapper.should_append_slash = False return wraps(view_func)(_view_wrapper)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/gzip.py
django/views/decorators/gzip.py
from django.middleware.gzip import GZipMiddleware from django.utils.decorators import decorator_from_middleware gzip_page = decorator_from_middleware(GZipMiddleware) gzip_page.__doc__ = "Decorator for views that gzips pages if the client supports it."
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/clickjacking.py
django/views/decorators/clickjacking.py
from functools import wraps from asgiref.sync import iscoroutinefunction def xframe_options_deny(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'DENY' as long as the response doesn't already have that header set. Usage: @xframe_options_deny def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "DENY" return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "DENY" return response return wraps(view_func)(_view_wrapper) def xframe_options_sameorigin(view_func): """ Modify a view function so its response has the X-Frame-Options HTTP header set to 'SAMEORIGIN' as long as the response doesn't already have that header set. Usage: @xframe_options_sameorigin def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "SAMEORIGIN" return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) if response.get("X-Frame-Options") is None: response["X-Frame-Options"] = "SAMEORIGIN" return response return wraps(view_func)(_view_wrapper) def xframe_options_exempt(view_func): """ Modify a view function by setting a response variable that instructs XFrameOptionsMiddleware to NOT set the X-Frame-Options HTTP header. Usage: @xframe_options_exempt def some_view(request): ... """ if iscoroutinefunction(view_func): async def _view_wrapper(*args, **kwargs): response = await view_func(*args, **kwargs) response.xframe_options_exempt = True return response else: def _view_wrapper(*args, **kwargs): response = view_func(*args, **kwargs) response.xframe_options_exempt = True return response return wraps(view_func)(_view_wrapper)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/__init__.py
django/views/decorators/__init__.py
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/csrf.py
django/views/decorators/csrf.py
from functools import wraps from asgiref.sync import iscoroutinefunction from django.middleware.csrf import CsrfViewMiddleware, get_token from django.utils.decorators import decorator_from_middleware csrf_protect = decorator_from_middleware(CsrfViewMiddleware) csrf_protect.__name__ = "csrf_protect" csrf_protect.__doc__ = """ This decorator adds CSRF protection in exactly the same way as CsrfViewMiddleware, but it can be used on a per view basis. Using both, or using the decorator multiple times, is harmless and efficient. """ class _EnsureCsrfToken(CsrfViewMiddleware): # Behave like CsrfViewMiddleware but don't reject requests or log warnings. def _reject(self, request, reason): return None requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken) requires_csrf_token.__name__ = "requires_csrf_token" requires_csrf_token.__doc__ = """ Use this decorator on views that need a correct csrf_token available to RequestContext, but without the CSRF protection that csrf_protect enforces. """ class _EnsureCsrfCookie(CsrfViewMiddleware): def _reject(self, request, reason): return None def process_view(self, request, callback, callback_args, callback_kwargs): retval = super().process_view(request, callback, callback_args, callback_kwargs) # Force process_response to send the cookie get_token(request) return retval ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie) ensure_csrf_cookie.__name__ = "ensure_csrf_cookie" ensure_csrf_cookie.__doc__ = """ Use this decorator to ensure that a view sets a CSRF cookie, whether or not it uses the csrf_token template tag, or the CsrfViewMiddleware is used. """ def csrf_exempt(view_func): """Mark a view function as being exempt from the CSRF view protection.""" # view_func.csrf_exempt = True would also work, but decorators are nicer # if they don't have side effects, so return a new function. if iscoroutinefunction(view_func): async def _view_wrapper(request, *args, **kwargs): return await view_func(request, *args, **kwargs) else: def _view_wrapper(request, *args, **kwargs): return view_func(request, *args, **kwargs) _view_wrapper.csrf_exempt = True return wraps(view_func)(_view_wrapper)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/decorators/cache.py
django/views/decorators/cache.py
from functools import wraps from asgiref.sync import iscoroutinefunction from django.middleware.cache import CacheMiddleware from django.utils.cache import add_never_cache_headers, patch_cache_control from django.utils.decorators import decorator_from_middleware_with_args def cache_page(timeout, *, cache=None, key_prefix=None): """ Decorator for views that tries getting the page from the cache and populates the cache if the page isn't in the cache yet. The cache is keyed by the URL and some data from the headers. Additionally there is the key prefix that is used to distinguish different cache areas in a multi-site setup. You could use the get_current_site().domain, for example, as that is unique across a Django project. Additionally, all headers from the response's Vary header will be taken into account on caching -- just like the middleware does. """ return decorator_from_middleware_with_args(CacheMiddleware)( page_timeout=timeout, cache_alias=cache, key_prefix=key_prefix, ) def _check_request(request, decorator_name): # Ensure argument looks like a request. if not hasattr(request, "META"): raise TypeError( f"{decorator_name} didn't receive an HttpRequest. If you are " "decorating a classmethod, be sure to use @method_decorator." ) def cache_control(**kwargs): def _cache_controller(viewfunc): if iscoroutinefunction(viewfunc): async def _view_wrapper(request, *args, **kw): _check_request(request, "cache_control") response = await viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response else: def _view_wrapper(request, *args, **kw): _check_request(request, "cache_control") response = viewfunc(request, *args, **kw) patch_cache_control(response, **kwargs) return response return wraps(viewfunc)(_view_wrapper) return _cache_controller def never_cache(view_func): """ Decorator that adds headers to a response so that it will never be cached. """ if iscoroutinefunction(view_func): async def _view_wrapper(request, *args, **kwargs): _check_request(request, "never_cache") response = await view_func(request, *args, **kwargs) add_never_cache_headers(response) return response else: def _view_wrapper(request, *args, **kwargs): _check_request(request, "never_cache") response = view_func(request, *args, **kwargs) add_never_cache_headers(response) return response return wraps(view_func)(_view_wrapper)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/edit.py
django/views/generic/edit.py
from django.core.exceptions import ImproperlyConfigured from django.forms import Form from django.forms import models as model_forms from django.http import HttpResponseRedirect from django.views.generic.base import ContextMixin, TemplateResponseMixin, View from django.views.generic.detail import ( BaseDetailView, SingleObjectMixin, SingleObjectTemplateResponseMixin, ) class FormMixin(ContextMixin): """Provide a way to show and handle a form in a request.""" initial = {} form_class = None success_url = None prefix = None def get_initial(self): """Return the initial data to use for forms on this view.""" return self.initial.copy() def get_prefix(self): """Return the prefix to use for forms.""" return self.prefix def get_form_class(self): """Return the form class to use.""" return self.form_class def get_form(self, form_class=None): """Return an instance of the form to be used in this view.""" if form_class is None: form_class = self.get_form_class() return form_class(**self.get_form_kwargs()) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = { "initial": self.get_initial(), "prefix": self.get_prefix(), } if self.request.method in ("POST", "PUT"): kwargs.update( { "data": self.request.POST, "files": self.request.FILES, } ) return kwargs def get_success_url(self): """Return the URL to redirect to after processing a valid form.""" if not self.success_url: raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.") return str(self.success_url) # success_url may be lazy def form_valid(self, form): """If the form is valid, redirect to the supplied URL.""" return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form): """If the form is invalid, render the invalid form.""" return self.render_to_response(self.get_context_data(form=form)) def get_context_data(self, **kwargs): """Insert the form into the context dict.""" if "form" not in kwargs: kwargs["form"] = self.get_form() return super().get_context_data(**kwargs) class ModelFormMixin(FormMixin, SingleObjectMixin): """Provide a way to show and handle a ModelForm in a request.""" fields = None def get_form_class(self): """Return the form class to use in this view.""" if self.fields is not None and self.form_class: raise ImproperlyConfigured( "Specifying both 'fields' and 'form_class' is not permitted." ) if self.form_class: return self.form_class else: if self.model is not None: # If a model has been explicitly provided, use it model = self.model elif getattr(self, "object", None) is not None: # If this view is operating on a single object, use # the class of that object model = self.object.__class__ else: # Try to get a queryset and extract the model class # from that model = self.get_queryset().model if self.fields is None: raise ImproperlyConfigured( "Using ModelFormMixin (base class of %s) without " "the 'fields' attribute is prohibited." % self.__class__.__name__ ) return model_forms.modelform_factory(model, fields=self.fields) def get_form_kwargs(self): """Return the keyword arguments for instantiating the form.""" kwargs = super().get_form_kwargs() if hasattr(self, "object"): kwargs.update({"instance": self.object}) return kwargs def get_success_url(self): """Return the URL to redirect to after processing a valid form.""" if self.success_url: url = self.success_url.format(**self.object.__dict__) else: try: url = self.object.get_absolute_url() except AttributeError: raise ImproperlyConfigured( "No URL to redirect to. Either provide a url or define" " a get_absolute_url method on the Model." ) return url def form_valid(self, form): """If the form is valid, save the associated model.""" self.object = form.save() return super().form_valid(form) class ProcessFormView(View): """Render a form on GET and processes it on POST.""" def get(self, request, *args, **kwargs): """Handle GET requests: instantiate a blank version of the form.""" return self.render_to_response(self.get_context_data()) def post(self, request, *args, **kwargs): """ Handle POST requests: instantiate a form instance with the passed POST variables and then check if it's valid. """ form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) # PUT is a valid HTTP verb for creating (with a known URL) or editing an # object, note that browsers only support POST for now. def put(self, *args, **kwargs): return self.post(*args, **kwargs) class BaseFormView(FormMixin, ProcessFormView): """A base view for displaying a form.""" class FormView(TemplateResponseMixin, BaseFormView): """A view for displaying a form and rendering a template response.""" class BaseCreateView(ModelFormMixin, ProcessFormView): """ Base view for creating a new object instance. This requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = None return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = None return super().post(request, *args, **kwargs) class CreateView(SingleObjectTemplateResponseMixin, BaseCreateView): """ View for creating a new object, with a response rendered by a template. """ template_name_suffix = "_form" class BaseUpdateView(ModelFormMixin, ProcessFormView): """ Base view for updating an existing object. This requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = self.get_object() return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) class UpdateView(SingleObjectTemplateResponseMixin, BaseUpdateView): """View for updating an object, with a response rendered by a template.""" template_name_suffix = "_form" class DeletionMixin: """Provide the ability to delete objects.""" success_url = None def delete(self, request, *args, **kwargs): """ Call the delete() method on the fetched object and then redirect to the success URL. """ self.object = self.get_object() success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url) # Add support for browsers which only accept GET and POST for now. def post(self, request, *args, **kwargs): return self.delete(request, *args, **kwargs) def get_success_url(self): if self.success_url: return self.success_url.format(**self.object.__dict__) else: raise ImproperlyConfigured("No URL to redirect to. Provide a success_url.") class BaseDeleteView(DeletionMixin, FormMixin, BaseDetailView): """ Base view for deleting an object. This requires subclassing to provide a response mixin. """ form_class = Form def post(self, request, *args, **kwargs): # Set self.object before the usual form processing flow. # Inlined because having DeletionMixin as the first base, for # get_success_url(), makes leveraging super() with ProcessFormView # overly complex. self.object = self.get_object() form = self.get_form() if form.is_valid(): return self.form_valid(form) else: return self.form_invalid(form) def form_valid(self, form): success_url = self.get_success_url() self.object.delete() return HttpResponseRedirect(success_url) class DeleteView(SingleObjectTemplateResponseMixin, BaseDeleteView): """ View for deleting an object retrieved with self.get_object(), with a response rendered by a template. """ template_name_suffix = "_confirm_delete"
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/detail.py
django/views/generic/detail.py
from django.core.exceptions import ImproperlyConfigured from django.db import models from django.http import Http404 from django.utils.translation import gettext as _ from django.views.generic.base import ContextMixin, TemplateResponseMixin, View class SingleObjectMixin(ContextMixin): """ Provide the ability to retrieve a single object for further manipulation. """ model = None queryset = None slug_field = "slug" context_object_name = None slug_url_kwarg = "slug" pk_url_kwarg = "pk" query_pk_and_slug = False def get_object(self, queryset=None): """ Return the object the view is displaying. Require `self.queryset` and a `pk` or `slug` argument in the URLconf. Subclasses can override this to return any object. """ # Use a custom queryset if provided; this is required for subclasses # like DateDetailView if queryset is None: queryset = self.get_queryset() # Next, try looking up by primary key. pk = self.kwargs.get(self.pk_url_kwarg) slug = self.kwargs.get(self.slug_url_kwarg) if pk is not None: queryset = queryset.filter(pk=pk) # Next, try looking up by slug. if slug is not None and (pk is None or self.query_pk_and_slug): slug_field = self.get_slug_field() queryset = queryset.filter(**{slug_field: slug}) # If none of those are defined, it's an error. if pk is None and slug is None: raise AttributeError( "Generic detail view %s must be called with either an object " "pk or a slug in the URLconf." % self.__class__.__name__ ) try: # Get the single item from the filtered queryset obj = queryset.get() except queryset.model.DoesNotExist: raise Http404( _("No %(verbose_name)s found matching the query") % {"verbose_name": queryset.model._meta.verbose_name} ) return obj def get_queryset(self): """ Return the `QuerySet` that will be used to look up the object. This method is called by the default implementation of get_object() and may not be called if get_object() is overridden. """ if self.queryset is None: if self.model: return self.model._default_manager.all() else: raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % {"cls": self.__class__.__name__} ) return self.queryset.all() def get_slug_field(self): """Get the name of a slug field to be used to look up by slug.""" return self.slug_field def get_context_object_name(self, obj): """Get the name to use for the object.""" if self.context_object_name: return self.context_object_name elif isinstance(obj, models.Model): return obj._meta.model_name else: return None def get_context_data(self, **kwargs): """Insert the single object into the context dict.""" context = {} if self.object: context["object"] = self.object context_object_name = self.get_context_object_name(self.object) if context_object_name: context[context_object_name] = self.object context.update(kwargs) return super().get_context_data(**context) class BaseDetailView(SingleObjectMixin, View): """ Base view for displaying a single object. This requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object = self.get_object() context = self.get_context_data(object=self.object) return self.render_to_response(context) class SingleObjectTemplateResponseMixin(TemplateResponseMixin): template_name_field = None template_name_suffix = "_detail" def get_template_names(self): """ Return a list of template names to be used for the request. May not be called if render_to_response() is overridden. Return a list containing ``template_name``, if set on the value. Otherwise, return a list containing: * the contents of the ``template_name_field`` field on the object instance that the view is operating upon (if available) * ``<app_label>/<model_name><template_name_suffix>.html`` """ try: names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If self.template_name_field is set, grab the value of the field # of that name from the object; this is the most specific template # name, if given. if self.object and self.template_name_field: name = getattr(self.object, self.template_name_field, None) if name: names.insert(0, name) # The least-specific option is the default # <app>/<model>_detail.html; only use this if the object in # question is a model. if isinstance(self.object, models.Model): object_meta = self.object._meta names.append( "%s/%s%s.html" % ( object_meta.app_label, object_meta.model_name, self.template_name_suffix, ) ) elif getattr(self, "model", None) is not None and issubclass( self.model, models.Model ): names.append( "%s/%s%s.html" % ( self.model._meta.app_label, self.model._meta.model_name, self.template_name_suffix, ) ) # If we still haven't managed to find any template names, we should # re-raise the ImproperlyConfigured to alert the user. if not names: raise ImproperlyConfigured( "SingleObjectTemplateResponseMixin requires a definition " "of 'template_name', 'template_name_field', or 'model'; " "or an implementation of 'get_template_names()'." ) return names class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView): """ Render a "detail" view of an object. By default this is a model instance looked up from `self.queryset`, but the view will support display of *any* object by overriding `self.get_object()`. """
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/list.py
django/views/generic/list.py
from django.core.exceptions import ImproperlyConfigured from django.core.paginator import InvalidPage, Paginator from django.db.models import QuerySet from django.http import Http404 from django.utils.translation import gettext as _ from django.views.generic.base import ContextMixin, TemplateResponseMixin, View class MultipleObjectMixin(ContextMixin): """A mixin for views manipulating multiple objects.""" allow_empty = True queryset = None model = None paginate_by = None paginate_orphans = 0 context_object_name = None paginator_class = Paginator page_kwarg = "page" ordering = None def get_queryset(self): """ Return the list of items for this view. The return value must be an iterable and may be an instance of `QuerySet` in which case `QuerySet` specific behavior will be enabled. """ if self.queryset is not None: queryset = self.queryset if isinstance(queryset, QuerySet): queryset = queryset.all() elif self.model is not None: queryset = self.model._default_manager.all() else: raise ImproperlyConfigured( "%(cls)s is missing a QuerySet. Define " "%(cls)s.model, %(cls)s.queryset, or override " "%(cls)s.get_queryset()." % {"cls": self.__class__.__name__} ) ordering = self.get_ordering() if ordering: if isinstance(ordering, str): ordering = (ordering,) queryset = queryset.order_by(*ordering) return queryset def get_ordering(self): """Return the field or fields to use for ordering the queryset.""" return self.ordering def paginate_queryset(self, queryset, page_size): """Paginate the queryset, if needed.""" paginator = self.get_paginator( queryset, page_size, orphans=self.get_paginate_orphans(), allow_empty_first_page=self.get_allow_empty(), ) page_kwarg = self.page_kwarg page = self.kwargs.get(page_kwarg) or self.request.GET.get(page_kwarg) or 1 try: page_number = int(page) except ValueError: if page == "last": page_number = paginator.num_pages else: raise Http404( _("Page is not “last”, nor can it be converted to an int.") ) try: page = paginator.page(page_number) return (paginator, page, page.object_list, page.has_other_pages()) except InvalidPage as e: raise Http404( _("Invalid page (%(page_number)s): %(message)s") % {"page_number": page_number, "message": str(e)} ) def get_paginate_by(self, queryset): """ Get the number of items to paginate by, or ``None`` for no pagination. """ return self.paginate_by def get_paginator( self, queryset, per_page, orphans=0, allow_empty_first_page=True, **kwargs ): """Return an instance of the paginator for this view.""" return self.paginator_class( queryset, per_page, orphans=orphans, allow_empty_first_page=allow_empty_first_page, **kwargs, ) def get_paginate_orphans(self): """ Return the maximum number of orphans extend the last page by when paginating. """ return self.paginate_orphans def get_allow_empty(self): """ Return ``True`` if the view should display empty lists and ``False`` if a 404 should be raised instead. """ return self.allow_empty def get_context_object_name(self, object_list): """Get the name of the item to be used in the context.""" if self.context_object_name: return self.context_object_name elif hasattr(object_list, "model"): return "%s_list" % object_list.model._meta.model_name else: return None def get_context_data(self, *, object_list=None, **kwargs): """Get the context for this view.""" queryset = object_list if object_list is not None else self.object_list page_size = self.get_paginate_by(queryset) context_object_name = self.get_context_object_name(queryset) if page_size: paginator, page, queryset, is_paginated = self.paginate_queryset( queryset, page_size ) context = { "paginator": paginator, "page_obj": page, "is_paginated": is_paginated, "object_list": queryset, } else: context = { "paginator": None, "page_obj": None, "is_paginated": False, "object_list": queryset, } if context_object_name is not None: context[context_object_name] = queryset context.update(kwargs) return super().get_context_data(**context) class BaseListView(MultipleObjectMixin, View): """ Base view for displaying a list of objects. This requires subclassing to provide a response mixin. """ def get(self, request, *args, **kwargs): self.object_list = self.get_queryset() allow_empty = self.get_allow_empty() if not allow_empty: # When pagination is enabled and object_list is a queryset, # it's better to do a cheap query than to load the unpaginated # queryset in memory. if self.get_paginate_by(self.object_list) is not None and hasattr( self.object_list, "exists" ): is_empty = not self.object_list.exists() else: is_empty = not self.object_list if is_empty: raise Http404( _("Empty list and “%(class_name)s.allow_empty” is False.") % { "class_name": self.__class__.__name__, } ) context = self.get_context_data() return self.render_to_response(context) class MultipleObjectTemplateResponseMixin(TemplateResponseMixin): """Mixin for responding with a template and list of objects.""" template_name_suffix = "_list" def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response is overridden. """ try: names = super().get_template_names() except ImproperlyConfigured: # If template_name isn't specified, it's not a problem -- # we just start with an empty list. names = [] # If the list is a queryset, we'll invent a template name based on the # app and model name. This name gets put at the end of the template # name list so that user-supplied names override the automatically- # generated ones. if hasattr(self.object_list, "model"): opts = self.object_list.model._meta names.append( "%s/%s%s.html" % (opts.app_label, opts.model_name, self.template_name_suffix) ) elif not names: raise ImproperlyConfigured( "%(cls)s requires either a 'template_name' attribute " "or a get_queryset() method that returns a QuerySet." % { "cls": self.__class__.__name__, } ) return names class ListView(MultipleObjectTemplateResponseMixin, BaseListView): """ Render some list of objects, set by `self.model` or `self.queryset`. `self.queryset` can actually be any iterable of items, not just a queryset. """
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/__init__.py
django/views/generic/__init__.py
from django.views.generic.base import RedirectView, TemplateView, View from django.views.generic.dates import ( ArchiveIndexView, DateDetailView, DayArchiveView, MonthArchiveView, TodayArchiveView, WeekArchiveView, YearArchiveView, ) from django.views.generic.detail import DetailView from django.views.generic.edit import CreateView, DeleteView, FormView, UpdateView from django.views.generic.list import ListView __all__ = [ "View", "TemplateView", "RedirectView", "ArchiveIndexView", "YearArchiveView", "MonthArchiveView", "WeekArchiveView", "DayArchiveView", "TodayArchiveView", "DateDetailView", "DetailView", "FormView", "CreateView", "UpdateView", "DeleteView", "ListView", "GenericViewError", ] class GenericViewError(Exception): """A problem in a generic view.""" pass
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/dates.py
django/views/generic/dates.py
import datetime from django.conf import settings from django.core.exceptions import ImproperlyConfigured from django.db import models from django.http import Http404 from django.utils import timezone from django.utils.functional import cached_property from django.utils.translation import gettext as _ from django.views.generic.base import View from django.views.generic.detail import ( BaseDetailView, SingleObjectTemplateResponseMixin, ) from django.views.generic.list import ( MultipleObjectMixin, MultipleObjectTemplateResponseMixin, ) class YearMixin: """Mixin for views manipulating year-based data.""" year_format = "%Y" year = None def get_year_format(self): """ Get a year format string in strptime syntax to be used to parse the year from url variables. """ return self.year_format def get_year(self): """Return the year for which this view should display data.""" year = self.year if year is None: try: year = self.kwargs["year"] except KeyError: try: year = self.request.GET["year"] except KeyError: raise Http404(_("No year specified")) return year def get_next_year(self, date): """Get the next valid year.""" return _get_next_prev(self, date, is_previous=False, period="year") def get_previous_year(self, date): """Get the previous valid year.""" return _get_next_prev(self, date, is_previous=True, period="year") def _get_next_year(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) def _get_current_year(self, date): """Return the start date of the current interval.""" return date.replace(month=1, day=1) class MonthMixin: """Mixin for views manipulating month-based data.""" month_format = "%b" month = None def get_month_format(self): """ Get a month format string in strptime syntax to be used to parse the month from url variables. """ return self.month_format def get_month(self): """Return the month for which this view should display data.""" month = self.month if month is None: try: month = self.kwargs["month"] except KeyError: try: month = self.request.GET["month"] except KeyError: raise Http404(_("No month specified")) return month def get_next_month(self, date): """Get the next valid month.""" return _get_next_prev(self, date, is_previous=False, period="month") def get_previous_month(self, date): """Get the previous valid month.""" return _get_next_prev(self, date, is_previous=True, period="month") def _get_next_month(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ if date.month == 12: try: return date.replace(year=date.year + 1, month=1, day=1) except ValueError: raise Http404(_("Date out of range")) else: return date.replace(month=date.month + 1, day=1) def _get_current_month(self, date): """Return the start date of the previous interval.""" return date.replace(day=1) class DayMixin: """Mixin for views manipulating day-based data.""" day_format = "%d" day = None def get_day_format(self): """ Get a day format string in strptime syntax to be used to parse the day from url variables. """ return self.day_format def get_day(self): """Return the day for which this view should display data.""" day = self.day if day is None: try: day = self.kwargs["day"] except KeyError: try: day = self.request.GET["day"] except KeyError: raise Http404(_("No day specified")) return day def get_next_day(self, date): """Get the next valid day.""" return _get_next_prev(self, date, is_previous=False, period="day") def get_previous_day(self, date): """Get the previous valid day.""" return _get_next_prev(self, date, is_previous=True, period="day") def _get_next_day(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ return date + datetime.timedelta(days=1) def _get_current_day(self, date): """Return the start date of the current interval.""" return date class WeekMixin: """Mixin for views manipulating week-based data.""" week_format = "%U" week = None def get_week_format(self): """ Get a week format string in strptime syntax to be used to parse the week from url variables. """ return self.week_format def get_week(self): """Return the week for which this view should display data.""" week = self.week if week is None: try: week = self.kwargs["week"] except KeyError: try: week = self.request.GET["week"] except KeyError: raise Http404(_("No week specified")) return week def get_next_week(self, date): """Get the next valid week.""" return _get_next_prev(self, date, is_previous=False, period="week") def get_previous_week(self, date): """Get the previous valid week.""" return _get_next_prev(self, date, is_previous=True, period="week") def _get_next_week(self, date): """ Return the start date of the next interval. The interval is defined by start date <= item date < next start date. """ try: return date + datetime.timedelta(days=7 - self._get_weekday(date)) except OverflowError: raise Http404(_("Date out of range")) def _get_current_week(self, date): """Return the start date of the current interval.""" return date - datetime.timedelta(self._get_weekday(date)) def _get_weekday(self, date): """ Return the weekday for a given date. The first day according to the week format is 0 and the last day is 6. """ week_format = self.get_week_format() if week_format in {"%W", "%V"}: # week starts on Monday return date.weekday() elif week_format == "%U": # week starts on Sunday return (date.weekday() + 1) % 7 else: raise ValueError("unknown week format: %s" % week_format) class DateMixin: """Mixin class for views manipulating date-based data.""" date_field = None allow_future = False def get_date_field(self): """Get the name of the date field to be used to filter by.""" if self.date_field is None: raise ImproperlyConfigured( "%s.date_field is required." % self.__class__.__name__ ) return self.date_field def get_allow_future(self): """ Return `True` if the view should be allowed to display objects from the future. """ return self.allow_future # Note: the following three methods only work in subclasses that also # inherit SingleObjectMixin or MultipleObjectMixin. @cached_property def uses_datetime_field(self): """ Return `True` if the date field is a `DateTimeField` and `False` if it's a `DateField`. """ model = self.get_queryset().model if self.model is None else self.model field = model._meta.get_field(self.get_date_field()) return isinstance(field, models.DateTimeField) def _make_date_lookup_arg(self, value): """ Convert a date into a datetime when the date field is a DateTimeField. When time zone support is enabled, `date` is assumed to be in the current time zone, so that displayed items are consistent with the URL. """ if self.uses_datetime_field: value = datetime.datetime.combine(value, datetime.time.min) if settings.USE_TZ: value = timezone.make_aware(value) return value def _make_single_date_lookup(self, date): """ Get the lookup kwargs for filtering on a single date. If the date field is a DateTimeField, we can't just filter on date_field=date because that doesn't take the time into account. """ date_field = self.get_date_field() if self.uses_datetime_field: since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(date + datetime.timedelta(days=1)) return { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } else: # Skip self._make_date_lookup_arg, it's a no-op in this branch. return {date_field: date} class BaseDateListView(MultipleObjectMixin, DateMixin, View): """ Base class for date-based views displaying a list of objects. This requires subclassing to provide a response mixin. """ allow_empty = False date_list_period = "year" def get(self, request, *args, **kwargs): self.date_list, self.object_list, extra_context = self.get_dated_items() context = self.get_context_data( object_list=self.object_list, date_list=self.date_list, **extra_context ) return self.render_to_response(context) def get_dated_items(self): """Obtain the list of dates and items.""" raise NotImplementedError( "A DateView must provide an implementation of get_dated_items()" ) def get_ordering(self): """ Return the field or fields to use for ordering the queryset; use the date field by default. """ return "-%s" % self.get_date_field() if self.ordering is None else self.ordering def get_dated_queryset(self, **lookup): """ Get a queryset properly filtered according to `allow_future` and any extra lookup kwargs. """ qs = self.get_queryset().filter(**lookup) date_field = self.get_date_field() allow_future = self.get_allow_future() allow_empty = self.get_allow_empty() paginate_by = self.get_paginate_by(qs) if not allow_future: now = timezone.now() if self.uses_datetime_field else timezone_today() qs = qs.filter(**{"%s__lte" % date_field: now}) if not allow_empty: # When pagination is enabled, it's better to do a cheap query # than to load the unpaginated queryset in memory. is_empty = not qs if paginate_by is None else not qs.exists() if is_empty: raise Http404( _("No %(verbose_name_plural)s available") % { "verbose_name_plural": qs.model._meta.verbose_name_plural, } ) return qs def get_date_list_period(self): """ Get the aggregation period for the list of dates: 'year', 'month', or 'day'. """ return self.date_list_period def get_date_list(self, queryset, date_type=None, ordering="ASC"): """ Get a date list by calling `queryset.dates/datetimes()`, checking along the way for empty lists that aren't allowed. """ date_field = self.get_date_field() allow_empty = self.get_allow_empty() if date_type is None: date_type = self.get_date_list_period() if self.uses_datetime_field: date_list = queryset.datetimes(date_field, date_type, ordering) else: date_list = queryset.dates(date_field, date_type, ordering) if date_list is not None and not date_list and not allow_empty: raise Http404( _("No %(verbose_name_plural)s available") % { "verbose_name_plural": queryset.model._meta.verbose_name_plural, } ) return date_list class BaseArchiveIndexView(BaseDateListView): """ Base view for archives of date-based items. This requires subclassing to provide a response mixin. """ context_object_name = "latest" def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" qs = self.get_dated_queryset() date_list = self.get_date_list(qs, ordering="DESC") if not date_list: qs = qs.none() return (date_list, qs, {}) class ArchiveIndexView(MultipleObjectTemplateResponseMixin, BaseArchiveIndexView): """Top-level archive of date-based items.""" template_name_suffix = "_archive" class BaseYearArchiveView(YearMixin, BaseDateListView): """ Base view for a list of objects published in a given year. This requires subclassing to provide a response mixin. """ date_list_period = "month" make_object_list = False def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() date_field = self.get_date_field() date = _date_from_string(year, self.get_year_format()) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_year(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) date_list = self.get_date_list(qs) if not self.get_make_object_list(): # We need this to be a queryset since parent classes introspect it # to find information about the model. qs = qs.none() return ( date_list, qs, { "year": date, "next_year": self.get_next_year(date), "previous_year": self.get_previous_year(date), }, ) def get_make_object_list(self): """ Return `True` if this view should contain the full list of objects in the given year. """ return self.make_object_list class YearArchiveView(MultipleObjectTemplateResponseMixin, BaseYearArchiveView): """List of objects published in a given year.""" template_name_suffix = "_archive_year" class BaseMonthArchiveView(YearMixin, MonthMixin, BaseDateListView): """ Base view for a list of objects published in a given month. This requires subclassing to provide a response mixin. """ date_list_period = "day" def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() month = self.get_month() date_field = self.get_date_field() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format() ) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_month(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) date_list = self.get_date_list(qs) return ( date_list, qs, { "month": date, "next_month": self.get_next_month(date), "previous_month": self.get_previous_month(date), }, ) class MonthArchiveView(MultipleObjectTemplateResponseMixin, BaseMonthArchiveView): """List of objects published in a given month.""" template_name_suffix = "_archive_month" class BaseWeekArchiveView(YearMixin, WeekMixin, BaseDateListView): """ Base view for a list of objects published in a given week. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() week = self.get_week() date_field = self.get_date_field() week_format = self.get_week_format() week_choices = {"%W": "1", "%U": "0", "%V": "1"} try: week_start = week_choices[week_format] except KeyError: raise ValueError( "Unknown week format %r. Choices are: %s" % ( week_format, ", ".join(sorted(week_choices)), ) ) year_format = self.get_year_format() if week_format == "%V" and year_format != "%G": raise ValueError( "ISO week directive '%s' is incompatible with the year " "directive '%s'. Use the ISO year '%%G' instead." % ( week_format, year_format, ) ) date = _date_from_string(year, year_format, week_start, "%w", week, week_format) since = self._make_date_lookup_arg(date) until = self._make_date_lookup_arg(self._get_next_week(date)) lookup_kwargs = { "%s__gte" % date_field: since, "%s__lt" % date_field: until, } qs = self.get_dated_queryset(**lookup_kwargs) return ( None, qs, { "week": date, "next_week": self.get_next_week(date), "previous_week": self.get_previous_week(date), }, ) class WeekArchiveView(MultipleObjectTemplateResponseMixin, BaseWeekArchiveView): """List of objects published in a given week.""" template_name_suffix = "_archive_week" class BaseDayArchiveView(YearMixin, MonthMixin, DayMixin, BaseDateListView): """ Base view for a list of objects published on a given day. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format(), ) return self._get_dated_items(date) def _get_dated_items(self, date): """ Do the actual heavy lifting of getting the dated items; this accepts a date object so that TodayArchiveView can be trivial. """ lookup_kwargs = self._make_single_date_lookup(date) qs = self.get_dated_queryset(**lookup_kwargs) return ( None, qs, { "day": date, "previous_day": self.get_previous_day(date), "next_day": self.get_next_day(date), "previous_month": self.get_previous_month(date), "next_month": self.get_next_month(date), }, ) class DayArchiveView(MultipleObjectTemplateResponseMixin, BaseDayArchiveView): """List of objects published on a given day.""" template_name_suffix = "_archive_day" class BaseTodayArchiveView(BaseDayArchiveView): """ Base view for a list of objects published today. This requires subclassing to provide a response mixin. """ def get_dated_items(self): """Return (date_list, items, extra_context) for this request.""" return self._get_dated_items(datetime.date.today()) class TodayArchiveView(MultipleObjectTemplateResponseMixin, BaseTodayArchiveView): """List of objects published today.""" template_name_suffix = "_archive_day" class BaseDateDetailView(YearMixin, MonthMixin, DayMixin, DateMixin, BaseDetailView): """ Base detail view for a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. This requires subclassing to provide a response mixin. """ def get_object(self, queryset=None): """Get the object this request displays.""" year = self.get_year() month = self.get_month() day = self.get_day() date = _date_from_string( year, self.get_year_format(), month, self.get_month_format(), day, self.get_day_format(), ) # Use a custom queryset if provided qs = self.get_queryset() if queryset is None else queryset if not self.get_allow_future() and date > datetime.date.today(): raise Http404( _( "Future %(verbose_name_plural)s not available because " "%(class_name)s.allow_future is False." ) % { "verbose_name_plural": qs.model._meta.verbose_name_plural, "class_name": self.__class__.__name__, } ) # Filter down a queryset from self.queryset using the date from the # URL. This'll get passed as the queryset to DetailView.get_object, # which'll handle the 404 lookup_kwargs = self._make_single_date_lookup(date) qs = qs.filter(**lookup_kwargs) return super().get_object(queryset=qs) class DateDetailView(SingleObjectTemplateResponseMixin, BaseDateDetailView): """ Detail view of a single object on a single date; this differs from the standard DetailView by accepting a year/month/day in the URL. """ template_name_suffix = "_detail" def _date_from_string( year, year_format, month="", month_format="", day="", day_format="", delim="__" ): """ Get a datetime.date object given a format string and a year, month, and day (only year is mandatory). Raise a 404 for an invalid date. """ format = year_format + delim + month_format + delim + day_format datestr = str(year) + delim + str(month) + delim + str(day) try: return datetime.datetime.strptime(datestr, format).date() except ValueError: raise Http404( _("Invalid date string “%(datestr)s” given format “%(format)s”") % { "datestr": datestr, "format": format, } ) def _get_next_prev(generic_view, date, is_previous, period): """ Get the next or the previous valid date. The idea is to allow links on month/day views to never be 404s by never providing a date that'll be invalid for the given view. This is a bit complicated since it handles different intervals of time, hence the coupling to generic_view. However in essence the logic comes down to: * If allow_empty and allow_future are both true, this is easy: just return the naive result (just the next/previous day/week/month, regardless of object existence.) * If allow_empty is true, allow_future is false, and the naive result isn't in the future, then return it; otherwise return None. * If allow_empty is false and allow_future is true, return the next date *that contains a valid object*, even if it's in the future. If there are no next objects, return None. * If allow_empty is false and allow_future is false, return the next date that contains a valid object. If that date is in the future, or if there are no next objects, return None. """ date_field = generic_view.get_date_field() allow_empty = generic_view.get_allow_empty() allow_future = generic_view.get_allow_future() get_current = getattr(generic_view, "_get_current_%s" % period) get_next = getattr(generic_view, "_get_next_%s" % period) # Bounds of the current interval start, end = get_current(date), get_next(date) # If allow_empty is True, the naive result will be valid if allow_empty: if is_previous: result = get_current(start - datetime.timedelta(days=1)) else: result = end if allow_future or result <= timezone_today(): return result else: return None # Otherwise, we'll need to go to the database to look for an object # whose date_field is at least (greater than/less than) the given # naive result else: # Construct a lookup and an ordering depending on whether we're doing # a previous date or a next date lookup. if is_previous: lookup = {"%s__lt" % date_field: generic_view._make_date_lookup_arg(start)} ordering = "-%s" % date_field else: lookup = {"%s__gte" % date_field: generic_view._make_date_lookup_arg(end)} ordering = date_field # Filter out objects in the future if appropriate. if not allow_future: # Fortunately, to match the implementation of allow_future, # we need __lte, which doesn't conflict with __lt above. if generic_view.uses_datetime_field: now = timezone.now() else: now = timezone_today() lookup["%s__lte" % date_field] = now qs = generic_view.get_queryset().filter(**lookup).order_by(ordering) # Snag the first object from the queryset; if it doesn't exist that # means there's no next/previous link available. try: result = getattr(qs[0], date_field) except IndexError: return None # Convert datetimes to dates in the current time zone. if generic_view.uses_datetime_field: if settings.USE_TZ: result = timezone.localtime(result) result = result.date() # Return the first day of the period. return get_current(result) def timezone_today(): """Return the current date in the current time zone.""" if settings.USE_TZ: return timezone.localdate() else: return datetime.date.today()
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/views/generic/base.py
django/views/generic/base.py
import logging from urllib.parse import urlparse from asgiref.sync import iscoroutinefunction, markcoroutinefunction from django.core.exceptions import ImproperlyConfigured from django.http import ( HttpResponse, HttpResponseGone, HttpResponseNotAllowed, HttpResponsePermanentRedirect, HttpResponseRedirect, ) from django.template.response import TemplateResponse from django.urls import reverse from django.utils.decorators import classonlymethod from django.utils.functional import classproperty from django.utils.log import log_response logger = logging.getLogger("django.request") class ContextMixin: """ A default context mixin that passes the keyword arguments received by get_context_data() as the template context. """ extra_context = None def get_context_data(self, **kwargs): kwargs.setdefault("view", self) if self.extra_context is not None: kwargs.update(self.extra_context) return kwargs class View: """ Intentionally simple parent class for all views. Only implements dispatch-by-method and simple sanity checking. """ http_method_names = [ "get", "post", "put", "patch", "delete", "head", "options", "trace", ] def __init__(self, **kwargs): """ Constructor. Called in the URLconf; can contain helpful extra keyword arguments, and other things. """ # Go through keyword arguments, and either save their values to our # instance, or raise an error. for key, value in kwargs.items(): setattr(self, key, value) @classproperty def view_is_async(cls): handlers = [ getattr(cls, method) for method in cls.http_method_names if (method != "options" and hasattr(cls, method)) ] if not handlers: return False is_async = iscoroutinefunction(handlers[0]) if not all(iscoroutinefunction(h) == is_async for h in handlers[1:]): raise ImproperlyConfigured( f"{cls.__qualname__} HTTP handlers must either be all sync or all " "async." ) return is_async @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" for key in initkwargs: if key in cls.http_method_names: raise TypeError( "The method name %s is not accepted as a keyword argument " "to %s()." % (key, cls.__name__) ) if not hasattr(cls, key): raise TypeError( "%s() received an invalid keyword %r. as_view " "only accepts arguments that are already " "attributes of the class." % (cls.__name__, key) ) def view(request, *args, **kwargs): self = cls(**initkwargs) self.setup(request, *args, **kwargs) if not hasattr(self, "request"): raise AttributeError( "%s instance has no 'request' attribute. Did you override " "setup() and forget to call super()?" % cls.__name__ ) return self.dispatch(request, *args, **kwargs) view.view_class = cls view.view_initkwargs = initkwargs # __name__ and __qualname__ are intentionally left unchanged as # view_class should be used to robustly determine the name of the view # instead. view.__doc__ = cls.__doc__ view.__module__ = cls.__module__ view.__annotations__ = cls.dispatch.__annotations__ # Copy possible attributes set by decorators, e.g. @csrf_exempt, from # the dispatch method. view.__dict__.update(cls.dispatch.__dict__) # Mark the callback if the view class is async. if cls.view_is_async: markcoroutinefunction(view) return view def setup(self, request, *args, **kwargs): """Initialize attributes shared by all view methods.""" if hasattr(self, "get") and not hasattr(self, "head"): self.head = self.get self.request = request self.args = args self.kwargs = kwargs def dispatch(self, request, *args, **kwargs): # Try to dispatch to the right method; if a method doesn't exist, # defer to the error handler. Also defer to the error handler if the # request method isn't on the approved list. method = request.method.lower() if method in self.http_method_names: handler = getattr(self, method, self.http_method_not_allowed) else: handler = self.http_method_not_allowed return handler(request, *args, **kwargs) def http_method_not_allowed(self, request, *args, **kwargs): response = HttpResponseNotAllowed(self._allowed_methods()) log_response( "Method Not Allowed (%s): %s", request.method, request.path, response=response, request=request, ) if self.view_is_async: async def func(): return response return func() else: return response def options(self, request, *args, **kwargs): """Handle responding to requests for the OPTIONS HTTP verb.""" response = HttpResponse() response.headers["Allow"] = ", ".join(self._allowed_methods()) response.headers["Content-Length"] = "0" if self.view_is_async: async def func(): return response return func() else: return response def _allowed_methods(self): return [m.upper() for m in self.http_method_names if hasattr(self, m)] class TemplateResponseMixin: """A mixin that can be used to render a template.""" template_name = None template_engine = None response_class = TemplateResponse content_type = None def render_to_response(self, context, **response_kwargs): """ Return a response, using the `response_class` for this view, with a template rendered with the given context. Pass response_kwargs to the constructor of the response class. """ response_kwargs.setdefault("content_type", self.content_type) return self.response_class( request=self.request, template=self.get_template_names(), context=context, using=self.template_engine, **response_kwargs, ) def get_template_names(self): """ Return a list of template names to be used for the request. Must return a list. May not be called if render_to_response() is overridden. """ if self.template_name is None: raise ImproperlyConfigured( "TemplateResponseMixin requires either a definition of " "'template_name' or an implementation of 'get_template_names()'" ) else: return [self.template_name] class TemplateView(TemplateResponseMixin, ContextMixin, View): """ Render a template. Pass keyword arguments from the URLconf to the context. """ def get(self, request, *args, **kwargs): context = self.get_context_data(**kwargs) return self.render_to_response(context) class RedirectView(View): """Provide a redirect on any GET request.""" permanent = False url = None pattern_name = None query_string = False def get_redirect_url(self, *args, **kwargs): """ Return the URL redirect to. Keyword arguments from the URL pattern match generating the redirect request are provided as kwargs to this method. """ if self.url: url = self.url % kwargs elif self.pattern_name: url = reverse(self.pattern_name, args=args, kwargs=kwargs) else: return None args = self.request.META.get("QUERY_STRING", "") if args and self.query_string: if urlparse(url).query: url = f"{url}&{args}" else: url = f"{url}?{args}" return url def get(self, request, *args, **kwargs): url = self.get_redirect_url(*args, **kwargs) if url: if self.permanent: return HttpResponsePermanentRedirect(url) else: return HttpResponseRedirect(url) else: response = HttpResponseGone() log_response("Gone: %s", request.path, response=response, request=request) return response def head(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def post(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def options(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def delete(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def put(self, request, *args, **kwargs): return self.get(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.get(request, *args, **kwargs)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/dispatch/__init__.py
django/dispatch/__init__.py
"""Multi-consumer multi-producer dispatching mechanism Originally based on pydispatch (BSD) https://pypi.org/project/PyDispatcher/2.0.1/ See license.txt for original license. Heavily modified for Django's purposes. """ from django.dispatch.dispatcher import Signal, receiver # NOQA
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/dispatch/dispatcher.py
django/dispatch/dispatcher.py
import asyncio import contextvars import logging import threading import weakref from asgiref.sync import async_to_sync, iscoroutinefunction, sync_to_async from django.utils.inspect import func_accepts_kwargs logger = logging.getLogger("django.dispatch") def _make_id(target): if hasattr(target, "__func__"): return (id(target.__self__), id(target.__func__)) return id(target) NONE_ID = _make_id(None) # A marker for caching NO_RECEIVERS = object() def _restore_context(context): """ Check for changes in contextvars, and set them to the current context for downstream consumers. """ for cvar in context: cvalue = context.get(cvar) try: if cvar.get() != cvalue: cvar.set(cvalue) except LookupError: cvar.set(cvalue) async def _run_parallel(*coros): """ Execute multiple asynchronous coroutines in parallel, sharing the current context between them. """ context = contextvars.copy_context() if len(coros) == 0: return [] async def run(i, coro): results[i] = await coro try: async with asyncio.TaskGroup() as tg: results = [None] * len(coros) for i, coro in enumerate(coros): tg.create_task(run(i, coro), context=context) return results except BaseExceptionGroup as exception_group: if len(exception_group.exceptions) == 1: raise exception_group.exceptions[0] raise finally: _restore_context(context=context) class Signal: """ Base class for all signals Internal attributes: receivers: [ ( (id(receiver), id(sender)), ref(receiver), ref(sender), is_async, ) ] sender_receivers_cache: WeakKeyDictionary[sender, list[receiver]] """ def __init__(self, use_caching=False): """ Create a new signal. """ self.receivers = [] self.lock = threading.Lock() self.use_caching = use_caching # For convenience we create empty caches even if they are not used. # A note about caching: if use_caching is defined, then for each # distinct sender we cache the receivers that sender has in # 'sender_receivers_cache'. The cache is cleaned when .connect() or # .disconnect() is called and populated on send(). self.sender_receivers_cache = weakref.WeakKeyDictionary() if use_caching else {} self._dead_receivers = False def connect(self, receiver, sender=None, weak=True, dispatch_uid=None): """ Connect receiver to sender for signal. Arguments: receiver A function or an instance method which is to receive signals. Receivers must be hashable objects. Receivers can be asynchronous. If weak is True, then receiver must be weak referenceable. Receivers must be able to accept keyword arguments. If a receiver is connected with a dispatch_uid argument, it will not be added if another receiver was already connected with that dispatch_uid. sender The sender to which the receiver should respond. Must either be a Python object, or None to receive events from any sender. weak Whether to use weak references to the receiver. By default, the module will attempt to use weak references to the receiver objects. If this parameter is false, then strong references will be used. dispatch_uid An identifier used to uniquely identify a particular instance of a receiver. This will usually be a string, though it may be anything hashable. """ from django.conf import settings # If DEBUG is on, check that we got a good receiver if settings.configured and settings.DEBUG: if not callable(receiver): raise TypeError("Signal receivers must be callable.") # Check for **kwargs if not func_accepts_kwargs(receiver): raise ValueError( "Signal receivers must accept keyword arguments (**kwargs)." ) if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) is_async = iscoroutinefunction(receiver) if weak: ref = weakref.ref receiver_object = receiver # Check for bound methods if hasattr(receiver, "__self__") and hasattr(receiver, "__func__"): ref = weakref.WeakMethod receiver_object = receiver.__self__ receiver = ref(receiver) weakref.finalize(receiver_object, self._flag_dead_receivers) # Keep a weakref to sender if possible to ensure associated receivers # are cleared if it gets garbage collected. This ensures there is no # id(sender) collisions for distinct senders with non-overlapping # lifetimes. sender_ref = None if sender is not None: try: sender_ref = weakref.ref(sender, self._flag_dead_receivers) except TypeError: pass with self.lock: self._clear_dead_receivers() if not any(r_key == lookup_key for r_key, _, _, _ in self.receivers): self.receivers.append((lookup_key, receiver, sender_ref, is_async)) self.sender_receivers_cache.clear() def disconnect(self, receiver=None, sender=None, dispatch_uid=None): """ Disconnect receiver from sender for signal. If weak references are used, disconnect need not be called. The receiver will be removed from dispatch automatically. Arguments: receiver The registered receiver to disconnect. May be none if dispatch_uid is specified. sender The registered sender to disconnect dispatch_uid the unique identifier of the receiver to disconnect """ if dispatch_uid: lookup_key = (dispatch_uid, _make_id(sender)) else: lookup_key = (_make_id(receiver), _make_id(sender)) disconnected = False with self.lock: self._clear_dead_receivers() for index in range(len(self.receivers)): r_key, *_ = self.receivers[index] if r_key == lookup_key: disconnected = True del self.receivers[index] break self.sender_receivers_cache.clear() return disconnected def has_listeners(self, sender=None): sync_receivers, async_receivers = self._live_receivers(sender) return bool(sync_receivers) or bool(async_receivers) def send(self, sender, **named): """ Send signal from sender to all connected receivers. If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. If any receivers are asynchronous, they are called after all the synchronous receivers via a single call to async_to_sync(). They are also executed concurrently with asyncio.TaskGroup(). Arguments: sender The sender of the signal. Either a specific object or None. named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ... ]. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] responses = [] sync_receivers, async_receivers = self._live_receivers(sender) for receiver in sync_receivers: response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) if async_receivers: async def asend(): async_responses = await _run_parallel( *( receiver(signal=self, sender=sender, **named) for receiver in async_receivers ) ) return zip(async_receivers, async_responses) responses.extend(async_to_sync(asend)()) return responses async def asend(self, sender, **named): """ Send signal from sender to all connected receivers in async mode. All sync receivers will be wrapped by sync_to_async() If any receiver raises an error, the error propagates back through send, terminating the dispatch loop. So it's possible that all receivers won't be called if an error is raised. If any receivers are synchronous, they are grouped and called behind a sync_to_async() adaption before executing any asynchronous receivers. If any receivers are asynchronous, they are grouped and executed concurrently with asyncio.TaskGroup(). Arguments: sender The sender of the signal. Either a specific object or None. named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ...]. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] sync_receivers, async_receivers = self._live_receivers(sender) if sync_receivers: @sync_to_async def sync_send(): responses = [] for receiver in sync_receivers: response = receiver(signal=self, sender=sender, **named) responses.append((receiver, response)) return responses else: async def sync_send(): return [] responses = await sync_send() async_responses = await _run_parallel( *( receiver(signal=self, sender=sender, **named) for receiver in async_receivers ) ) responses.extend(zip(async_receivers, async_responses)) return responses def _log_robust_failure(self, receiver, err): logger.error( "Error calling %s in Signal.send_robust() (%s)", receiver.__qualname__, err, exc_info=err, ) def send_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. If any receivers are asynchronous, they are called after all the synchronous receivers via a single call to async_to_sync(). They are also executed concurrently with asyncio.TaskGroup(). Arguments: sender The sender of the signal. Can be any Python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ... ]. If any receiver raises an error (specifically any subclass of Exception), return the error instance as the result for that receiver. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. responses = [] sync_receivers, async_receivers = self._live_receivers(sender) for receiver in sync_receivers: try: response = receiver(signal=self, sender=sender, **named) except Exception as err: self._log_robust_failure(receiver, err) responses.append((receiver, err)) else: responses.append((receiver, response)) if async_receivers: async def asend_and_wrap_exception(receiver): try: response = await receiver(signal=self, sender=sender, **named) except Exception as err: self._log_robust_failure(receiver, err) return err return response async def asend(): async_responses = await _run_parallel( *( asend_and_wrap_exception(receiver) for receiver in async_receivers ) ) return zip(async_receivers, async_responses) responses.extend(async_to_sync(asend)()) return responses async def asend_robust(self, sender, **named): """ Send signal from sender to all connected receivers catching errors. If any receivers are synchronous, they are grouped and called behind a sync_to_async() adaption before executing any asynchronous receivers. If any receivers are asynchronous, they are grouped and executed concurrently with asyncio.TaskGroup. Arguments: sender The sender of the signal. Can be any Python object (normally one registered with a connect if you actually want something to occur). named Named arguments which will be passed to receivers. Return a list of tuple pairs [(receiver, response), ... ]. If any receiver raises an error (specifically any subclass of Exception), return the error instance as the result for that receiver. """ if ( not self.receivers or self.sender_receivers_cache.get(sender) is NO_RECEIVERS ): return [] # Call each receiver with whatever arguments it can accept. # Return a list of tuple pairs [(receiver, response), ... ]. sync_receivers, async_receivers = self._live_receivers(sender) if sync_receivers: @sync_to_async def sync_send(): responses = [] for receiver in sync_receivers: try: response = receiver(signal=self, sender=sender, **named) except Exception as err: self._log_robust_failure(receiver, err) responses.append((receiver, err)) else: responses.append((receiver, response)) return responses else: async def sync_send(): return [] async def asend_and_wrap_exception(receiver): try: response = await receiver(signal=self, sender=sender, **named) except Exception as err: self._log_robust_failure(receiver, err) return err return response responses = await sync_send() async_responses = await _run_parallel( *(asend_and_wrap_exception(receiver) for receiver in async_receivers), ) responses.extend(zip(async_receivers, async_responses)) return responses def _clear_dead_receivers(self): # Note: caller is assumed to hold self.lock. if self._dead_receivers: self._dead_receivers = False self.receivers = [ r for r in self.receivers if ( not (isinstance(r[1], weakref.ReferenceType) and r[1]() is None) and not (r[2] is not None and r[2]() is None) ) ] def _live_receivers(self, sender): """ Filter sequence of receivers to get resolved, live receivers. This checks for weak references and resolves them, then returning only live receivers. """ receivers = None if self.use_caching and not self._dead_receivers: receivers = self.sender_receivers_cache.get(sender) # We could end up here with NO_RECEIVERS even if we do check this # case in .send() prior to calling _live_receivers() due to # concurrent .send() call. if receivers is NO_RECEIVERS: return [], [] if receivers is None: with self.lock: self._clear_dead_receivers() senderkey = _make_id(sender) receivers = [] for ( (_receiverkey, r_senderkey), receiver, sender_ref, is_async, ) in self.receivers: if r_senderkey == NONE_ID or r_senderkey == senderkey: receivers.append((receiver, sender_ref, is_async)) if self.use_caching: if not receivers: self.sender_receivers_cache[sender] = NO_RECEIVERS else: # Note, we must cache the weakref versions. self.sender_receivers_cache[sender] = receivers non_weak_sync_receivers = [] non_weak_async_receivers = [] for receiver, sender_ref, is_async in receivers: # Skip if the receiver/sender is a dead weakref if isinstance(receiver, weakref.ReferenceType): receiver = receiver() if receiver is None: continue if sender_ref is not None and sender_ref() is None: continue if is_async: non_weak_async_receivers.append(receiver) else: non_weak_sync_receivers.append(receiver) return non_weak_sync_receivers, non_weak_async_receivers def _flag_dead_receivers(self, reference=None): # Mark that the self.receivers list has dead weakrefs. If so, we will # clean those up in connect, disconnect and _live_receivers while # holding self.lock. Note that doing the cleanup here isn't a good # idea, _flag_dead_receivers() will be called as side effect of garbage # collection, and so the call can happen while we are already holding # self.lock. self._dead_receivers = True def receiver(signal, **kwargs): """ A decorator for connecting receivers to signals. Used by passing in the signal (or list of signals) and keyword arguments to connect:: @receiver(post_save, sender=MyModel) def signal_receiver(sender, **kwargs): ... @receiver([post_save, post_delete], sender=MyModel) def signals_receiver(sender, **kwargs): ... """ def _decorator(func): if isinstance(signal, (list, tuple)): for s in signal: s.connect(func, **kwargs) else: signal.connect(func, **kwargs) return func return _decorator
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/defaultfilters.py
django/template/defaultfilters.py
"""Default variable filters.""" import random as random_module import re import types from decimal import ROUND_HALF_UP, Context, Decimal, InvalidOperation, getcontext from functools import wraps from inspect import unwrap from operator import itemgetter from pprint import pformat from urllib.parse import quote from django.utils import formats from django.utils.dateformat import format, time_format from django.utils.encoding import iri_to_uri from django.utils.html import avoid_wrapping, conditional_escape, escape, escapejs from django.utils.html import json_script as _json_script from django.utils.html import linebreaks, strip_tags from django.utils.html import urlize as _urlize from django.utils.safestring import SafeData, mark_safe from django.utils.text import Truncator, normalize_newlines, phone2numeric from django.utils.text import slugify as _slugify from django.utils.text import wrap from django.utils.timesince import timesince, timeuntil from django.utils.translation import gettext, ngettext from .base import VARIABLE_ATTRIBUTE_SEPARATOR from .library import Library register = Library() ####################### # STRING DECORATOR # ####################### def stringfilter(func): """ Decorator for filters which should only receive strings. The object passed as the first positional argument will be converted to a string. """ @wraps(func) def _dec(first, *args, **kwargs): first = str(first) result = func(first, *args, **kwargs) if isinstance(first, SafeData) and getattr(unwrap(func), "is_safe", False): result = mark_safe(result) return result return _dec ################### # STRINGS # ################### @register.filter(is_safe=True) @stringfilter def addslashes(value): """ Add slashes before quotes. Useful for escaping strings in CSV, for example. Less useful for escaping JavaScript; use the ``escapejs`` filter instead. """ return value.replace("\\", "\\\\").replace('"', '\\"').replace("'", "\\'") @register.filter(is_safe=True) @stringfilter def capfirst(value): """Capitalize the first character of the value.""" return value and value[0].upper() + value[1:] @register.filter("escapejs") @stringfilter def escapejs_filter(value): """Hex encode characters for use in JavaScript strings.""" return escapejs(value) @register.filter(is_safe=True) def json_script(value, element_id=None): """ Output value JSON-encoded, wrapped in a <script type="application/json"> tag (with an optional id). """ return _json_script(value, element_id) @register.filter(is_safe=True) def floatformat(text, arg=-1): """ Display a float to a specified number of decimal places. If called without an argument, display the floating point number with one decimal place -- but only if there's a decimal place to be displayed: * num1 = 34.23234 * num2 = 34.00000 * num3 = 34.26000 * {{ num1|floatformat }} displays "34.2" * {{ num2|floatformat }} displays "34" * {{ num3|floatformat }} displays "34.3" If arg is positive, always display exactly arg number of decimal places: * {{ num1|floatformat:3 }} displays "34.232" * {{ num2|floatformat:3 }} displays "34.000" * {{ num3|floatformat:3 }} displays "34.260" If arg is negative, display arg number of decimal places -- but only if there are places to be displayed: * {{ num1|floatformat:"-3" }} displays "34.232" * {{ num2|floatformat:"-3" }} displays "34" * {{ num3|floatformat:"-3" }} displays "34.260" If arg has the 'g' suffix, force the result to be grouped by the THOUSAND_SEPARATOR for the active locale. When the active locale is en (English): * {{ 6666.6666|floatformat:"2g" }} displays "6,666.67" * {{ 10000|floatformat:"g" }} displays "10,000" If arg has the 'u' suffix, force the result to be unlocalized. When the active locale is pl (Polish): * {{ 66666.6666|floatformat:"2" }} displays "66666,67" * {{ 66666.6666|floatformat:"2u" }} displays "66666.67" If the input float is infinity or NaN, display the string representation of that value. """ force_grouping = False use_l10n = True if isinstance(arg, str): last_char = arg[-1] if arg[-2:] in {"gu", "ug"}: force_grouping = True use_l10n = False arg = arg[:-2] or -1 elif last_char == "g": force_grouping = True arg = arg[:-1] or -1 elif last_char == "u": use_l10n = False arg = arg[:-1] or -1 try: input_val = str(text) d = Decimal(input_val) except InvalidOperation: try: d = Decimal(str(float(text))) except (ValueError, InvalidOperation, TypeError): return "" try: p = int(arg) except ValueError: return input_val _, digits, exponent = d.as_tuple() try: number_of_digits_and_exponent_sum = len(digits) + abs(exponent) except TypeError: # Exponent values can be "F", "n", "N". number_of_digits_and_exponent_sum = 0 # Values with more than 200 digits, or with a large exponent, are returned # "as is" to avoid high memory consumption and potential denial-of-service # attacks. The cut-off of 200 is consistent with # django.utils.numberformat.floatformat(). if number_of_digits_and_exponent_sum > 200: return input_val try: m = int(d) - d except (ValueError, OverflowError, InvalidOperation): return input_val if not m and p <= 0: return mark_safe( formats.number_format( "%d" % (int(d)), 0, use_l10n=use_l10n, force_grouping=force_grouping, ) ) exp = Decimal(1).scaleb(-abs(p)) # Set the precision high enough to avoid an exception (#15789). tupl = d.as_tuple() units = len(tupl[1]) units += -tupl[2] if m else tupl[2] prec = abs(p) + units + 1 prec = max(getcontext().prec, prec) # Avoid conversion to scientific notation by accessing `sign`, `digits`, # and `exponent` from Decimal.as_tuple() directly. rounded_d = d.quantize(exp, ROUND_HALF_UP, Context(prec=prec)) sign, digits, exponent = rounded_d.as_tuple() digits = [str(digit) for digit in reversed(digits)] while len(digits) <= abs(exponent): digits.append("0") digits.insert(-exponent, ".") if sign and rounded_d: digits.append("-") number = "".join(reversed(digits)) return mark_safe( formats.number_format( number, abs(p), use_l10n=use_l10n, force_grouping=force_grouping, ) ) @register.filter(is_safe=True) @stringfilter def iriencode(value): """Escape an IRI value for use in a URL.""" return iri_to_uri(value) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linenumbers(value, autoescape=True): """Display text with line numbers.""" lines = value.split("\n") # Find the maximum width of the line count, for use with zero padding # string format command width = str(len(str(len(lines)))) if not autoescape or isinstance(value, SafeData): for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, line) else: for i, line in enumerate(lines): lines[i] = ("%0" + width + "d. %s") % (i + 1, escape(line)) return mark_safe("\n".join(lines)) @register.filter(is_safe=True) @stringfilter def lower(value): """Convert a string into all lowercase.""" return value.lower() @register.filter(is_safe=False) @stringfilter def make_list(value): """ Return the value turned into a list. For an integer, it's a list of digits. For a string, it's a list of characters. """ return list(value) @register.filter(is_safe=True) @stringfilter def slugify(value): """ Convert to ASCII. Convert spaces to hyphens. Remove characters that aren't alphanumerics, underscores, or hyphens. Convert to lowercase. Also strip leading and trailing whitespace. """ return _slugify(value) @register.filter(is_safe=True) def stringformat(value, arg): """ Format the variable according to the arg, a string formatting specifier. This specifier uses Python string formatting syntax, with the exception that the leading "%" is dropped. See https://docs.python.org/library/stdtypes.html#printf-style-string-formatting for documentation of Python string formatting. """ if isinstance(value, tuple): value = str(value) try: return ("%" + str(arg)) % value except (ValueError, TypeError): return "" @register.filter(is_safe=True) @stringfilter def title(value): """Convert a string into titlecase.""" t = re.sub("([a-z])'([A-Z])", lambda m: m[0].lower(), value.title()) return re.sub(r"\d([A-Z])", lambda m: m[0].lower(), t) @register.filter(is_safe=True) @stringfilter def truncatechars(value, arg): """Truncate a string after `arg` number of characters.""" try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).chars(length) @register.filter(is_safe=True) @stringfilter def truncatechars_html(value, arg): """ Truncate HTML after `arg` number of chars. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).chars(length, html=True) @register.filter(is_safe=True) @stringfilter def truncatewords(value, arg): """ Truncate a string after `arg` number of words. Remove newlines within the string. """ try: length = int(arg) except ValueError: # Invalid literal for int(). return value # Fail silently. return Truncator(value).words(length, truncate=" …") @register.filter(is_safe=True) @stringfilter def truncatewords_html(value, arg): """ Truncate HTML after `arg` number of words. Preserve newlines in the HTML. """ try: length = int(arg) except ValueError: # invalid literal for int() return value # Fail silently. return Truncator(value).words(length, html=True, truncate=" …") @register.filter(is_safe=False) @stringfilter def upper(value): """Convert a string into all uppercase.""" return value.upper() @register.filter(is_safe=False) @stringfilter def urlencode(value, safe=None): """ Escape a value for use in a URL. The ``safe`` parameter determines the characters which should not be escaped by Python's quote() function. If not provided, use the default safe characters (but an empty string can be provided when *all* characters should be escaped). """ kwargs = {} if safe is not None: kwargs["safe"] = safe return quote(value, **kwargs) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlize(value, autoescape=True): """Convert URLs in plain text into clickable links.""" return mark_safe(_urlize(value, nofollow=True, autoescape=autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def urlizetrunc(value, limit, autoescape=True): """ Convert URLs into clickable links, truncating URLs to the given character limit, and adding 'rel=nofollow' attribute to discourage spamming. Argument: Length to truncate URLs to. """ return mark_safe( _urlize(value, trim_url_limit=int(limit), nofollow=True, autoescape=autoescape) ) @register.filter(is_safe=False) @stringfilter def wordcount(value): """Return the number of words.""" return len(value.split()) @register.filter(is_safe=True) @stringfilter def wordwrap(value, arg): """Wrap words at `arg` line length.""" return wrap(value, int(arg)) @register.filter(is_safe=True) @stringfilter def ljust(value, arg): """Left-align the value in a field of a given width.""" return value.ljust(int(arg)) @register.filter(is_safe=True) @stringfilter def rjust(value, arg): """Right-align the value in a field of a given width.""" return value.rjust(int(arg)) @register.filter(is_safe=True) @stringfilter def center(value, arg): """Center the value in a field of a given width.""" width = int(arg) if width <= 0: return value return f"{value:^{width}}" @register.filter @stringfilter def cut(value, arg): """Remove all values of arg from the given string.""" safe = isinstance(value, SafeData) value = value.replace(arg, "") if safe and arg != ";": return mark_safe(value) return value ################### # HTML STRINGS # ################### @register.filter("escape", is_safe=True) @stringfilter def escape_filter(value): """Mark the value as a string that should be auto-escaped.""" return conditional_escape(value) @register.filter(is_safe=True) def escapeseq(value): """ An "escape" filter for sequences. Mark each element in the sequence, individually, as a string that should be auto-escaped. Return a list with the results. """ return [conditional_escape(obj) for obj in value] @register.filter(is_safe=True) @stringfilter def force_escape(value): """ Escape a string's HTML. Return a new string containing the escaped characters (as opposed to "escape", which marks the content for later possible escaping). """ return escape(value) @register.filter("linebreaks", is_safe=True, needs_autoescape=True) @stringfilter def linebreaks_filter(value, autoescape=True): """ Replace line breaks in plain text with appropriate HTML; a single newline becomes an HTML line break (``<br>``) and a new line followed by a blank line becomes a paragraph break (``</p>``). """ autoescape = autoescape and not isinstance(value, SafeData) return mark_safe(linebreaks(value, autoescape)) @register.filter(is_safe=True, needs_autoescape=True) @stringfilter def linebreaksbr(value, autoescape=True): """ Convert all newlines in a piece of plain text to HTML line breaks (``<br>``). """ autoescape = autoescape and not isinstance(value, SafeData) value = normalize_newlines(value) if autoescape: value = escape(value) return mark_safe(value.replace("\n", "<br>")) @register.filter(is_safe=True) @stringfilter def safe(value): """Mark the value as a string that should not be auto-escaped.""" return mark_safe(value) @register.filter(is_safe=True) def safeseq(value): """ A "safe" filter for sequences. Mark each element in the sequence, individually, as safe, after converting them to strings. Return a list with the results. """ return [mark_safe(obj) for obj in value] @register.filter(is_safe=True) @stringfilter def striptags(value): """Strip all [X]HTML tags.""" return strip_tags(value) ################### # LISTS # ################### def _property_resolver(arg): """ When arg is convertible to float, behave like operator.itemgetter(arg) Otherwise, chain __getitem__() and getattr(). >>> _property_resolver(1)('abc') 'b' >>> _property_resolver('1')('abc') Traceback (most recent call last): ... TypeError: string indices must be integers >>> class Foo: ... a = 42 ... b = 3.14 ... c = 'Hey!' >>> _property_resolver('b')(Foo()) 3.14 """ try: float(arg) except ValueError: if VARIABLE_ATTRIBUTE_SEPARATOR + "_" in arg or arg[0] == "_": raise AttributeError("Access to private variables is forbidden.") parts = arg.split(VARIABLE_ATTRIBUTE_SEPARATOR) def resolve(value): for part in parts: try: value = value[part] except (AttributeError, IndexError, KeyError, TypeError, ValueError): value = getattr(value, part) return value return resolve else: return itemgetter(arg) @register.filter(is_safe=False) def dictsort(value, arg): """ Given a list of dicts, return that list sorted by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg)) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def dictsortreversed(value, arg): """ Given a list of dicts, return that list sorted in reverse order by the property given in the argument. """ try: return sorted(value, key=_property_resolver(arg), reverse=True) except (AttributeError, TypeError): return "" @register.filter(is_safe=False) def first(value): """Return the first item in a list.""" try: return value[0] except IndexError: return "" @register.filter(is_safe=True, needs_autoescape=True) def join(value, arg, autoescape=True): """Join a list with a string, like Python's ``str.join(list)``.""" try: if autoescape: data = conditional_escape(arg).join([conditional_escape(v) for v in value]) else: data = arg.join(value) except TypeError: # Fail silently if arg isn't iterable. return value return mark_safe(data) @register.filter(is_safe=True) def last(value): """Return the last item in a list.""" try: return value[-1] except IndexError: return "" @register.filter(is_safe=False) def length(value): """Return the length of the value - useful for lists.""" try: return len(value) except (ValueError, TypeError): return 0 @register.filter(is_safe=True) def random(value): """Return a random item from the list.""" try: return random_module.choice(value) except IndexError: return "" @register.filter("slice", is_safe=True) def slice_filter(value, arg): """ Return a slice of the list using the same syntax as Python's list slicing. """ try: bits = [] for x in str(arg).split(":"): if not x: bits.append(None) else: bits.append(int(x)) return value[slice(*bits)] except (ValueError, TypeError, KeyError): return value # Fail silently. @register.filter(is_safe=True, needs_autoescape=True) def unordered_list(value, autoescape=True): """ Recursively take a self-nested list and return an HTML unordered list -- WITHOUT opening and closing <ul> tags. Assume the list is in the proper format. For example, if ``var`` contains: ``['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']]``, then ``{{ var|unordered_list }}`` returns:: <li>States <ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li> </ul> </li> """ if autoescape: escaper = conditional_escape else: def escaper(x): return x def walk_items(item_list): item_iterator = iter(item_list) try: item = next(item_iterator) while True: try: next_item = next(item_iterator) except StopIteration: yield item, None break if isinstance(next_item, (list, tuple, types.GeneratorType)): try: iter(next_item) except TypeError: pass else: yield item, next_item item = next(item_iterator) continue yield item, None item = next_item except StopIteration: pass def list_formatter(item_list, tabs=1): indent = "\t" * tabs output = [] for item, children in walk_items(item_list): sublist = "" if children: sublist = "\n%s<ul>\n%s\n%s</ul>\n%s" % ( indent, list_formatter(children, tabs + 1), indent, indent, ) output.append("%s<li>%s%s</li>" % (indent, escaper(item), sublist)) return "\n".join(output) return mark_safe(list_formatter(value)) ################### # INTEGERS # ################### @register.filter(is_safe=False) def add(value, arg): """Add the arg to the value.""" try: return int(value) + int(arg) except (ValueError, TypeError): try: return value + arg except Exception: return "" @register.filter(is_safe=False) def get_digit(value, arg): """ Given a whole number, return the requested digit of it, where 1 is the right-most digit, 2 is the second-right-most digit, etc. Return the original value for invalid input (if input or argument is not an integer, or if argument is less than 1). Otherwise, output is always an integer. """ try: arg = int(arg) value = int(value) except ValueError: return value # Fail silently for an invalid argument if arg < 1: return value try: return int(str(value)[-arg]) except IndexError: return 0 ################### # DATES # ################### @register.filter(expects_localtime=True, is_safe=False) def date(value, arg=None): """Format a date according to the given format.""" if value in (None, ""): return "" try: return formats.date_format(value, arg) except AttributeError: try: return format(value, arg) except AttributeError: return "" @register.filter(expects_localtime=True, is_safe=False) def time(value, arg=None): """Format a time according to the given format.""" if value in (None, ""): return "" try: return formats.time_format(value, arg) except (AttributeError, TypeError): try: return time_format(value, arg) except (AttributeError, TypeError): return "" @register.filter("timesince", is_safe=False) def timesince_filter(value, arg=None): """Format a date as the time since that date (i.e. "4 days, 6 hours").""" if not value: return "" try: if arg: return timesince(value, arg) return timesince(value) except (ValueError, TypeError): return "" @register.filter("timeuntil", is_safe=False) def timeuntil_filter(value, arg=None): """Format a date as the time until that date (i.e. "4 days, 6 hours").""" if not value: return "" try: return timeuntil(value, arg) except (ValueError, TypeError): return "" ################### # LOGIC # ################### @register.filter(is_safe=False) def default(value, arg): """If value is unavailable, use given default.""" return value or arg @register.filter(is_safe=False) def default_if_none(value, arg): """If value is None, use given default.""" if value is None: return arg return value @register.filter(is_safe=False) def divisibleby(value, arg): """Return True if the value is divisible by the argument.""" return int(value) % int(arg) == 0 @register.filter(is_safe=False) def yesno(value, arg=None): """ Given a string mapping values for true, false, and (optionally) None, return one of those strings according to the value: ========== ====================== ================================== Value Argument Outputs ========== ====================== ================================== ``True`` ``"yeah,no,maybe"`` ``yeah`` ``False`` ``"yeah,no,maybe"`` ``no`` ``None`` ``"yeah,no,maybe"`` ``maybe`` ``None`` ``"yeah,no"`` ``"no"`` (converts None to False if no mapping for None is given. ========== ====================== ================================== """ if arg is None: # Translators: Please do not add spaces around commas. arg = gettext("yes,no,maybe") bits = arg.split(",") if len(bits) < 2: return value # Invalid arg. try: yes, no, maybe = bits except ValueError: # Unpack list of wrong size (no "maybe" value provided). yes, no, maybe = bits[0], bits[1], bits[1] if value is None: return maybe if value: return yes return no ################### # MISC # ################### @register.filter(is_safe=True) def filesizeformat(bytes_): """ Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102 bytes, etc.). """ try: bytes_ = int(bytes_) except (TypeError, ValueError, UnicodeDecodeError): value = ngettext("%(size)d byte", "%(size)d bytes", 0) % {"size": 0} return avoid_wrapping(value) def filesize_number_format(value): return formats.number_format(round(value, 1), 1) KB = 1 << 10 MB = 1 << 20 GB = 1 << 30 TB = 1 << 40 PB = 1 << 50 negative = bytes_ < 0 if negative: bytes_ = -bytes_ # Allow formatting of negative numbers. if bytes_ < KB: value = ngettext("%(size)d byte", "%(size)d bytes", bytes_) % {"size": bytes_} elif bytes_ < MB: value = gettext("%s KB") % filesize_number_format(bytes_ / KB) elif bytes_ < GB: value = gettext("%s MB") % filesize_number_format(bytes_ / MB) elif bytes_ < TB: value = gettext("%s GB") % filesize_number_format(bytes_ / GB) elif bytes_ < PB: value = gettext("%s TB") % filesize_number_format(bytes_ / TB) else: value = gettext("%s PB") % filesize_number_format(bytes_ / PB) if negative: value = "-%s" % value return avoid_wrapping(value) @register.filter(is_safe=False) def pluralize(value, arg="s"): """ Return a plural suffix if the value is not 1, '1', or an object of length 1. By default, use 's' as the suffix: * If value is 0, vote{{ value|pluralize }} display "votes". * If value is 1, vote{{ value|pluralize }} display "vote". * If value is 2, vote{{ value|pluralize }} display "votes". If an argument is provided, use that string instead: * If value is 0, class{{ value|pluralize:"es" }} display "classes". * If value is 1, class{{ value|pluralize:"es" }} display "class". * If value is 2, class{{ value|pluralize:"es" }} display "classes". If the provided argument contains a comma, use the text before the comma for the singular case and the text after the comma for the plural case: * If value is 0, cand{{ value|pluralize:"y,ies" }} display "candies". * If value is 1, cand{{ value|pluralize:"y,ies" }} display "candy". * If value is 2, cand{{ value|pluralize:"y,ies" }} display "candies". """ if "," not in arg: arg = "," + arg bits = arg.split(",") if len(bits) > 2: return "" singular_suffix, plural_suffix = bits[:2] try: return singular_suffix if float(value) == 1 else plural_suffix except ValueError: # Invalid string that's not a number. pass except TypeError: # Value isn't a string or a number; maybe it's a list? try: return singular_suffix if len(value) == 1 else plural_suffix except TypeError: # len() of unsized object. pass return "" @register.filter("phone2numeric", is_safe=True) def phone2numeric_filter(value): """Take a phone number and converts it in to its numerical equivalent.""" return phone2numeric(value) @register.filter(is_safe=True) def pprint(value): """A wrapper around pprint.pprint -- for debugging, really.""" try: return pformat(value) except Exception as e: return "Error in formatting: %s: %s" % (e.__class__.__name__, e)
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false
django/django
https://github.com/django/django/blob/3201a895cba335000827b28768a7b7105c81b415/django/template/loader.py
django/template/loader.py
from . import engines from .exceptions import TemplateDoesNotExist def get_template(template_name, using=None): """ Load and return a template for the given name. Raise TemplateDoesNotExist if no such template exists. """ chain = [] engines = _engine_list(using) for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) raise TemplateDoesNotExist(template_name, chain=chain) def select_template(template_name_list, using=None): """ Load and return a template for one of the given names. Try names in order and return the first template found. Raise TemplateDoesNotExist if no such template exists. """ if isinstance(template_name_list, str): raise TypeError( "select_template() takes an iterable of template names but got a " "string: %r. Use get_template() if you want to load a single " "template by name." % template_name_list ) chain = [] engines = _engine_list(using) for template_name in template_name_list: for engine in engines: try: return engine.get_template(template_name) except TemplateDoesNotExist as e: chain.append(e) if template_name_list: raise TemplateDoesNotExist(", ".join(template_name_list), chain=chain) else: raise TemplateDoesNotExist("No template names provided") def render_to_string(template_name, context=None, request=None, using=None): """ Load a template and render it with a context. Return a string. template_name may be a string or a list of strings. """ if isinstance(template_name, (list, tuple)): template = select_template(template_name, using=using) else: template = get_template(template_name, using=using) return template.render(context, request) def _engine_list(using=None): return engines.all() if using is None else [engines[using]]
python
BSD-3-Clause
3201a895cba335000827b28768a7b7105c81b415
2026-01-04T14:38:15.489092Z
false