one, env=None, dry_run=True):
    """Run a command with optional dry-run behavior."""
    environ = os.environ.copy()
    if env:
        environ.update(env)
    if dry_run:
        print("[DRY RUN]", " ".join(cmd))
    else:
        print("[EXECUTE]", " ".join(cmd))
        try:
            result = subprocess.check_output(
                cmd, cwd=cwd, env=environ, stderr=subprocess.STDOUT
            )
        except subprocess.CalledProcessError as e:
            result = e.output
            print("

ctory not provided (--checkout-dir).")
    if not os.path.exists(checkout_dir):
        sys.exit(f"Error: checkout directory '{checkout_dir}' does not exist.")
    if not os.path.isdir(checkout_dir):
        sys.exit(f"Error: '{checkout_dir}' is not a dire

 [ERROR]", result)
            raise
        else:
            print("    [RESULT]", result)
        return result.decode().strip()

def validate_env(checkout_dir):
    if not checkout_dir:
        sys.exit("Error: checkout dire


rocess
from datetime import date

checksum_file_text = """This file contains MD5, SHA1, and SHA256 checksums for the
source-code tarball and wheel files of Django {django_version}, released {release_date}.

It also includes the commit hash of the release tag, identifying the exact
source revision the artifacts were built from.

To use this file, you will need a working install of PGP or other
compatible public-key encryption software. You will also need to have
the Django release manager's public key in you

or via the GitHub API:

    curl {pgp_key_url} | gpg --import -

Once the key is imported, verify this file:

    gpg --verify {checksum_file_name}

Once you have verified this file, you can use normal MD5, SHA1, or SHA256
checksumming applications to gene

r keyring. This key has
the ID ``{pgp_key_id}`` and can be imported from the MIT
keyserver, for example, if using the open-source GNU Privacy Guard
implementation of PGP:

    gpg --keyserver pgp.mit.edu --recv-key {pgp_key_id}


on any branch:
- Ensures the summary line ends with a period.

Additionally, on stable branches:
- Adds the [A.B.x] branch prefix if missing.
- Adds "Backport of <sha> from main." when cherry-picking.

To install:
  1. Ensure the folder `.git/hooks` exists.
  2. Create an executable file `.git/hooks/prepare-commit-msg` with content:

#!/bin/sh
exec python scripts/prepare_commit_msg.py "$@"

"""

import os
import subprocess
import sys

def run(cmd):
    return subprocess.run(cmd, capture_output=True, text=T

ds with a period.
    - On stable branches, adds the [A.B.x] prefix to the first line if missing.
    - If cherry_sha is provided, appends "Backport of <sha> from main." to
      the body if not already present.

    Returns the modified lines (body + comm

rue).stdout.strip()

def process_commit_message(lines, branch, cherry_sha=None):
    """Adjust commit message lines for a potential backport.

    - Separates body lines from trailing git comment lines.
    - Ensure all lines en


ting-code/#committing-guidelines)).",
        "I have not requested, and will not request, an automated AI review"
        " for this PR."
        " <!-- You are welcome to do so in your own fork. -->",
        'I have checked the "Has patch" ticket flag in the Trac system.',
        "I have added or updated relevant tests.",
        "I have added or updated relevant docs, including release notes if"
        " applicable.",
        "I have attached screenshots in both light and dark modes for any UI"

ading spaces.
    return (
        f"#### Trac ticket number\n"
        f"<!-- Replace XXXXX with the corresponding Trac ticket number. -->\n"
        f'<!-- Or delete the line and write "N/A - typo" for typo fixes. -->\n'
        f"\n"
        f"{ticket}\

  " changes.",
    ]
    checklist_lines = "\n".join(
        f"- [x] {item}" if i < checked_items else f"- [ ] {item}"
        for i, item in enumerate(checklist_items)
    )

    # GitHub PR bodies are plain markdown with no le


on Middleware.

This module provides a middleware that implements protection against a
malicious site loading resources from your site in a hidden frame.
"""

from django.conf import settings
from django.utils.deprecation import MiddlewareMixin

class XFrameOptionsMiddleware(MiddlewareMixin):
    """
    Set the X-Frame-Options HTTP header in HTTP responses.

    Do not set the header if it's already set or if the response contains
    a xframe_options_exempt value set to True.

    By default, set the X-F

in your project's Django settings to 'SAMEORIGIN'.
    """

    def process_response(self, request, response):
        # Don't set it if it's already in the response
        if response.get("X-Frame-Options") is not None:
            return response

rame-Options header to 'DENY', meaning the response
    cannot be displayed in a frame, regardless of the site attempting to do so.
    To enable the response to be loaded on a frame within the same site, set
    X_FRAME_OPTIONS


rom django.utils.deprecation import MiddlewareMixin
from django.utils.regex_helper import _lazy_re_compile
from django.utils.text import acompress_sequence, compress_sequence, compress_string

re_accepts_gzip = _lazy_re_compile(r"\bgzip\b")

class GZipMiddleware(MiddlewareMixin):
    """
    Compress content if the browser allows gzip compression.
    Set the Vary header accordingly, so that caches will base their storage
    on the Accept-Encoding header.
    """

    max_random_bytes = 100

    def proce

g if we've already got a content-encoding.
        if response.has_header("Content-Encoding"):
            return response

        patch_vary_headers(response, ("Accept-Encoding",))

        ae = request.META.get("HTTP_ACCEPT_ENCODING", "")
        if not

ss_response(self, request, response):
        # It's not worth attempting to compress really short responses.
        if not response.streaming and len(response.content) < 200:
            return response

        # Avoid gzippin


None, flags=None
    ):
        if regex is not None:
            self.regex = regex
        if message is not None:
            self.message = message
        if code is not None:
            self.code = code
        if inverse_match is not None:
            self.inverse_match = inverse_match
        if flags is not None:
            self.flags = flags
        if self.flags and not isinstance(self.regex, str):
            raise TypeError(
                "If the flags are set, regex must be a regular expre

True) a match for the regular expression.
        """
        regex_matches = self.regex.search(str(value))
        invalid_input = regex_matches if self.inverse_match else not regex_matches
        if invalid_input:
            raise ValidationError(self.

ssion string."
            )

        self.regex = _lazy_re_compile(self.regex, self.flags)

    def __call__(self, value):
        """
        Validate that the input contains (or does *not* contain, if
        inverse_match is


inted error
    message to the appropriate output stream (i.e., stderr); as a
    result, raising this exception (with a sensible description of the
    error) is the preferred way to indicate that something has gone
    wrong in the execution of a command.
    """

    def __init__(self, *args, returncode=1, **kwargs):
        self.returncode = returncode
        super().__init__(*args, **kwargs)

class SystemCheckError(CommandError):
    """
    The system check framework detected unrecoverable errors.

is called programmatically.
    """

    def __init__(
        self, *, missing_args_message=None, called_from_command_line=None, **kwargs
    ):
        self.missing_args_message = missing_args_message
        self.called_from_command_line = called_from_c

   """

    pass

class CommandParser(ArgumentParser):
    """
    Customized ArgumentParser class to improve some error messages and prevent
    SystemExit in several occasions, as SystemExit is unacceptable when a
    command


.startswith("_") or not k.isupper()):
    """Convert a module namespace to a Python dictionary."""
    return {k: repr(getattr(module, k)) for k in dir(module) if not omittable(k)}

class Command(BaseCommand):
    help = """Displays differences between the current settings.py and Django's
    default settings."""

    requires_system_checks = []

    def add_arguments(self, parser):
        parser.add_argument(
            "--all",
            action="store_true",
            help=(
                'Displa

         help=(
                "The settings module to compare the current settings against. Leave "
                "empty to compare against Django's default settings."
            ),
        )
        parser.add_argument(
            "--output",

y all settings, regardless of their value. In "hash" '
                'mode, default values are prefixed by "###".'
            ),
        )
        parser.add_argument(
            "--default",
            metavar="MODULE",


o.core.mail import mail_admins, mail_managers, send_mail
from django.core.management.base import BaseCommand
from django.utils import timezone

class Command(BaseCommand):
    help = "Sends a test email to the email addresses specified as arguments."
    missing_args_message = (
        "You must specify some email recipients, or pass the --managers or --admin "
        "options."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "email",
            nargs="*",

ttings.MANAGERS.",
        )
        parser.add_argument(
            "--admins",
            action="store_true",
            help="Send a test email to the addresses specified in settings.ADMINS.",
        )

    def handle(self, *args, **kwargs):

  help="One or more email addresses to send a test email to.",
        )
        parser.add_argument(
            "--managers",
            action="store_true",
            help="Send a test email to the addresses specified in se


m django.core.management.base import BaseCommand
from django.db import connection

class Command(BaseCommand):
    help = "Runs a development server with data from the given fixture(s)."

    requires_system_checks = []

    def add_arguments(self, parser):
        parser.add_argument(
            "args",
            metavar="fixture",
            nargs="*",
            help="Path(s) to fixtures to load before running the server.",
        )
        parser.add_argument(
            "--noinput",

        default="",
            help="Port number or ipaddr:port to run the server on.",
        )
        parser.add_argument(
            "--ipv6",
            "-6",
            action="store_true",
            dest="use_ipv6",
            help="Tells Dj

 "--no-input",
            action="store_false",
            dest="interactive",
            help="Tells Django to NOT prompt the user for input of any kind.",
        )
        parser.add_argument(
            "--addrport",


giref import simple_server

from django.core.exceptions import ImproperlyConfigured
from django.core.handlers.wsgi import LimitedStream
from django.core.wsgi import get_wsgi_application
from django.db import connections
from django.utils.log import log_message
from django.utils.module_loading import import_string

__all__ = ("WSGIServer", "WSGIRequestHandler")

logger = logging.getLogger("django.server")

def get_internal_wsgi_application():
    """
    Load and return the WSGI application as configured by

e only useful
    for Django's internal server (runserver); external WSGI servers should just
    be configured to point to the correct application object directly.

    If settings.WSGI_APPLICATION is not set (is ``None``), return
    whatever ``django.co

 the user in
    ``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
    this will be the ``application`` object in ``projectname/wsgi.py``.

    This function, and the ``WSGI_APPLICATION`` setting itself, ar


(__file__).resolve().parent.parent
    sys.path[:0] = [str(repo_root / "tests"), str(repo_root)]

    from runtests import ALWAYS_INSTALLED_APPS, get_apps_to_install, get_test_modules

    import django
    from django.apps import apps
    from django.core.management import call_command

    django.setup()

    test_modules = list(get_test_modules(gis_enabled=False))
    installed_apps = list(ALWAYS_INSTALLED_APPS)
    for app in get_apps_to_install(test_modules):
        # Check against the list to prevent

pps:
            installed_apps.append(app)
    apps.set_installed_apps(installed_apps)

    # Note: We don't use check=True here because --check calls sys.exit(1)
    # instead of raising CommandError when migrations are missing.
    call_command("makemig

 duplicate errors.
        if app not in installed_a


ion
#
# * fetch: fetch translations from transifex.com
#
# Each command support the --languages and --resources options to limit their
# operation to the specified language or resource. For example, to get stats
# for Spanish in contrib.admin, run:
#
#  $ python scripts/manage_translations.py lang_stats -l es -r admin
#
# Also each command supports a --verbosity option to get progress feedback.

import json
import os
import subprocess
from argparse import ArgumentParser
from collections import defaultdict
f

]
LANG_OVERRIDES = {
    "zh_CN": "zh_Hans",
    "zh_TW": "zh_Hant",
}

def run(*args, verbosity=0, **kwargs):
    if verbosity > 1:
        print(f"\n** subprocess.run ** command: {args=} {kwargs=}")
    return subprocess.run(*args, **kwargs)

def get_a

rom configparser import ConfigParser
from datetime import datetime
from itertools import product

import requests

import django
from django.conf import settings
from django.core.management import call_command

HAVE_JS = ["admin"


ommit_msg import process_commit_message

class ParseMajorVersionTests(unittest.TestCase):
    def test_final_patch_release(self):
        self.assertEqual(parse_major_version("5.2.4"), "5.2")

    def test_final_dot_zero_release(self):
        self.assertEqual(parse_major_version("6.0"), "6.0")

    def test_alpha(self):
        self.assertEqual(parse_major_version("6.0a1"), "6.0")

    def test_beta(self):
        self.assertEqual(parse_major_version("6.0b1"), "6.0")

    def test_release_candidate(self):

NTENT = b"fake wheel content"
    TARBALL_CONTENT = b"fake tarball content"

    def generate_checksum_file(self, **overrides):
        with tempfile.TemporaryDirectory() as tmp:
            dist_path = os.path.join(tmp, "dist")
            os.mkdir(dist_p

        self.assertEqual(parse_major_version("6.0rc1"), "6.0")

    def test_two_digit_minor(self):
        self.assertEqual(parse_major_version("5.10a1"), "5.10")

class CreateChecksumFileTests(unittest.TestCase):
    WHEEL_CO


time.

"""

LEVEL_ERROR = ("🛑", "Error")
LEVEL_WARNING = ("⚠", "Warning")

class Message:
    """A PR quality check message bound to its runtime formatting kwargs."""

    def __init__(self, title, body, **kwargs):
        self.title = title
        self.body = body
        self.kwargs = kwargs

    def as_details(self, level=LEVEL_ERROR):
        body = self.body.format(**self.kwargs) if self.kwargs else self.body
        symbol, label = level
        return (
            f"<details>\n<summary><strong>{s

code/submitting-patches/"
TRIAGING_URL = f"{CONTRIBUTING_URL}triaging-tickets/"
FORUM_URL = "https://forum.djangoproject.com"
TRAC_URL = "https://code.djangoproject.com"

CHECKS_HEADER = (
    "Thank you for your contribution to Django! This pull request

ymbol} {label}: {self.title}"
            f"\n\n{body}\n\n"
        )

CONTRIBUTING_URL = "https://docs.djangoproject.com/en/dev/internals/contributing/"
SUBMITTING_URL = f"{CONTRIBUTING_URL}writing-


on
import logging
import os
import re
import sys
import time
import urllib.error
import urllib.parse
import urllib.request
from datetime import date, datetime, timedelta, timezone
from http import HTTPStatus

from pr_quality.errors import (
    CHECKS_FOOTER,
    CHECKS_HEADER,
    INCOMPLETE_CHECKLIST,
    INVALID_TRAC_STATUS,
    LEVEL_ERROR,
    LEVEL_WARNING,
    MISSING_AI_DESCRIPTION,
    MISSING_AI_DISCLOSURE,
    MISSING_DESCRIPTION,
    MISSING_HAS_PATCH_FLAG,
    MISSING_TICKET_IN_PR_TITLE,
    MI

inel: Trac returned HTTP 404 for the ticket.
URLOPEN_TIMEOUT_SECONDS = 15
# PRs opened before these dates predate PR template additions.
PR_TEMPLATE_DATE = date(2024, 3, 4)  # 3fcef50 -- PR template introduced
AI_DISCLOSURE_DATE = date(2026, 1, 8)  # 4f580

SSING_TRAC_TICKET,
    Message,
)

GITHUB_PER_PAGE = 100
LARGE_PR_THRESHOLD = 80  # additions + deletions
MIN_WORDS = 5
SKIPPED = object()  # Sentinel: check was not applicable and was skipped.
TICKET_NOT_FOUND = object()  # Sent


p import (
    Http404,
    HttpResponse,
    HttpResponsePermanentRedirect,
    HttpResponseRedirect,
)
from django.template import loader
from django.urls import NoReverseMatch, reverse
from django.utils.functional import Promise
from django.utils.http import MAX_URL_REDIRECT_LENGTH
from django.utils.translation import gettext as _

def render(
    request, template_name, context=None, content_type=None, status=None, using=None
):
    """
    Return an HttpResponse whose content is filled with the result

s)

def redirect(
    to,
    *args,
    permanent=False,
    preserve_request=False,
    max_length=MAX_URL_REDIRECT_LENGTH,
    **kwargs,
):
    """
    Return an HttpResponseRedirect to the appropriate URL for the arguments
    passed.

    The argumen

 of calling
    django.template.loader.render_to_string() with the passed arguments.
    """
    content = loader.render_to_string(template_name, context, request, using=using)
    return HttpResponse(content, content_type, statu


django.utils.version import get_version

VERSION = (6, 2, 0, "alpha", 0)

__version__ = get_version(VERSION)

def setup(set_prefix=True):
    """
    Configure the settings (this happens as a side effect of accessing the
    first setting), configure logging and populate the app registry.
    Set the thread-local urlresolvers script prefix if `set_prefix` is True.
    """
    from django.apps import apps
    from django.conf import settings
    from django.urls import set_script_prefix
    from django.util

onfigure_logging

    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
    if set_prefix:
        set_script_prefix(
            "/" if settings.FORCE_SCRIPT_NAME is None else settings.FORCE_SCRIPT_NAME
        )
    apps.populate(settings.INST


and
``FetchFromCacheMiddleware`` as the last::

    MIDDLEWARE = [
        'django.middleware.cache.UpdateCacheMiddleware',
        ...
        'django.middleware.cache.FetchFromCacheMiddleware'
    ]

This is counterintuitive, but correct: ``UpdateCacheMiddleware`` needs to run
last during the response phase, which processes middleware bottom-up;
``FetchFromCacheMiddleware`` needs to run last during the request phase, which
processes middleware top-down.

The single-class ``CacheMiddleware`` can be used fo

Django's ``LocaleMiddleware``.

More details about how the caching works:

* Only GET or HEAD-requests with status code 200 are cached.

* The number of seconds each page is stored for is set by the "max-age" section
  of the response's "Cache-Control" he

r some simple sites.
However, if any other piece of middleware needs to affect the cache key, you'll
need to use the two-part ``UpdateCacheMiddleware`` and
``FetchFromCacheMiddleware``. This'll most often happen when you're using


conf import settings
from django.utils.csp import CSP, LazyNonce, build_policy
from django.utils.deprecation import MiddlewareMixin

def get_nonce(request):
    return getattr(request, "_csp_nonce", None)

class ContentSecurityPolicyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        request._csp_nonce = LazyNonce()

    def process_response(self, request, response):
        nonce = get_nonce(request)

        sentinel = object()
        if (csp_config := getattr(response, "_csp_c

      for header, config in [
            (CSP.HEADER_ENFORCE, csp_config),
            (CSP.HEADER_REPORT_ONLY, csp_ro_config),
        ]:
            # If headers are already set on the response, don't overwrite them.
            # This allows for views

onfig", sentinel)) is sentinel:
            csp_config = settings.SECURE_CSP
        if (csp_ro_config := getattr(response, "_csp_ro_config", sentinel)) is sentinel:
            csp_ro_config = settings.SECURE_CSP_REPORT_ONLY


om django.http import HttpResponsePermanentRedirect
from django.urls import is_valid_path
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import escape_leading_slashes

class CommonMiddleware(MiddlewareMixin):
    """
    "Common" middleware for taking care of some basic operations:

        - Forbid access to User-Agents in settings.DISALLOWED_USER_AGENTS

        - URL rewriting: Based on the APPEND_SLASH and PREPEND_WWW settings,
          append missing slashes and/or prepen

RL is found in
              urlpatterns, return an HTTP redirect to this new URL; otherwise
              process the initial URL as usual.

          This behavior can be customized by subclassing CommonMiddleware and
          overriding the response_re

ds missing "www."s.

            - If APPEND_SLASH is set and the initial URL doesn't end with a
              slash, and it is not found in urlpatterns, form a new URL by
              appending a slash at the end. If this new U


ile

logger = logging.getLogger("django.security.csrf")
# This matches if any character is not in CSRF_ALLOWED_CHARS.
invalid_token_chars_re = _lazy_re_compile("[^a-zA-Z0-9]")

REASON_BAD_ORIGIN = "Origin checking failed - %s does not match any trusted origins."
REASON_NO_REFERER = "Referer checking failed - no Referer."
REASON_BAD_REFERER = "Referer checking failed - %s does not match any trusted origins."
REASON_NO_CSRF_COOKIE = "CSRF cookie not set."
REASON_CSRF_TOKEN_MISSING = "CSRF token missing."
REAS

dTokenFormat. They are
# phrases without a subject because they can be in reference to either the CSRF
# cookie or non-cookie token.
REASON_INCORRECT_LENGTH = "has incorrect length"
REASON_INVALID_CHARACTERS = "has invalid characters"

CSRF_SECRET_LENGTH =

ON_MALFORMED_REFERER = "Referer checking failed - Referer is malformed."
REASON_INSECURE_REFERER = (
    "Referer checking failed - Referer is insecure while host is secure."
)
# The reason strings below are for passing to Invali


mport cc_delim_re, get_conditional_response, set_response_etag
from django.utils.deprecation import MiddlewareMixin
from django.utils.http import parse_http_date_safe

class ConditionalGetMiddleware(MiddlewareMixin):
    """
    Handle conditional GET operations. If the response has an ETag or
    Last-Modified header and the request has If-None-Match or
    If-Modified-Since, replace the response with HttpNotModified. Add an ETag
    header if needed.
    """

    def process_response(self, request, respo

 != "GET":
            return response

        if self.needs_etag(response) and not response.has_header("ETag"):
            set_response_etag(response)

        etag = response.get("ETag")
        last_modified = response.get("Last-Modified")
        las

nse):
        # It's too late to prevent an unsafe request with a 412 response, and
        # for a HEAD request, the response body is always empty so computing
        # an accurate ETag isn't possible.
        if request.method


ango.http import HttpResponsePermanentRedirect
from django.utils.deprecation import MiddlewareMixin

class SecurityMiddleware(MiddlewareMixin):
    def __init__(self, get_response):
        super().__init__(get_response)
        self.sts_seconds = settings.SECURE_HSTS_SECONDS
        self.sts_include_subdomains = settings.SECURE_HSTS_INCLUDE_SUBDOMAINS
        self.sts_preload = settings.SECURE_HSTS_PRELOAD
        self.content_type_nosniff = settings.SECURE_CONTENT_TYPE_NOSNIFF
        self.redirect = set

Y
        self.cross_origin_opener_policy = settings.SECURE_CROSS_ORIGIN_OPENER_POLICY

    def process_request(self, request):
        path = request.path.lstrip("/")
        if (
            self.redirect
            and not request.is_secure()

tings.SECURE_SSL_REDIRECT
        self.redirect_host = settings.SECURE_SSL_HOST
        self.redirect_exempt = [re.compile(r) for r in settings.SECURE_REDIRECT_EXEMPT]
        self.referrer_policy = settings.SECURE_REFERRER_POLIC


validPage(Exception):
    pass

class PageNotAnInteger(InvalidPage):
    pass

class EmptyPage(InvalidPage):
    pass

class BasePaginator:
    # Translators: String used to replace omitted page numbers in elided page
    # range generated by paginators, e.g. [1, 2, '…', 5, 6, 7, '…', 9, 10].
    ELLIPSIS = _("…")
    default_error_messages = {
        "invalid_page": _("That page number is not an integer"),
        "min_page": _("That page number is less than 1"),
        "no_results": _("That page cont

       self._check_object_list_is_ordered()
        self.per_page = int(per_page)
        self.orphans = int(orphans)
        self.allow_empty_first_page = allow_empty_first_page
        self.error_messages = (
            self.default_error_messages

ains no results"),
    }

    def __init__(
        self,
        object_list,
        per_page,
        orphans=0,
        allow_empty_first_page=True,
        error_messages=None,
    ):
        self.object_list = object_list


om django.http import HttpResponseRedirect
from django.urls import get_script_prefix, is_valid_path
from django.utils import translation
from django.utils.cache import patch_vary_headers
from django.utils.deprecation import MiddlewareMixin

class LocaleMiddleware(MiddlewareMixin):
    """
    Parse a request and decide what translation object to install in the
    current thread context. This allows pages to be dynamically translated to
    the language the user desires (if the language is available).

default_language,
        ) = is_language_prefix_patterns_used(urlconf)
        language = translation.get_language_from_request(
            request, check_path=i18n_patterns_used
        )
        language_from_path = translation.get_language_from_path(r

"""

    response_redirect_class = HttpResponseRedirect

    def process_request(self, request):
        urlconf = getattr(request, "urlconf", settings.ROOT_URLCONF)
        (
            i18n_patterns_used,
            prefixed_


signing.loads(s) checks the signature and returns the deserialized object.
If the signature fails, a BadSignature exception is raised.

>>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv422nZA4sgmk")
'hello'
>>> signing.loads("ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified")
...
BadSignature: Signature "ImhlbGxvIg:1QaUZC:YIye-ze3TTx7gtSv42-modified" does
not match

You can optionally compress the JSON prior to base64 encoding it to save
space, using the compress=True argument. This checks if compression a

'

The fact that the string is compressed is signalled by the prefixed '.' at the
start of the base64 JSON.

There are 65 url-safe characters: the 64 used by url-safe base64 and the ':'.
These functions make use of all of them.
"""

import base64
import da

ctually
helps and only applies compression if the result is a shorter string:

>>> signing.dumps(list(range(1, 20)), compress=True)
'.eJwFwcERACAIwLCF-rCiILN47r-GyZVJsNgkxaFxoDgxcOHGxMKD_T7vhAml:1QaUaL:BA0thEZrp4FQVXIXuOvYJtLJSrQ


s

class AppRegistryNotReady(Exception):
    """The django.apps registry is not populated yet"""

    pass

class ObjectDoesNotExist(Exception):
    """The requested object does not exist"""

    silent_variable_failure = True

class ObjectNotUpdated(Exception):
    """The updated object no longer exists."""

class MultipleObjectsReturned(Exception):
    """The query returned multiple objects when only one was expected."""

    pass

class SuspiciousOperation(Exception):
    """The user did something s

 attempted"""

    pass

class DisallowedHost(SuspiciousOperation):
    """HTTP_HOST header contains invalid value"""

    pass

class DisallowedRedirect(SuspiciousOperation):
    """Redirect was too long or scheme was not in allowed list."""

    pass

uspicious"""

class SuspiciousMultipartForm(SuspiciousOperation):
    """Suspect MIME request in multipart form data"""

    pass

class SuspiciousFileOperation(SuspiciousOperation):
    """A Suspicious filesystem operation was


s.log import log_response
from django.utils.module_loading import import_string

from .exception import convert_exception_to_response

logger = logging.getLogger("django.request")

class BaseHandler:
    _view_middleware = None
    _template_response_middleware = None
    _exception_middleware = None
    _middleware_chain = None

    def load_middleware(self, is_async=False):
        """
        Populate middleware lists from settings.MIDDLEWARE.

        Must be called after the environment is fixed (see

else self._get_response
        handler = convert_exception_to_response(get_response)
        handler_is_async = is_async
        for middleware_path in reversed(settings.MIDDLEWARE):
            middleware = import_string(middleware_path)
            midd

__call__ in
        subclasses).
        """
        self._view_middleware = []
        self._template_response_middleware = []
        self._exception_middleware = []

        get_response = self._get_response_async if is_async


import set_script_prefix
from django.utils.encoding import repercent_broken_unicode
from django.utils.functional import cached_property
from django.utils.regex_helper import _lazy_re_compile

_slashes_re = _lazy_re_compile(rb"/+")

class LimitedStream(IOBase):
    """
    Wrap another stream to disallow reading it past a number of bytes.

    Based on the implementation from werkzeug.wsgi.LimitedStream. See:
    https://github.com/pallets/werkzeug/blob/dbf78f67/src/werkzeug/wsgi.py#L828
    """

    def __

f.limit
        if _pos >= limit:
            return b""
        if size == -1 or size is None:
            size = limit - _pos
        else:
            size = min(size, limit - _pos)
        data = self._read(size)
        self._pos += len(data)

init__(self, stream, limit):
        self._read = stream.read
        self._readline = stream.readline
        self._pos = 0
        self.limit = limit

    def read(self, size=-1, /):
        _pos = self._pos
        limit = sel


gement_dir, "commands")
    return [
        name
        for _, name, is_pkg in pkgutil.iter_modules([command_dir])
        if not is_pkg and not name.startswith("_")
    ]

def load_command_class(app_name, name):
    """
    Given a command name and an application name, return the Command
    class instance. Allow all errors raised by the import process
    (ImportError, AttributeError) to propagate.
    """
    module = import_module("%s.management.commands.%s" % (app_name, name))
    return module.Comm

-- if a commands package exists, register all
    commands in that package.

    Core commands are always included. If a settings module has been
    specified, also include user-defined commands.

    The dictionary is in the format {command_name: app_nam

and()

@functools.cache
def get_commands():
    """
    Return a dictionary mapping command names to their callback applications.

    Look for a management.commands package in django.core, and in each
    installed application


rt (
    FileResponse,
    HttpRequest,
    HttpResponse,
    HttpResponseBadRequest,
    HttpResponseServerError,
    QueryDict,
    parse_cookie,
)
from django.urls import set_script_prefix
from django.utils.functional import cached_property

logger = logging.getLogger("django.request")

def get_script_prefix(scope):
    """
    Return the script prefix to use from either the scope or a setting.
    """
    if settings.FORCE_SCRIPT_NAME:
        return settings.FORCE_SCRIPT_NAME
    return scope.get("roo

up on trying to read a request
    # body and aborts.
    body_receive_timeout = 60

    def __init__(self, scope, body_file):
        self.scope = scope
        self._post_parse_error = False
        self._read_started = False
        self.resolver_match

t_path", "") or ""

class ASGIRequest(HttpRequest):
    """
    Custom request subclass that decodes from an ASGI-standard request dict
    and wraps request body handling.
    """

    # Number of seconds until a Request gives


 django.core.exceptions import (
    BadRequest,
    PermissionDenied,
    RequestDataTooBig,
    SuspiciousOperation,
    TooManyFieldsSent,
    TooManyFilesSent,
)
from django.http import Http404
from django.http.multipartparser import MultiPartParserError
from django.urls import get_resolver, get_urlconf
from django.utils.log import log_response
from django.views import debug

def convert_exception_to_response(get_response):
    """
    Wrap the given get_response callable in exception-to-response conve

    converted to 500 responses.

    This decorator is automatically applied to all middleware to ensure that
    no middleware leaks an exception and that the next middleware in the stack
    can rely on getting a response instead of an exception.
    ""

rsion.

    All exceptions will be converted. All known 4xx exceptions (Http404,
    PermissionDenied, MultiPartParserError, SuspiciousOperation) will be
    converted to the appropriate response, and all other exceptions will be


mport termcolors

try:
    import colorama

    # Avoid initializing colorama in non-Windows platforms.
    colorama.just_fix_windows_console()
except (
    AttributeError,  # colorama <= 0.4.6.
    ImportError,  # colorama is not installed.
    # If just_fix_windows_console() accesses sys.stdout with
    # WSGIRestrictedStdout.
    OSError,
):
    HAS_COLORAMA = False
else:
    HAS_COLORAMA = True

def supports_color():
    """
    Return True if the running system's terminal supports color,
    and False

   """
        try:
            # winreg is only available on Windows.
            import winreg
        except ImportError:
            return False
        else:
            try:
                reg_key = winreg.OpenKey(winreg.HKEY_CURRENT_USER, "Console

 otherwise.
    """

    def vt_codes_enabled_in_windows_registry():
        """
        Check the Windows Registry to see if VT code handling has been enabled
        by default, see https://superuser.com/a/1300251/447564.


ango.template import Context, Engine
from django.utils import archive
from django.utils.http import parse_header_parameters
from django.utils.version import get_docs_version

class TemplateCommand(BaseCommand):
    """
    Copy either a Django application layout template or a Django project
    layout template into the specified directory.

    :param style: A color style object (see django.core.management.color).
    :param app_or_project: The string 'app' or 'project'.
    :param name: The name of the ap

supported URL schemes
    url_schemes = ["http", "https", "ftp"]
    # Rewrite the following suffixes when determining the target filename.
    rewrite_template_suffixes = (
        # Allow shipping invalid .py files without byte-compilation.
        (".py

plication or project.
    :param directory: The directory to which the template should be copied.
    :param options: The additional variables passed to project or app templates
    """

    requires_system_checks = []
    # The


rypto import get_random_string
from django.utils.encoding import DEFAULT_LOCALE_ENCODING

from .base import CommandError, CommandParser

def popen_wrapper(args, stdout_encoding="utf-8"):
    """
    Friendly wrapper around Popen.

    Return stdout output, stderr output, and OS status code.
    """
    try:
        p = run(args, capture_output=True, close_fds=os.name != "nt")
    except OSError as err:
        raise CommandError("Error executing %s" % args[0]) from err
    return (
        p.stdout.decode(

sed by
    using --extension/-e multiple times.

    For example: running 'django-admin makemessages -e js,txt -e xhtml -a'
    would result in an extension list: ['.js', '.txt', '.xhtml']

    >>> handle_extensions(['.html', 'html,js,py,py,py,.py', 'py,.p

stdout_encoding),
        p.stderr.decode(DEFAULT_LOCALE_ENCODING, errors="replace"),
        p.returncode,
    )

def handle_extensions(extensions):
    """
    Organize multiple extensions that are separated with commas or pas


db import BaseDatabaseCache
from django.core.management.base import BaseCommand, CommandError
from django.db import (
    DEFAULT_DB_ALIAS,
    DatabaseError,
    connections,
    models,
    router,
    transaction,
)

class Command(BaseCommand):
    help = "Creates the tables needed to use the SQL cache backend."

    requires_system_checks = []

    def add_arguments(self, parser):
        parser.add_argument(
            "args",
            metavar="table_name",
            nargs="*",
            help=

ALIAS,
            choices=tuple(connections),
            help="Nominates a database onto which the cache tables will be "
            'installed. Defaults to the "default" database.',
        )
        parser.add_argument(
            "--dry-run",

(
                "Optional table names. Otherwise, settings.CACHES is used to find "
                "cache tables."
            ),
        )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_


pps import apps
from django.db import models

def sql_flush(style, connection, reset_sequences=True, allow_cascade=False):
    """
    Return a list of the SQL statements used to flush the database.
    """
    tables = connection.introspection.django_table_names(
        only_existing=True, include_views=False
    )
    return connection.ops.sql_flush(
        style,
        tables,
        reset_sequences=reset_sequences,
        allow_cascade=allow_cascade,
    )

def emit_pre_migrate_signal(verbosity,

        stdout = kwargs.get("stdout", sys.stdout)
            stdout.write(
                "Running pre-migrate handlers for application %s" % app_config.label
            )
        models.signals.pre_migrate.send(
            sender=app_config,

 interactive, db, **kwargs):
    # Emit the pre_migrate signal for every application.
    for app_config in apps.get_app_configs():
        if app_config.models_module is None:
            continue
        if verbosity >= 2:


import find_command, is_ignored_path, popen_wrapper

def has_bom(fn):
    with fn.open("rb") as f:
        sample = f.read(4)
    return sample.startswith(
        (codecs.BOM_UTF8, codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)
    )

def is_dir_writable(path):
    try:
        with tempfile.NamedTemporaryFile(dir=path):
            pass
    except OSError:
        return False
    return True

class Command(BaseCommand):
    help = "Compiles .po files to .mo files for use with builtin gettext support."

",
            default=[],
            help="Locale(s) to process (e.g. de_AT). Default is to process all. "
            "Can be used multiple times.",
        )
        parser.add_argument(
            "--exclude",
            "-x",
            action="ap

 requires_system_checks = []

    program = "msgfmt"
    program_options = ["--check-format"]

    def add_arguments(self, parser):
        parser.add_argument(
            "--locale",
            "-l",
            action="append


t checks
from django.core.checks.registry import registry
from django.core.management.base import BaseCommand, CommandError
from django.db import connections

class Command(BaseCommand):
    help = "Checks the entire Django project for potential problems."

    requires_system_checks = []

    def add_arguments(self, parser):
        parser.add_argument("args", metavar="app_label", nargs="*")
        parser.add_argument(
            "--tag",
            "-t",
            action="append",
            dest="

y --deploy to include available deployment "
                "tags."
            ),
        )
        parser.add_argument(
            "--deploy",
            action="store_true",
            help="Check deployment settings.",
        )
        parser.add_

tags",
            help="Run only checks labeled with given tag.",
        )
        parser.add_argument(
            "--list-tags",
            action="store_true",
            help=(
                "List available tags. Specif


jango.core.management.base import BaseCommand, CommandError
from django.db import DEFAULT_DB_ALIAS, connections

class Command(BaseCommand):
    help = (
        "Runs the command-line client for specified database, or the "
        "default database if none is provided."
    )

    requires_system_checks = []

    def add_arguments(self, parser):
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(

t("parameters", nargs="*")

    def handle(self, **options):
        connection = connections[options["database"]]
        try:
            connection.client.runshell(options["parameters"])
        except FileNotFoundError:
            # Note that we're as

       "Nominates a database onto which to open a shell. Defaults to the "
                '"default" database.'
            ),
        )
        parameters = parser.add_argument_group("parameters")
        parameters.add_argumen


s_lzma = True
except ImportError:
    has_lzma = False

class ProxyModelWarning(Warning):
    pass

class Command(BaseCommand):
    help = (
        "Output the contents of the database as a fixture of the given format "
        "(using each model's default manager unless --all is specified)."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "args",
            metavar="app_label[.ModelName]",
            nargs="*",
            help=(
                "Restricts dumped d

tion format for fixtures.",
        )
        parser.add_argument(
            "--indent",
            type=int,
            help="Specifies the indent level to use when pretty-printing output.",
        )
        parser.add_argument(
            "--databa

ata to the specified app_label or "
                "app_label.ModelName."
            ),
        )
        parser.add_argument(
            "--format",
            default="json",
            help="Specifies the output serializa


S,
            choices=tuple(connections),
            help=(
                'Nominates a database to introspect. Defaults to using the "default" '
                "database."
            ),
        )
        parser.add_argument(
            "--include-partitions",
            action="store_true",
            help="Also output models for partition tables.",
        )
        parser.add_argument(
            "--include-views",
            action="store_true",
            help="Also output models for databas

    else:
            raise CommandError(
                "Database inspection isn't supported for the currently selected "
                "database backend."
            )

    def handle_inspection(self, options):
        connection = connections[option

e views.",
        )

    def handle(self, **options):
        if connections[options["database"]].features.supports_inspectdb:
            for line in self.handle_inspection(options):
                self.stdout.write(line)


\s*$', re.MULTILINE | re.DOTALL
)
STATUS_OK = 0
NO_LOCALE_DIR = object()

def check_programs(*programs):
    for program in programs:
        if find_command(program) is None:
            raise CommandError(
                f"Can't find {program}. Make sure you have GNU gettext tools "
                "0.19 or newer installed."
            )

def is_valid_locale(locale):
    return re.match(r"^[a-z]+$", locale) or re.match(r"^[a-z]+_[A-Z0-9].*$", locale)

@total_ordering
class TranslatableFile:
    def _

name__,
            os.sep.join([self.dirpath, self.file]),
        )

    def __eq__(self, other):
        return self.path == other.path

    def __lt__(self, other):
        return self.path < other.path

    @property
    def path(self):
        return

_init__(self, dirpath, file_name, locale_dir):
        self.file = file_name
        self.dirpath = dirpath
        self.locale_dir = locale_dir

    def __repr__(self):
        return "<%s: %s>" % (
            self.__class__.__


s database schema. Manages both apps with migrations and those without."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label",
            nargs="?",
            help="App label of an application to synchronize the state.",
        )
        parser.add_argument(
            "migration_name",
            nargs="?",
            help="Database state will be brought to the state after that "
            'migration. Use the name "zero" to unapply all migrations.',

,
        )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(
                'Nominates a database to synchronize. Defaults to the "default" '

    )
        parser.add_argument(
            "--noinput",
            "--no-input",
            action="store_false",
            dest="interactive",
            help="Tells Django to NOT prompt the user for input of any kind."


.servers.basehttp import WSGIServer, get_internal_wsgi_application, run
from django.db import connections
from django.utils import autoreload
from django.utils.regex_helper import _lazy_re_compile
from django.utils.version import get_docs_version

naiveip_re = _lazy_re_compile(
    r"""^(?:
(?P<addr>
    (?P<ipv4>\d{1,3}(?:\.\d{1,3}){3}) |         # IPv4 address
    (?P<ipv6>\[[a-fA-F0-9:]+\]) |               # IPv6 address
    (?P<fqdn>[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*) # FQDN
):)?(?P<port>\d+)$""",
    re

7.0.0.1"
    default_addr_ipv6 = "::1"
    default_port = "8000"
    protocol = "http"
    server_cls = WSGIServer

    def add_arguments(self, parser):
        parser.add_argument(
            "addrport", nargs="?", help="Optional port number, or ipaddr:p

.X,
)

class Command(BaseCommand):
    help = "Starts a lightweight web server for development."

    stealth_options = ("shutdown_message",)
    suppressed_base_arguments = {"--verbosity", "--traceback"}

    default_addr = "12


e.management.utils import parse_apps_and_model_labels
from django.db import (
    DEFAULT_DB_ALIAS,
    DatabaseError,
    IntegrityError,
    connections,
    router,
    transaction,
)
from django.utils.functional import cached_property

try:
    import bz2

    has_bz2 = True
except ImportError:
    has_bz2 = False

try:
    import lzma

    has_lzma = True
except ImportError:
    has_lzma = False

READ_STDIN = "-"

class Command(BaseCommand):
    help = "Installs the named fixture(s) in the database."

      "args", metavar="fixture", nargs="+", help="Fixture labels."
        )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(
                "Nominates

    missing_args_message = (
        "No database fixture specified. Please provide the path of at least "
        "one fixture in the command line."
    )

    def add_arguments(self, parser):
        parser.add_argument(


tions
from django.db.migrations.exceptions import AmbiguityError
from django.db.migrations.loader import MigrationLoader
from django.db.migrations.optimizer import MigrationOptimizer
from django.db.migrations.writer import MigrationWriter
from django.utils.version import get_docs_version

class Command(BaseCommand):
    help = "Optimizes the operations for the named migration."

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label",
            help="App label of the app

          action="store_true",
            help="Exit with a non-zero status if the migration can be optimized.",
        )

    def handle(self, *args, **options):
        verbosity = options["verbosity"]
        app_label = options["app_label"]
        m

lication to optimize the migration for.",
        )
        parser.add_argument(
            "migration_name", help="Migration name to optimize the operations for."
        )
        parser.add_argument(
            "--check",


ort BaseCommand, CommandError
from django.core.management.color import no_style
from django.core.management.sql import emit_post_migrate_signal, sql_flush
from django.db import DEFAULT_DB_ALIAS, connections

class Command(BaseCommand):
    help = (
        "Removes ALL DATA from the database, including data added during "
        'migrations. Does not achieve a "fresh install" state.'
    )
    stealth_options = ("reset_sequences", "allow_cascade", "inhibit_post_migrate")

    def add_arguments(self, parse

        )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help='Nominates a database to flush. Defaults to the "default" database.',
        )

    def handle(

r):
        parser.add_argument(
            "--noinput",
            "--no-input",
            action="store_false",
            dest="interactive",
            help="Tells Django to NOT prompt the user for input of any kind.",


and(BaseCommand):
    help = (
        "Runs a Python interactive interpreter. Tries to use IPython or "
        "bpython, if one of them is available. Any standard input is executed "
        "as code."
    )

    requires_system_checks = []
    shells = ["ipython", "bpython", "python"]

    def add_arguments(self, parser):
        parser.add_argument(
            "--no-startup",
            action="store_true",
            help=(
                "When using plain Python, ignore the PYTHONSTARTUP environme

,
        )
        parser.add_argument(
            "-i",
            "--interface",
            choices=self.shells,
            help=(
                "Specify an interactive interpreter interface. Available options: "
                '"ipython", "bpyth

nt "
                "variable and ~/.pythonrc.py script."
            ),
        )
        parser.add_argument(
            "--no-imports",
            action="store_true",
            help="Disable automatic imports of models."


m django.db.migrations.recorder import MigrationRecorder

class Command(BaseCommand):
    help = "Shows all available migrations for the current project"

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label",
            nargs="*",
            help="App labels of applications to limit the output to.",
        )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(

    "--list",
            "-l",
            action="store_const",
            dest="format",
            const="list",
            help=(
                "Shows a list of all migrations and which are applied. "
                "With a verbosity level of 2

       "Nominates a database to show migrations for. Defaults to the "
                '"default" database.'
            ),
        )

        formats = parser.add_mutually_exclusive_group()
        formats.add_argument(


m django.core.management.base import AppCommand
from django.db import DEFAULT_DB_ALIAS, connections

class Command(AppCommand):
    help = (
        "Prints the SQL statements for resetting sequences for the given app name(s)."
    )

    output_transaction = True

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(
                'N

        return
        connection = connections[options["database"]]
        models = app_config.get_models(include_auto_created=True)
        statements = connection.ops.sequence_reset_sql(self.style, models)
        if not statements and options["verbosi

ominates a database to print the SQL for. Defaults to the "default" '
                "database."
            ),
        )

    def handle_app_config(self, app_config, **options):
        if app_config.models_module is None:


security.base import SECRET_KEY_INSECURE_PREFIX
from django.core.management.templates import TemplateCommand
from django.core.management.utils import get_random_secret_key

class Command(TemplateCommand):
    help = (
        "Creates a Django project directory structure for the given project "
        "name in the current directory or optionally in the given directory."
    )
    missing_args_message = "You must provide a project name."

    def handle(self, **options):
        project_name = options.pop(

  target = options.pop("directory")

        # Create a random SECRET_KEY to put it in the main settings.
        options["secret_key"] = SECRET_KEY_INSECURE_PREFIX + get_random_secret_key()

        super().handle("project", project_name, target, **option


ort ProjectState
from django.db.migrations.utils import get_migration_name_timestamp
from django.db.migrations.writer import MigrationWriter

class Command(BaseCommand):
    autodetector = MigrationAutodetector
    help = "Creates new migration(s) for apps."

    def add_arguments(self, parser):
        parser.add_argument(
            "args",
            metavar="app_label",
            nargs="*",
            help="Specify the app label(s) to create migrations for.",
        )
        parser.add_argument(

store_true",
            help="Enable fixing of migration conflicts.",
        )
        parser.add_argument(
            "--empty",
            action="store_true",
            help="Create an empty migration.",
        )
        parser.add_argument(

            "--dry-run",
            action="store_true",
            help="Just show what migrations would be made; don't actually write them.",
        )
        parser.add_argument(
            "--merge",
            action="


rom django.core.management.base import BaseCommand
from django.core.management.sql import sql_flush
from django.db import DEFAULT_DB_ALIAS, connections

class Command(BaseCommand):
    help = (
        "Returns a list of the SQL statements required to return all tables in "
        "the database to the state they were in just after they were installed."
    )

    output_transaction = True

    def add_arguments(self, parser):
        super().add_arguments(parser)
        parser.add_argument(
            "

         ),
        )

    def handle(self, **options):
        sql_statements = sql_flush(self.style, connections[options["database"]])
        if not sql_statements and options["verbosity"] >= 1:
            self.stderr.write("No tables found.")

--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(
                'Nominates a database to print the SQL for. Defaults to the "default" '
                "database."


mport MigrationOptimizer
from django.db.migrations.writer import MigrationWriter

class Command(BaseCommand):
    help = (
        "Squashes an existing set of migrations (from first until specified) into a "
        "single new one."
    )

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label",
            help="App label of the application to squash migrations for.",
        )
        parser.add_argument(
            "start_migration_name",
            nargs="?",

ations will be squashed until and including this migration.",
        )
        parser.add_argument(
            "--no-optimize",
            action="store_true",
            help="Do not try to optimize the squashed operations.",
        )
        parser.

       help=(
                "Migrations will be squashed starting from and including this "
                "migration."
            ),
        )
        parser.add_argument(
            "migration_name",
            help="Migr


ango.db import DEFAULT_DB_ALIAS, connections
from django.db.migrations.loader import AmbiguityError, MigrationLoader

class Command(BaseCommand):
    help = "Prints the SQL statements for the named migration."

    output_transaction = True

    def add_arguments(self, parser):
        parser.add_argument(
            "app_label", help="App label of the application containing the migration."
        )
        parser.add_argument(
            "migration_name", help="Migration name to print the SQL for."

he "default" '
                "database."
            ),
        )
        parser.add_argument(
            "--backwards",
            action="store_true",
            help="Creates SQL to unapply the migration, rather than to apply it",
        )

    de

     )
        parser.add_argument(
            "--database",
            default=DEFAULT_DB_ALIAS,
            choices=tuple(connections),
            help=(
                'Nominates a database to create SQL for. Defaults to t


his package defines set of cache backends that all conform to a simple API.
In a nutshell, a cache is a set of values -- which can be any object that
may be pickled -- identified by string keys. For the complete API, see
the abstract BaseCache class in django.core.cache.backends.base.

Client code should use the `cache` variable defined here to access the default
cache backend and look up non-default cache backends in the `caches` dict-like
object.

See docs/topics/cache.txt for information on the public AP

ler, ConnectionProxy
from django.utils.module_loading import import_string

__all__ = [
    "cache",
    "caches",
    "DEFAULT_CACHE_ALIAS",
    "InvalidCacheBackendError",
    "CacheKeyWarning",
    "BaseCache",
    "InvalidCacheKey",
]

DEFAULT_CACHE_AL

I.
"""

from django.core import signals
from django.core.cache.backends.base import (
    BaseCache,
    CacheKeyWarning,
    InvalidCacheBackendError,
    InvalidCacheKey,
)
from django.utils.connection import BaseConnectionHand


is allows cache operations to be controlled by the router
    """

    def __init__(self, table):
        self.db_table = table
        self.app_label = "django_cache"
        self.model_name = "cacheentry"
        self.verbose_name = "cache entry"
        self.verbose_name_plural = "cache entries"
        self.object_name = "CacheEntry"
        self.abstract = False
        self.managed = True
        self.proxy = False
        self.swapped = False

class BaseDatabaseCache(BaseCache):
    def __init__(sel

    # This class uses cursors provided by the database connection. This means
    # it reads expiration values as aware or naive datetimes, depending on the
    # value of USE_TZ and whether the database supports time zones. The ORM's
    # conversion and

f, table, params):
        super().__init__(params)
        self._table = table

        class CacheEntry:
            _meta = Options(table)

        self.cache_model_class = CacheEntry

class DatabaseCache(BaseDatabaseCache):


BaseCache
from django.core.files import locks
from django.core.files.move import file_move_safe
from django.utils._os import safe_makedirs

class FileBasedCache(BaseCache):
    cache_suffix = ".djcache"
    pickle_protocol = pickle.HIGHEST_PROTOCOL

    def __init__(self, dir, params):
        super().__init__(params)
        self._dir = os.path.abspath(dir)
        self._createdir()

    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
        if self.has_key(key, version):
            re

 f:
                if not self._is_expired(f):
                    return pickle.loads(zlib.decompress(f.read()))
        except FileNotFoundError:
            pass
        return default

    def _write_content(self, file, timeout, value):
        expiry

turn False
        self.set(key, value, timeout, version)
        return True

    def get(self, key, default=None, version=None):
        fname = self._key_to_file(key, version)
        try:
            with open(fname, "rb") as


tional import cached_property

class BaseMemcachedCache(BaseCache):
    def __init__(self, server, params, library, value_not_found_exception):
        super().__init__(params)
        if isinstance(server, str):
            self._servers = re.split("[;,]", server)
        else:
            self._servers = server

        # Exception type raised by the underlying client library for a
        # nonexistent key.
        self.LibraryValueNotFoundException = value_not_found_exception

        self._lib = libra

 Implement transparent thread-safe access to a memcached client.
        """
        return self._class(self.client_servers, **self._options)

    def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
        """
        Memcached deals with long (> 30 d

ry
        self._class = library.Client
        self._options = params.get("OPTIONS") or {}

    @property
    def client_servers(self):
        return self._servers

    @cached_property
    def _cache(self):
        """


jango.core.management.base import BaseCommand
from django.core.management.utils import get_command_line_option
from django.test.runner import get_max_test_processes
from django.test.utils import NullTimeKeeper, TimeKeeper, get_runner

class Command(BaseCommand):
    help = "Discover and run tests in the specified modules or the current directory."

    # DiscoverRunner runs the checks after databases are set up.
    requires_system_checks = []
    test_runner = None

    def run_from_argv(self, argv):

_line_option(argv, "--testrunner")
        super().run_from_argv(argv)

    def add_arguments(self, parser):
        parser.add_argument(
            "args",
            metavar="test_label",
            nargs="*",
            help=(
                "Modul

    """
        Pre-parse the command line to extract the value of the --testrunner
        option. This allows a test runner to define additional command line
        arguments.
        """
        self.test_runner = get_command


Dummy cache backend"

from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache

class DummyCache(BaseCache):
    def __init__(self, host, *args, **kwargs):
        super().__init__(*args, **kwargs)

    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
        self.make_and_validate_key(key, version=version)
        return True

    def get(self, key, default=None, version=None):
        self.make_and_validate_key(key, version=version)
        return default

    def set(self,

on)
        return False

    def delete(self, key, version=None):
        self.make_and_validate_key(key, version=version)
        return False

    def has_key(self, key, version=None):
        self.make_and_validate_key(key, version=version)
        ret

 key, value, timeout=DEFAULT_TIMEOUT, version=None):
        self.make_and_validate_key(key, version=version)

    def touch(self, key, timeout=DEFAULT_TIMEOUT, version=None):
        self.make_and_validate_key(key, version=versi


from django.utils.module_loading import import_string

class RedisSerializer:
    def __init__(self, protocol=None):
        self.protocol = pickle.HIGHEST_PROTOCOL if protocol is None else protocol

    def dumps(self, obj):
        # For better incr() and decr() atomicity, don't pickle integers.
        # Using type() rather than isinstance() matches only integers and not
        # subclasses like bool.
        if type(obj) is int:
            return obj
        return pickle.dumps(obj, self.protocol)

ne,
        pool_class=None,
        parser_class=None,
        **options,
    ):
        import redis

        self._lib = redis
        self._servers = servers
        self._pools = {}

        self._client = self._lib.Redis

        if isinstance(pool_c

   def loads(self, data):
        try:
            return int(data)
        except ValueError:
            return pickle.loads(data)

class RedisCacheClient:
    def __init__(
        self,
        servers,
        serializer=No


json))

To add your own serializers, use the SERIALIZATION_MODULES setting::

    SERIALIZATION_MODULES = {
        "csv": "path.to.csv.serializer",
        "txt": "path.to.txt.serializer",
    }

"""

import importlib

from django.apps import apps
from django.conf import settings
from django.core.serializers.base import SerializerDoesNotExist

# Built-in serializers
BUILTIN_SERIALIZERS = {
    "xml": "django.core.serializers.xml_serializer",
    "python": "django.core.serializers.python",
    "json": "djan

ration

    This allows the serializer registration to cache serializers and if there
    is an error raised in the process of creating a serializer it will be
    raised and passed along to the caller when the serializer is used.
    """

    internal_use

go.core.serializers.json",
    "yaml": "django.core.serializers.pyyaml",
    "jsonl": "django.core.serializers.jsonl",
}

_serializers = {}

class BadSerializer:
    """
    Stub serializer to hold exception raised during regist


hat can be reopened in the same
process on any platform. Most platforms use the standard Python
tempfile.NamedTemporaryFile class, but Windows users are given a custom class.

This is needed because the Python implementation of NamedTemporaryFile uses the
O_TEMPORARY flag under Windows, which prevents the file from being reopened
if the same flag is not provided [1][2]. Note that this does not address the
more general issue of opening a file for writing and reading in multiple
processes in a manner that wor

tps://bugs.python.org/issue14243
"""

import os
import tempfile

from django.core.files.utils import FileProxyMixin

__all__ = (
    "NamedTemporaryFile",
    "gettempdir",
)

if os.name == "nt":

    class TemporaryFile(FileProxyMixin):
        """

ks across platforms.

The custom version of NamedTemporaryFile doesn't support the same keyword
arguments available in tempfile.NamedTemporaryFile.

1: https://mail.python.org/pipermail/python-list/2005-December/336955.html
2: ht


t settings
from django.core.exceptions import ImproperlyConfigured
from django.core.mail import InvalidMailer
from django.core.mail.backends.console import EmailBackend as ConsoleEmailBackend

class EmailBackend(ConsoleEmailBackend):
    def __init__(self, fail_silently=False, file_path=None, **kwargs):
        self._fname = None
        # Since we're using the console-based backend as a base, force the
        # stream to be None, so we don't default to stdout.
        kwargs["stream"] = None
        supe

         self.file_path = file_path
            else:
                self.file_path = getattr(settings, "EMAIL_FILE_PATH", None)
            if self.file_path is None:
                raise ImproperlyConfigured(
                    "The EMAIL_FILE_PATH se

r().__init__(fail_silently=fail_silently, **kwargs)

        # RemovedInDjango70Warning.
        if self.alias is None:
            # Use deprecated settings when MAILERS not enabled.
            if file_path is not None:


inary form must reproduce the above copyright
#      notice, this list of conditions and the following disclaimer in the
#      documentation and/or other materials provided with the distribution.
#
#   3. Neither the name of Distance nor the names of its contributors may be
#      used to endorse or promote products derived from this software without
#      specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANT

CIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# C

IES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, IN


from threading import Lock

from django.core.cache.backends.base import DEFAULT_TIMEOUT, BaseCache

# Global in-memory store of cache data. Keyed by name, to provide
# multiple named local memory caches.
_caches = {}
_expire_info = {}
_locks = {}

class LocMemCache(BaseCache):
    pickle_protocol = pickle.HIGHEST_PROTOCOL

    def __init__(self, name, params):
        super().__init__(params)
        self._cache = _caches.setdefault(name, OrderedDict())
        self._expire_info = _expire_info.setdefault(n

lue, self.pickle_protocol)
        with self._lock:
            if self._has_expired(key):
                self._set(key, pickled, timeout)
                return True
            return False

    def get(self, key, default=None, version=None):
        ke

ame, {})
        self._lock = _locks.setdefault(name, Lock())

    def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
        key = self.make_and_validate_key(key, version=version)
        pickled = pickle.dumps(va


LAG_HASNODATA,
    BANDTYPE_PIXTYPE_MASK,
    GDAL_TO_POSTGIS,
    GDAL_TO_STRUCT,
    POSTGIS_HEADER_STRUCTURE,
    POSTGIS_TO_GDAL,
    STRUCT_SIZE,
)

def pack(structure, data):
    """
    Pack data into hex string with little endian format.
    """
    return struct.pack("<" + structure, *data)

def unpack(structure, data):
    """
    Unpack little endian hexlified binary string into a list.
    """
    return struct.unpack("<" + structure, bytes.fromhex(data))

def chunk(data, index):
    """

   # Split raster header from data
    header, data = chunk(data, 122)
    header = unpack(POSTGIS_HEADER_STRUCTURE, header)

    # Parse band data
    bands = []
    pixeltypes = []
    while data:
        # Get pixel type for this band
        pixeltype_

Split a string into two parts at the input index.
    """
    return data[:index], data[index:]

def from_pgraster(data):
    """
    Convert a PostGIS HEX String into a dictionary.
    """
    if data is None:
        return


ss-origin",
    "same-origin",
    "strict-origin",
    "strict-origin-when-cross-origin",
    "unsafe-url",
}

SECRET_KEY_INSECURE_PREFIX = "django-insecure-"
SECRET_KEY_MIN_LENGTH = 50
SECRET_KEY_MIN_UNIQUE_CHARACTERS = 5

SECRET_KEY_WARNING_MSG = (
    f"Your %s has less than {SECRET_KEY_MIN_LENGTH} characters, less than "
    f"{SECRET_KEY_MIN_UNIQUE_CHARACTERS} unique characters, or it's prefixed "
    f"with '{SECRET_KEY_INSECURE_PREFIX}' indicating that it was generated "
    f"automatically by Djang

re' "
    "in your MIDDLEWARE so the SECURE_HSTS_SECONDS, "
    "SECURE_CONTENT_TYPE_NOSNIFF, SECURE_REFERRER_POLICY, "
    "SECURE_CROSS_ORIGIN_OPENER_POLICY, and SECURE_SSL_REDIRECT settings will "
    "have no effect.",
    id="security.W001",
)

W002 =

o. Please generate a long and random value, "
    f"otherwise many of Django's security-critical features will be "
    f"vulnerable to attack."
)

W001 = Warning(
    "You do not have 'django.middleware.security.SecurityMiddlewa


messages import (
    CRITICAL,
    DEBUG,
    ERROR,
    INFO,
    WARNING,
    CheckMessage,
    Critical,
    Debug,
    Error,
    Info,
    Warning,
)
from .registry import Tags, register, run_checks, tag_exists

# Import these to force registration of checks
import django.core.checks.async_checks  # NOQA isort:skip
import django.core.checks.caches  # NOQA isort:skip
import django.core.checks.commands  # NOQA isort:skip
import django.core.checks.compatibility.django_4_0  # NOQA isort:skip
import django

hecks.security.csrf  # NOQA isort:skip
import django.core.checks.security.sessions  # NOQA isort:skip
import django.core.checks.templates  # NOQA isort:skip
import django.core.checks.translation  # NOQA isort:skip
import django.core.checks.urls  # NOQA iso

.core.checks.database  # NOQA isort:skip
import django.core.checks.files  # NOQA isort:skip
import django.core.checks.model_checks  # NOQA isort:skip
import django.core.checks.security.base  # NOQA isort:skip
import django.core.c


om django.core.cache import DEFAULT_CACHE_ALIAS, caches
from django.core.cache.backends.filebased import FileBasedCache

from . import Error, Tags, Warning, register

E001 = Error(
    "You must define a '%s' cache in your CACHES setting." % DEFAULT_CACHE_ALIAS,
    id="caches.E001",
)

@register(Tags.caches)
def check_default_cache_is_configured(app_configs, **kwargs):
    if DEFAULT_CACHE_ALIAS not in settings.CACHES:
        return [E001]
    return []

@register(Tags.caches, deploy=True)
def check_cac

   if name == "STATICFILES_DIRS":
            paths = set()
            for staticfiles_dir in setting:
                if isinstance(staticfiles_dir, (list, tuple)):
                    _, staticfiles_dir = staticfiles_dir
                paths.add(pathli

he_location_not_exposed(app_configs, **kwargs):
    errors = []
    for name in ("MEDIA_ROOT", "STATIC_ROOT", "STATICFILES_DIRS"):
        setting = getattr(settings, name, None)
        if not setting:
            continue


ng, register

@register(Tags.models)
def check_all_models(app_configs, **kwargs):
    db_table_models = defaultdict(list)
    indexes = defaultdict(list)
    constraints = defaultdict(list)
    errors = []
    if app_configs is None:
        models = apps.get_models()
    else:
        models = chain.from_iterable(
            app_config.get_models() for app_config in app_configs
        )
    for model in models:
        if model._meta.managed and not model._meta.proxy:
            db_table_models[model._

           % (model.__name__, model.check),
                    obj=model,
                    id="models.E020",
                )
            )
        else:
            errors.extend(model.check(**kwargs))
        for model_index in model._meta.indexes:

meta.db_table].append(model._meta.label)
        if not inspect.ismethod(model.check):
            errors.append(
                Error(
                    "The '%s.check()' class method is currently overridden by %r."


ettings
from django.utils.translation import get_supported_language_variant
from django.utils.translation.trans_real import language_code_re

from . import Error, Tags, register

E001 = Error(
    "You have provided an invalid value for the LANGUAGE_CODE setting: {!r}.",
    id="translation.E001",
)

E002 = Error(
    "You have provided an invalid language code in the LANGUAGES setting: {!r}.",
    id="translation.E002",
)

E003 = Error(
    "You have provided an invalid language code in the LANGUAGES_BIDI

ef check_setting_language_code(app_configs, **kwargs):
    """Error if LANGUAGE_CODE setting is invalid."""
    tag = settings.LANGUAGE_CODE
    if not isinstance(tag, str) or not language_code_re.match(tag):
        return [Error(E001.msg.format(tag), id=

setting: {!r}.",
    id="translation.E003",
)

E004 = Error(
    "You have provided a value for the LANGUAGE_CODE setting that is not in "
    "the LANGUAGES setting.",
    id="translation.E004",
)

@register(Tags.translation)
d


iewDoesNotExist
from django.utils.inspect import signature

from . import Error, Tags, Warning, register

@register(Tags.urls)
def check_url_config(app_configs, **kwargs):
    if getattr(settings, "ROOT_URLCONF", None):
        from django.urls import get_resolver

        resolver = get_resolver()
        return check_resolver(resolver)
    return []

def check_resolver(resolver):
    """
    Recursively check the resolver.
    """
    check_method = getattr(resolver, "check", None)
    if check_method i

configs, **kwargs):
    """
    Warn if URL namespaces used in applications aren't unique.
    """
    if not getattr(settings, "ROOT_URLCONF", None):
        return []

    from django.urls import get_resolver

    resolver = get_resolver()
    all_namesp

s not None:
        return check_method()
    elif not hasattr(resolver, "resolve"):
        return get_warning_for_invalid_pattern(resolver)
    else:
        return []

@register(Tags.urls)
def check_url_namespaces_unique(app_


  pass

# Stub class to ensure not passing in a `timeout` argument results in
# the default timeout
DEFAULT_TIMEOUT = object()

# Memcached does not accept keys longer than this.
MEMCACHE_MAX_KEY_LENGTH = 250

def default_key_func(key, key_prefix, version):
    """
    Default function to generate keys.

    Construct the key used by all other methods. By default, prepend
    the `key_prefix`. KEY_FUNCTION can be used to specify an alternate
    function with custom key making behavior.
    """
    return

unc):
            return key_func
        else:
            return import_string(key_func)
    return default_key_func

class BaseCache:
    _missing_key = object()

    def __init__(self, params):
        timeout = params.get("timeout", params.get("TIMEO

 "%s:%s:%s" % (key_prefix, version, key)

def get_key_func(key_func):
    """
    Function to decide which key function to use.

    Default to ``default_key_func``.
    """
    if key_func is not None:
        if callable(key_f


40
CRITICAL = 50

class CheckMessage:
    def __init__(self, level, msg, hint=None, obj=None, id=None):
        if not isinstance(level, int):
            raise TypeError("The first argument should be level.")
        self.level = level
        self.msg = msg
        self.hint = hint
        self.obj = obj
        self.id = id

    def __eq__(self, other):
        return isinstance(other, self.__class__) and all(
            getattr(self, attr) == getattr(other, attr)
            for attr in ["level", "msg

 hardcode ModelBase and Field cases because its __str__
            # method doesn't return "applabel.modellabel" and cannot be
            # changed.
            obj = self.obj._meta.label
        else:
            obj = str(self.obj)
        id = "(%s) "

", "hint", "obj", "id"]
        )

    def __str__(self):
        from django.db import models

        if self.obj is None:
            obj = "?"
        elif isinstance(self.obj, models.base.ModelBase):
            # We need to


hecks import Error, Tags, Warning, register
from django.utils.inspect import signature

W003 = Warning(
    "You don't appear to be using Django's built-in "
    "cross-site request forgery protection via the middleware "
    "('django.middleware.csrf.CsrfViewMiddleware' is not in your "
    "MIDDLEWARE). Enabling the middleware is the safest approach "
    "to ensure you don't leave any holes.",
    id="security.W003",
)

W016 = Warning(
    "You have 'django.middleware.csrf.CsrfViewMiddleware' in your "

middleware():
    return "django.middleware.csrf.CsrfViewMiddleware" in settings.MIDDLEWARE

@register(Tags.security, deploy=True)
def check_csrf_middleware(app_configs, **kwargs):
    passed_check = _csrf_middleware()
    return [] if passed_check else [

   "MIDDLEWARE, but you have not set CSRF_COOKIE_SECURE to True. "
    "Using a secure-only CSRF cookie makes it more difficult for network "
    "traffic sniffers to steal the CSRF token.",
    id="security.W016",
)

def _csrf_


om django.utils.inspect import func_accepts_kwargs

class Tags:
    """
    Built-in tags for internal checks.
    """

    admin = "admin"
    async_support = "async_support"
    caches = "caches"
    commands = "commands"
    compatibility = "compatibility"
    database = "database"
    files = "files"
    models = "models"
    security = "security"
    signals = "signals"
    sites = "sites"
    staticfiles = "staticfiles"
    templates = "templates"
    translation = "translation"
    urls = "urls"

c

corator. Register given function
        `f` labeled with given `tags`. The function should receive **kwargs
        and return list of Errors and Warnings.

        Example::

            registry = CheckRegistry()
            @registry.register('mytag',

lass CheckRegistry:
    def __init__(self):
        self.registered_checks = set()
        self.deployment_checks = set()

    def register(self, check=None, *tags, **kwargs):
        """
        Can be used as a function or a de


commands)
def migrate_and_makemigrations_autodetector(**kwargs):
    from django.core.management import get_commands, load_command_class

    commands = get_commands()

    make_migrations = load_command_class(commands["makemigrations"], "makemigrations")
    migrate = load_command_class(commands["migrate"], "migrate")

    if make_migrations.autodetector is not migrate.autodetector:
        return [
            Error(
                "The migrate and makemigrations commands must have the same "

             f"makemigrations.Command.autodetector is "
                    f"{make_migrations.autodetector.__name__}, but "
                    f"migrate.Command.autodetector is "
                    f"{migrate.autodetector.__name__}."
                ),

     "autodetector.",
                hint=(


go.core.serializers.base import DeserializationError
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.python import Serializer as PythonSerializer
from django.utils.duration import duration_iso_string
from django.utils.functional import Promise
from django.utils.timezone import is_aware

class Serializer(PythonSerializer):
    """Convert a queryset to JSON."""

    internal_use_only = False

    def _init_options(self):
        self._current = None

f.json_kwargs["separators"] = (",", ": ")
        self.json_kwargs.setdefault("cls", DjangoJSONEncoder)
        self.json_kwargs.setdefault("ensure_ascii", False)

    def start_serialization(self):
        self._init_options()
        self.stream.write("[

        self.json_kwargs = self.options.copy()
        self.json_kwargs.pop("stream", None)
        self.json_kwargs.pop("fields", None)
        if self.options.get("indent"):
            # Prevent trailing spaces
            sel


apps import apps
from django.core.serializers import base
from django.db import DEFAULT_DB_ALIAS, models
from django.db.models import CompositePrimaryKey
from django.utils.encoding import is_protected_type

class Serializer(base.Serializer):
    """
    Serialize a QuerySet to basic Python objects.
    """

    internal_use_only = True

    def start_serialization(self):
        self._current = None
        self.objects = []

    def end_serialization(self):
        pass

    def start_object(self, obj):

f not self.use_natural_primary_keys or not self._resolve_natural_key(obj):
            data["pk"] = self._value_from_field(obj, obj._meta.pk)
        data["fields"] = self._current
        return data

    def _value_from_field(self, obj, field):
        i

       self._current = {}

    def end_object(self, obj):
        self.objects.append(self.get_dump_object(obj))
        self._current = None

    def get_dump_object(self, obj):
        data = {"model": str(obj._meta)}
        i


en the XML document and the root element.
        """
        # Increment the indent_level before each startElement() and decrement
        # it following each endElement(). If the closing tag should appear on
        # its own line, use self.indent(self.indent_level) before endElement().
        self.indent_level = 0
        self.xml = SimplerXMLGenerator(
            self.stream, self.options.get("encoding", settings.DEFAULT_CHARSET)
        )
        self.xml.startDocument()
        self.xml.startElement

        self.xml.endDocument()

    def start_object(self, obj):
        """
        Called as each object is handled.
        """
        if not hasattr(obj, "_meta"):
            raise base.SerializationError(
                "Non-model object (%s) encou

("django-objects", {"version": "1.0"})

    def end_serialization(self):
        """
        End serialization -- end the document.
        """
        self.indent(self.indent_level)
        self.xml.endElement("django-objects")


s Pillow as you might imagine.
"""

import struct
import zlib

from django.core.files import File

class ImageFile(File):
    """
    A mixin for use alongside django.core.files.base.File, which provides
    additional features for dealing with images.
    """

    @property
    def width(self):
        return self._get_image_dimensions()[0]

    @property
    def height(self):
        return self._get_image_dimensions()[1]

    def _get_image_dimensions(self):
        if not hasattr(self, "_dimensions_cac

):
    """
    Return the (width, height) of an image, given an open file or a path. Set
    'close' to True to close the file at the end if it is initially in an open
    state.
    """
    from PIL import ImageFile as PillowImageFile

    p = PillowImage

he"):
            close = self.closed
            self.open()
            self._dimensions_cache = get_image_dimensions(self, close=close)
        return self._dimensions_cache

def get_image_dimensions(file_or_path, close=False


n
Cookbook [1] (licensed under the Python Software License) and a ctypes port by
Anatoly Techtonik for Roundup [2] (license [3]).

[1] https://code.activestate.com/recipes/65203/
[2] https://sourceforge.net/p/roundup/code/ci/default/tree/roundup/backends/portalocker.py  # NOQA
[3] https://sourceforge.net/p/roundup/code/ci/default/tree/COPYING.txt

Example Usage::

    >>> from django.core.files import locks
    >>> with open('./file', 'wb') as f:
    ...     locks.lock(f, locks.LOCK_EX)
    ...     f.write(

e f

if os.name == "nt":
    import msvcrt
    from ctypes import (
        POINTER,
        Structure,
        Union,
        WinDLL,
        byref,
        c_int64,
        c_ulong,
        c_void_p,
        sizeof,
    )
    from ctypes.wintypes import

'Django')
"""

import os

__all__ = ("LOCK_EX", "LOCK_SH", "LOCK_NB", "lock", "unlock")

def _fd(f):
    """Get a filedescriptor from something which could be a file or an fd."""
    return f.fileno() if hasattr(f, "fileno") els


hecks import Tags, Warning, register

def add_session_cookie_message(message):
    return message + (
        " Using a secure-only session cookie makes it more difficult for "
        "network traffic sniffers to hijack user sessions."
    )

W010 = Warning(
    add_session_cookie_message(
        "You have 'django.contrib.sessions' in your INSTALLED_APPS, "
        "but you have not set SESSION_COOKIE_SECURE to True."
    ),
    id="security.W010",
)

W011 = Warning(
    add_session_cookie_message(

_cookie_message("SESSION_COOKIE_SECURE is not set to True."),
    id="security.W012",
)

def add_httponly_message(message):
    return message + (
        " Using an HttpOnly session cookie makes it more difficult for "
        "cross-site scripting attac

    "You have 'django.contrib.sessions.middleware.SessionMiddleware' "
        "in your MIDDLEWARE, but you have not set "
        "SESSION_COOKIE_SECURE to True."
    ),
    id="security.W011",
)

W012 = Warning(
    add_session


ass DeserializationError(Exception):
    """Something bad happened during deserialization."""

    @classmethod
    def WithData(cls, original_exc, model, fk, field_value):
        """
        Factory method for creating a deserialization error which has a more
        explanatory message.
        """
        return cls(
            "%s: (%s:pk=%s) field_value was '%s'"
            % (original_exc, model, fk, field_value)
        )

class M2MDeserializationError(Exception):
    """Something bad happened du

otal_count):
        self.output = output
        self.total_count = total_count
        self.prev_done = 0

    def update(self, count):
        if not self.output:
            return
        perc = count * 100 // self.total_count
        done = perc * se

ring deserialization of a ManyToManyField."""

    def __init__(self, original_exc, pk):
        self.original_exc = original_exc
        self.pk = pk

class ProgressBar:
    progress_width = 75

    def __init__(self, output, t


FileProxyMixin
from django.utils.functional import cached_property

class File(FileProxyMixin):
    DEFAULT_CHUNK_SIZE = 64 * 2**10

    def __init__(self, file, name=None):
        self.file = file
        if name is None:
            name = getattr(file, "name", None)
        self.name = name
        if hasattr(file, "mode"):
            self.mode = file.mode

    def __str__(self):
        return self.name or ""

    def __repr__(self):
        return "<%s: %s>" % (self.__class__.__name__, self.name or

asattr(self.file, "name"):
            try:
                return os.path.getsize(self.file.name)
            except (OSError, TypeError):
                pass
        if hasattr(self.file, "tell") and hasattr(self.file, "seek"):
            pos = self.fi

"None")

    def __bool__(self):
        return True

    def __len__(self):
        return self.size

    @cached_property
    def size(self):
        if hasattr(self.file, "size"):
            return self.file.size
        if h


>> from django.core.files.move import file_move_safe
    >>> file_move_safe("/tmp/old_file", "/tmp/new_file")
"""

import os
from shutil import copymode, copystat

from django.core.files import locks

__all__ = ["file_move_safe"]

def file_move_safe(
    old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False
):
    """
    Move a file from one location to another in the safest way possible.

    First, try ``os.rename``, which is simple but will break across
    filesystems. If that fail

    try:
        if os.path.samefile(old_file_name, new_file_name):
            return
    except OSError:
        pass

    if not allow_overwrite and os.access(new_file_name, os.F_OK):
        raise FileExistsError(
            f"Destination file {new_f

s, stream manually from one file to another in
    pure Python.

    If the destination file exists and ``allow_overwrite`` is ``False``, raise
    ``FileExistsError``.
    """
    # There's no reason to move if we don't have to.


son

from django.core.serializers.base import DeserializationError
from django.core.serializers.json import DjangoJSONEncoder
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.python import Serializer as PythonSerializer

class Serializer(PythonSerializer):
    """Convert a queryset to JSON Lines."""

    internal_use_only = False

    def _init_options(self):
        self._current = None
        self.json_kwargs = self.options.copy()
        self.js

oder)
        self.json_kwargs.setdefault("ensure_ascii", False)

    def start_serialization(self):
        self._init_options()

    def end_object(self, obj):
        # self._current has the field data
        json.dump(self.get_dump_object(obj), self.s

on_kwargs.pop("stream", None)
        self.json_kwargs.pop("fields", None)
        self.json_kwargs.pop("indent", None)
        self.json_kwargs["separators"] = (",", ": ")
        self.json_kwargs.setdefault("cls", DjangoJSONEnc


ml.org/), but that's checked for in __init__.
"""

import datetime
import decimal

import yaml

from django.core.serializers.base import DeserializationError
from django.core.serializers.python import Deserializer as PythonDeserializer
from django.core.serializers.python import Serializer as PythonSerializer

# Use the C (faster) implementation if possible
try:
    from yaml import CSafeDumper as SafeDumper
    from yaml import CSafeLoader as SafeLoader
except ImportError:
    from yaml import SafeDumper, S

  def represent_time(self, data):
        # Base YAML doesn't support serialization of time types (as opposed to
        # dates or datetimes, which it does support). Converting them to
        # strings isn't perfect, but it's better than a "!!python/time

afeLoader

class DjangoSafeDumper(SafeDumper):
    # The "safe" serializer is used for better interoperability.

    def represent_decimal(self, data):
        return self.represent_scalar("tag:yaml.org,2002:str", str(data))


 import InMemoryUploadedFile, TemporaryUploadedFile
from django.utils.module_loading import import_string

__all__ = [
    "UploadFileException",
    "StopUpload",
    "SkipFile",
    "FileUploadHandler",
    "TemporaryFileUploadHandler",
    "MemoryFileUploadHandler",
    "load_handler",
    "StopFutureHandlers",
]

class UploadFileException(Exception):
    """
    Any error having to do with uploading files.
    """

    pass

class StopUpload(UploadFileException):
    """
    This exception is raised w

will cause the browser
        to show a "connection reset" error.
        """
        self.connection_reset = connection_reset

    def __str__(self):
        if self.connection_reset:
            return "StopUpload: Halt current upload."
        else:

hen an upload must abort.
    """

    def __init__(self, connection_reset=False):
        """
        If ``connection_reset`` is ``True``, Django knows will halt the upload
        without consuming the rest of the upload. This


rt get_random_string
from django.utils.text import get_valid_filename

class Storage:
    """
    A base storage class, providing some default behaviors that all other
    storage systems can inherit or override, as necessary.
    """

    # The following methods represent a public interface to private methods.
    # These shouldn't be overridden by subclasses unless absolutely necessary.

    def open(self, name, mode="rb"):
        """Retrieve the specified file from storage."""
        return self._open

read
        from the beginning.
        """
        # Get the proper name for the file, as it will actually be saved.
        if name is None:
            name = content.name

        if not hasattr(content, "chunks"):
            content = File(content,

(name, mode)

    def save(self, name, content, max_length=None):
        """
        Save new content to the file specified by name. The content should be
        a proper File object or any Python file-like object, ready to be


conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.functional import cached_property
from django.utils.module_loading import import_string

class InvalidStorageError(ImproperlyConfigured):
    pass

class StorageHandler:
    def __init__(self, backends=None):
        # backends is an optional dict of storage backend definitions
        # (structured like settings.STORAGES).
        self._backends = backends
        self._storages = {}

    @cached_property
    d

      except KeyError:
            try:
                params = self.backends[alias]
            except KeyError:
                raise InvalidStorageError(
                    f"Could not find config for '{alias}' in settings.STORAGES."
                )

ef backends(self):
        if self._backends is None:
            self._backends = settings.STORAGES.copy()
        return self._backends

    def __getitem__(self, alias):
        try:
            return self._storages[alias]


ore/mail.py before the introduction of email
# backends and the subsequent reorganization (See #10355)
from django.core.mail.message import (
    DEFAULT_ATTACHMENT_MIME_TYPE,
    EmailAlternative,
    EmailAttachment,
    EmailMessage,
    EmailMultiAlternatives,
    forbid_multi_line_headers,
    make_msgid,
)
from django.core.mail.utils import DNS_NAME, CachedDnsName
from django.utils.deprecation import (
    RemovedInDjango70Warning,
    deprecate_posargs,
    warn_about_external_use,
)
from django.util

 warn_about_default_mailers_if_needed,
)

__all__ = [
    "InvalidMailer",
    "MailerDoesNotExist",
    "CachedDnsName",
    "DNS_NAME",
    "EmailMessage",
    "EmailMultiAlternatives",
    "DEFAULT_ATTACHMENT_MIME_TYPE",
    "make_msgid",
    "mailers",

s.functional import Promise
from django.utils.module_loading import import_string

from .deprecation import (
    AUTH_ARGS_WARNING,
    CONNECTION_ARG_WARNING,
    FAIL_SILENTLY_ARG_WARNING,
    report_using_incompatibility,


ail import InvalidMailer, MailerDoesNotExist
from django.utils.module_loading import import_string

DEFAULT_MAILER_ALIAS = "default"

# Default value for a MAILERS "BACKEND". (Not related to the default mailer.)
DEFAULT_MAILER_BACKEND = "django.core.mail.backends.smtp.EmailBackend"

class MailersHandler:
    def __getitem__(self, /, alias):
        return self.create_connection(alias)

    def __contains__(self, /, alias):
        return alias in self.settings

    def __iter__(self):
        return iter(s

_MAILER_ALIAS]

    @property
    def settings(self):
        # RemovedInDjango70Warning: change to:
        #   return settings.MAILERS
        return getattr(settings, "MAILERS", {})

    # RemovedInDjango70Warning.
    @property
    def _is_configured(s

elf.settings)

    def get(self, alias, /, default=None):
        try:
            return self[alias]
        except MailerDoesNotExist:
            return default

    @property
    def default(self):
        return self[DEFAULT


ion import RemovedInDjango70Warning, warn_about_external_use

# RemovedInDjango70Warning.
_NOT_PROVIDED = object()

class BaseEmailBackend:
    """
    Base class for email backend implementations.

    Subclasses must implement at least send_messages().

    Subclass __init__() should pass alias and unknown **kwargs to
    super().__init__() for proper error reporting.

    open() and close() can be called indirectly by using a backend object as a
    context manager:

       with backend as connection:

s=None,
        _ignore_unknown_kwargs=None,
        **kwargs,
    ):
        self.alias = alias

        # RemovedInDjango70Warning.
        if fail_silently is _NOT_PROVIDED:
            self._fail_silently = False
        else:
            self._fail_si

          # do something with connection
           pass
    """

    # RemovedInDjango70Warning: fail_silently, _ignore_unknown_kwargs.
    def __init__(
        self,
        fail_silently=_NOT_PROVIDED,
        *,
        alia


t settings
from django.core.files import temp as tempfile
from django.core.files.base import File
from django.core.files.utils import validate_file_name

__all__ = (
    "UploadedFile",
    "TemporaryUploadedFile",
    "InMemoryUploadedFile",
    "SimpleUploadedFile",
)

class UploadedFile(File):
    """
    An abstract uploaded file (``TemporaryUploadedFile`` and
    ``InMemoryUploadedFile`` are the built-in concrete subclasses).

    An ``UploadedFile`` object behaves somewhat like a file object and

e_extra=None,
    ):
        super().__init__(file, name)
        self.size = size
        self.content_type = content_type
        self.charset = charset
        self.content_type_extra = content_type_extra

    def __repr__(self):
        return "<%s: %s

represents some file data that the user submitted with a form.
    """

    def __init__(
        self,
        file=None,
        name=None,
        content_type=None,
        size=None,
        charset=None,
        content_typ