prefix stringlengths 512 512 | suffix stringlengths 256 256 | middle stringlengths 14 229 | meta dict |
|---|---|---|---|
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_o... | 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 | {
"filepath": "scripts/archive_eol_stable_branches.py",
"language": "python",
"file_size": 4716,
"cut_index": 614,
"middle_length": 229
} |
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 bui... | 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}
| {
"filepath": "scripts/do_django_release.py",
"language": "python",
"file_size": 7718,
"cut_index": 716,
"middle_length": 229
} |
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`... | 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 | {
"filepath": "scripts/prepare_commit_msg.py",
"language": "python",
"file_size": 3543,
"cut_index": 614,
"middle_length": 229
} |
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 t... | 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 | {
"filepath": "scripts/pr_quality/tests/test_check_pr.py",
"language": "python",
"file_size": 39032,
"cut_index": 2151,
"middle_length": 229
} |
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-Fra... | 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 | {
"filepath": "django/middleware/clickjacking.py",
"language": "python",
"file_size": 1724,
"cut_index": 537,
"middle_length": 229
} |
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 br... | 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 | {
"filepath": "django/middleware/gzip.py",
"language": "python",
"file_size": 2626,
"cut_index": 563,
"middle_length": 229
} |
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 N... | 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 | {
"filepath": "django/core/validators.py",
"language": "python",
"file_size": 22484,
"cut_index": 1331,
"middle_length": 229
} |
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)... | 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 | {
"filepath": "django/core/management/base.py",
"language": "python",
"file_size": 25059,
"cut_index": 1331,
"middle_length": 229
} |
.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."""
... | 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",
| {
"filepath": "django/core/management/commands/diffsettings.py",
"language": "python",
"file_size": 3564,
"cut_index": 614,
"middle_length": 229
} |
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 re... | 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 | {
"filepath": "django/core/management/commands/sendtestemail.py",
"language": "python",
"file_size": 1518,
"cut_index": 537,
"middle_length": 229
} |
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",
... | 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",
| {
"filepath": "django/core/management/commands/testserver.py",
"language": "python",
"file_size": 2221,
"cut_index": 563,
"middle_length": 229
} |
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
__al... | 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 | {
"filepath": "django/core/servers/basehttp.py",
"language": "python",
"file_size": 9776,
"cut_index": 921,
"middle_length": 229
} |
(__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_mo... | 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 | {
"filepath": "scripts/check_migrations.py",
"language": "python",
"file_size": 964,
"cut_index": 582,
"middle_length": 52
} |
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
... | ]
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" | {
"filepath": "scripts/manage_translations.py",
"language": "python",
"file_size": 13511,
"cut_index": 921,
"middle_length": 229
} |
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(sel... | 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 | {
"filepath": "scripts/tests.py",
"language": "python",
"file_size": 9342,
"cut_index": 921,
"middle_length": 229
} |
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(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"</strong></summary>\n\n{body}\n\n</details>"
)
CONTRIBUTING_URL = "https://docs.djangoproject.com/en/dev/internals/contributing/"
SUBMITTING_URL = f"{CONTRIBUTING_URL}writing- | {
"filepath": "scripts/pr_quality/errors.py",
"language": "python",
"file_size": 6891,
"cut_index": 716,
"middle_length": 229
} |
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_TRA... | 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 | {
"filepath": "scripts/pr_quality/check_pr.py",
"language": "python",
"file_size": 19541,
"cut_index": 1331,
"middle_length": 229
} |
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 impo... | 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 | {
"filepath": "django/shortcuts.py",
"language": "python",
"file_size": 6884,
"cut_index": 716,
"middle_length": 229
} |
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 urlr... | 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 | s.log import c | {
"filepath": "django/__init__.py",
"language": "python",
"file_size": 799,
"cut_index": 517,
"middle_length": 14
} |
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 pr... |
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 | {
"filepath": "django/middleware/cache.py",
"language": "python",
"file_size": 8880,
"cut_index": 716,
"middle_length": 229
} |
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.... | 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
| {
"filepath": "django/middleware/csp.py",
"language": "python",
"file_size": 1279,
"cut_index": 524,
"middle_length": 229
} |
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:
... | 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 | {
"filepath": "django/middleware/common.py",
"language": "python",
"file_size": 8162,
"cut_index": 716,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/middleware/csrf.py",
"language": "python",
"file_size": 19521,
"cut_index": 1331,
"middle_length": 229
} |
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... | != "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 | {
"filepath": "django/middleware/http.py",
"language": "python",
"file_size": 1620,
"cut_index": 537,
"middle_length": 229
} |
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 = sett... | 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 | {
"filepath": "django/middleware/security.py",
"language": "python",
"file_size": 2599,
"cut_index": 563,
"middle_length": 229
} |
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 = _("…")
... | 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
| {
"filepath": "django/core/paginator.py",
"language": "python",
"file_size": 15061,
"cut_index": 921,
"middle_length": 229
} |
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 decid... | 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_ | {
"filepath": "django/middleware/locale.py",
"language": "python",
"file_size": 3442,
"cut_index": 614,
"middle_length": 229
} |
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:1Q... | '
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 | {
"filepath": "django/core/signing.py",
"language": "python",
"file_size": 9305,
"cut_index": 921,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/exceptions.py",
"language": "python",
"file_size": 6771,
"cut_index": 716,
"middle_length": 229
} |
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_c... | 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 | {
"filepath": "django/core/handlers/base.py",
"language": "python",
"file_size": 14840,
"cut_index": 921,
"middle_length": 229
} |
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 pas... | 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 | {
"filepath": "django/core/handlers/wsgi.py",
"language": "python",
"file_size": 7314,
"cut_index": 716,
"middle_length": 229
} |
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 a... | -- 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 | {
"filepath": "django/core/management/__init__.py",
"language": "python",
"file_size": 17413,
"cut_index": 1331,
"middle_length": 229
} |
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)... | 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 | {
"filepath": "django/core/handlers/asgi.py",
"language": "python",
"file_size": 13839,
"cut_index": 921,
"middle_length": 229
} |
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... |
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 | {
"filepath": "django/core/handlers/exception.py",
"language": "python",
"file_size": 5980,
"cut_index": 716,
"middle_length": 229
} |
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
# WSGIRestric... | """
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.
| {
"filepath": "django/core/management/color.py",
"language": "python",
"file_size": 3168,
"cut_index": 614,
"middle_length": 229
} |
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 th... | 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 | {
"filepath": "django/core/management/templates.py",
"language": "python",
"file_size": 15458,
"cut_index": 921,
"middle_length": 229
} |
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 ... | 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 | {
"filepath": "django/core/management/utils.py",
"language": "python",
"file_size": 5636,
"cut_index": 716,
"middle_length": 229
} |
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."
... | 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_ | {
"filepath": "django/core/management/commands/createcachetable.py",
"language": "python",
"file_size": 4656,
"cut_index": 614,
"middle_length": 229
} |
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
)
... | 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:
| {
"filepath": "django/core/management/sql.py",
"language": "python",
"file_size": 1851,
"cut_index": 537,
"middle_length": 229
} |
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):... | ",
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 | {
"filepath": "django/core/management/commands/compilemessages.py",
"language": "python",
"file_size": 7010,
"cut_index": 716,
"middle_length": 229
} |
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, ... | 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 | {
"filepath": "django/core/management/commands/check.py",
"language": "python",
"file_size": 2832,
"cut_index": 563,
"middle_length": 229
} |
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 = []
de... | 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 | {
"filepath": "django/core/management/commands/dbshell.py",
"language": "python",
"file_size": 1762,
"cut_index": 537,
"middle_length": 229
} |
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_argu... | 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 | {
"filepath": "django/core/management/commands/dumpdata.py",
"language": "python",
"file_size": 11194,
"cut_index": 921,
"middle_length": 229
} |
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="Al... | 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)
| {
"filepath": "django/core/management/commands/inspectdb.py",
"language": "python",
"file_size": 17670,
"cut_index": 1331,
"middle_length": 229
} |
\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 i... | 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__.__ | {
"filepath": "django/core/management/commands/makemessages.py",
"language": "python",
"file_size": 29123,
"cut_index": 1331,
"middle_length": 229
} |
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(
"... | ,
)
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." | {
"filepath": "django/core/management/commands/migrate.py",
"language": "python",
"file_size": 21505,
"cut_index": 1331,
"middle_length": 229
} |
.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,... | 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 | {
"filepath": "django/core/management/commands/runserver.py",
"language": "python",
"file_size": 7560,
"cut_index": 716,
"middle_length": 229
} |
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
... | "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(
| {
"filepath": "django/core/management/commands/loaddata.py",
"language": "python",
"file_size": 16008,
"cut_index": 921,
"middle_length": 229
} |
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):
... | 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",
| {
"filepath": "django/core/management/commands/optimizemigration.py",
"language": "python",
"file_size": 5244,
"cut_index": 716,
"middle_length": 229
} |
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 duri... | )
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.",
| {
"filepath": "django/core/management/commands/flush.py",
"language": "python",
"file_size": 3623,
"cut_index": 614,
"middle_length": 229
} |
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, pa... | ,
)
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." | {
"filepath": "django/core/management/commands/shell.py",
"language": "python",
"file_size": 9695,
"cut_index": 921,
"middle_length": 229
} |
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 li... | "--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(
| {
"filepath": "django/core/management/commands/showmigrations.py",
"language": "python",
"file_size": 6847,
"cut_index": 716,
"middle_length": 229
} |
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().... | 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:
| {
"filepath": "django/core/management/commands/sqlsequencereset.py",
"language": "python",
"file_size": 1101,
"cut_index": 515,
"middle_length": 229
} |
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 cu... | 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 | "name")
| {
"filepath": "django/core/management/commands/startproject.py",
"language": "python",
"file_size": 809,
"cut_index": 536,
"middle_length": 14
} |
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_arg... | 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=" | {
"filepath": "django/core/management/commands/makemigrations.py",
"language": "python",
"file_size": 22559,
"cut_index": 1331,
"middle_length": 229
} |
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... | ),
)
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."
| {
"filepath": "django/core/management/commands/sqlflush.py",
"language": "python",
"file_size": 1031,
"cut_index": 513,
"middle_length": 229
} |
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(
... | 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 | {
"filepath": "django/core/management/commands/squashmigrations.py",
"language": "python",
"file_size": 10131,
"cut_index": 921,
"middle_length": 229
} |
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(
... | 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 | {
"filepath": "django/core/management/commands/sqlmigrate.py",
"language": "python",
"file_size": 3310,
"cut_index": 614,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/cache/__init__.py",
"language": "python",
"file_size": 1928,
"cut_index": 537,
"middle_length": 229
} |
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_... | # 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):
| {
"filepath": "django/core/cache/backends/db.py",
"language": "python",
"file_size": 11392,
"cut_index": 921,
"middle_length": 229
} |
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)... | 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 | {
"filepath": "django/core/cache/backends/filebased.py",
"language": "python",
"file_size": 5797,
"cut_index": 716,
"middle_length": 229
} |
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
... | 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):
"""
| {
"filepath": "django/core/cache/backends/memcached.py",
"language": "python",
"file_size": 6791,
"cut_index": 716,
"middle_length": 229
} |
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 modu... | _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 | {
"filepath": "django/core/management/commands/test.py",
"language": "python",
"file_size": 2367,
"cut_index": 563,
"middle_length": 229
} |
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(k... | 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 | {
"filepath": "django/core/cache/backends/dummy.py",
"language": "python",
"file_size": 1043,
"cut_index": 513,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/cache/backends/redis.py",
"language": "python",
"file_size": 8491,
"cut_index": 716,
"middle_length": 229
} |
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 impo... | 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 | {
"filepath": "django/core/serializers/__init__.py",
"language": "python",
"file_size": 8785,
"cut_index": 716,
"middle_length": 229
} |
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 bei... | 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 | {
"filepath": "django/core/files/temp.py",
"language": "python",
"file_size": 2503,
"cut_index": 563,
"middle_length": 229
} |
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._... | 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:
| {
"filepath": "django/core/mail/backends/filebased.py",
"language": "python",
"file_size": 3659,
"cut_index": 614,
"middle_length": 229
} |
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 d... | 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 | {
"filepath": "django/contrib/gis/measure.py",
"language": "python",
"file_size": 12576,
"cut_index": 921,
"middle_length": 229
} |
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_PROT... | 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 | {
"filepath": "django/core/cache/backends/locmem.py",
"language": "python",
"file_size": 4036,
"cut_index": 614,
"middle_length": 229
} |
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(struc... | # 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
| {
"filepath": "django/contrib/gis/db/backends/postgis/pgraster.py",
"language": "python",
"file_size": 4588,
"cut_index": 614,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/checks/security/base.py",
"language": "python",
"file_size": 11550,
"cut_index": 921,
"middle_length": 229
} |
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:sk... | 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 | {
"filepath": "django/core/checks/__init__.py",
"language": "python",
"file_size": 1248,
"cut_index": 518,
"middle_length": 229
} |
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 chec... | 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
| {
"filepath": "django/core/checks/caches.py",
"language": "python",
"file_size": 2643,
"cut_index": 563,
"middle_length": 229
} |
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(
... | % (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."
| {
"filepath": "django/core/checks/model_checks.py",
"language": "python",
"file_size": 8820,
"cut_index": 716,
"middle_length": 229
} |
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(
... | 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 | {
"filepath": "django/core/checks/translation.py",
"language": "python",
"file_size": 1990,
"cut_index": 537,
"middle_length": 229
} |
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 chec... | 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_ | {
"filepath": "django/core/checks/urls.py",
"language": "python",
"file_size": 4906,
"cut_index": 614,
"middle_length": 229
} |
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.
Construc... | 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 | {
"filepath": "django/core/cache/backends/base.py",
"language": "python",
"file_size": 15772,
"cut_index": 921,
"middle_length": 229
} |
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
sel... | 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 | {
"filepath": "django/core/checks/messages.py",
"language": "python",
"file_size": 2255,
"cut_index": 563,
"middle_length": 229
} |
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():
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_ | {
"filepath": "django/core/checks/security/csrf.py",
"language": "python",
"file_size": 2089,
"cut_index": 563,
"middle_length": 229
} |
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 = ... | 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 | {
"filepath": "django/core/checks/registry.py",
"language": "python",
"file_size": 3880,
"cut_index": 614,
"middle_length": 229
} |
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")... | f"makemigrations.Command.autodetector is "
f"{make_migrations.autodetector.__name__}, but "
f"migrate.Command.autodetector is "
f"{migrate.autodetector.__name__}."
),
| "autodetector.",
hint=(
| {
"filepath": "django/core/checks/commands.py",
"language": "python",
"file_size": 965,
"cut_index": 582,
"middle_length": 52
} |
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... | 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 | {
"filepath": "django/core/serializers/json.py",
"language": "python",
"file_size": 3714,
"cut_index": 614,
"middle_length": 229
} |
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.
"""
intern... | 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 | {
"filepath": "django/core/serializers/python.py",
"language": "python",
"file_size": 8902,
"cut_index": 716,
"middle_length": 229
} |
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.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")
| {
"filepath": "django/core/serializers/xml_serializer.py",
"language": "python",
"file_size": 21893,
"cut_index": 1331,
"middle_length": 229
} |
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._g... | ):
"""
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 | {
"filepath": "django/core/files/images.py",
"language": "python",
"file_size": 2643,
"cut_index": 563,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/files/locks.py",
"language": "python",
"file_size": 3614,
"cut_index": 614,
"middle_length": 229
} |
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.... | _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 | {
"filepath": "django/core/checks/security/sessions.py",
"language": "python",
"file_size": 2569,
"cut_index": 563,
"middle_length": 229
} |
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 cl... | 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 | {
"filepath": "django/core/serializers/base.py",
"language": "python",
"file_size": 13573,
"cut_index": 921,
"middle_length": 229
} |
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... | 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 | {
"filepath": "django/core/files/base.py",
"language": "python",
"file_size": 4976,
"cut_index": 614,
"middle_length": 229
} |
>> 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_overwr... |
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. | {
"filepath": "django/core/files/move.py",
"language": "python",
"file_size": 2951,
"cut_index": 563,
"middle_length": 229
} |
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):
... | 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 | {
"filepath": "django/core/serializers/jsonl.py",
"language": "python",
"file_size": 2258,
"cut_index": 563,
"middle_length": 229
} |
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... | 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))
| {
"filepath": "django/core/serializers/pyyaml.py",
"language": "python",
"file_size": 2619,
"cut_index": 563,
"middle_length": 229
} |
import InMemoryUploadedFile, TemporaryUploadedFile
from django.utils.module_loading import import_string
__all__ = [
"UploadFileException",
"StopUpload",
"SkipFile",
"FileUploadHandler",
"TemporaryFileUploadHandler",
"MemoryFileUploadHandler",
"load_handler",
"StopFutureHandlers",
]
... | 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 | {
"filepath": "django/core/files/uploadhandler.py",
"language": "python",
"file_size": 7813,
"cut_index": 716,
"middle_length": 229
} |
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.
# ... | 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 | {
"filepath": "django/core/files/storage/base.py",
"language": "python",
"file_size": 8297,
"cut_index": 716,
"middle_length": 229
} |
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):
# back... | 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]
| {
"filepath": "django/core/files/storage/handler.py",
"language": "python",
"file_size": 1507,
"cut_index": 524,
"middle_length": 229
} |
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 d... | 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,
| {
"filepath": "django/core/mail/__init__.py",
"language": "python",
"file_size": 12405,
"cut_index": 921,
"middle_length": 229
} |
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 __get... | _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 | {
"filepath": "django/core/mail/handler.py",
"language": "python",
"file_size": 2727,
"cut_index": 563,
"middle_length": 229
} |
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 ... | 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 | {
"filepath": "django/core/mail/backends/base.py",
"language": "python",
"file_size": 4262,
"cut_index": 614,
"middle_length": 229
} |
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 abstra... | 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 | {
"filepath": "django/core/files/uploadedfile.py",
"language": "python",
"file_size": 4263,
"cut_index": 614,
"middle_length": 229
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.