Add files using upload-large-folder tool
Browse files- testbed/django__django/django/utils/ipv6.py +47 -0
- testbed/django__django/django/utils/log.py +250 -0
- testbed/django__django/django/utils/numberformat.py +105 -0
- testbed/django__django/django/utils/safestring.py +72 -0
- testbed/django__django/django/utils/text.py +455 -0
- testbed/django__django/django/utils/timezone.py +259 -0
- testbed/django__django/django/utils/version.py +121 -0
- testbed/django__django/django/views/decorators/__init__.py +0 -0
- testbed/django__django/django/views/decorators/cache.py +84 -0
- testbed/django__django/django/views/decorators/common.py +27 -0
- testbed/django__django/django/views/decorators/csrf.py +69 -0
- testbed/django__django/django/views/decorators/gzip.py +5 -0
- testbed/django__django/django/views/defaults.py +149 -0
- testbed/django__django/django/views/generic/base.py +285 -0
- testbed/django__django/django/views/generic/detail.py +180 -0
- testbed/django__django/django/views/templates/default_urlconf.html +253 -0
- testbed/django__django/django/views/templates/i18n_catalog.js +102 -0
testbed/django__django/django/utils/ipv6.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import ipaddress
|
| 2 |
+
|
| 3 |
+
from django.core.exceptions import ValidationError
|
| 4 |
+
from django.utils.translation import gettext_lazy as _
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def clean_ipv6_address(
|
| 8 |
+
ip_str, unpack_ipv4=False, error_message=_("This is not a valid IPv6 address.")
|
| 9 |
+
):
|
| 10 |
+
"""
|
| 11 |
+
Clean an IPv6 address string.
|
| 12 |
+
|
| 13 |
+
Raise ValidationError if the address is invalid.
|
| 14 |
+
|
| 15 |
+
Replace the longest continuous zero-sequence with "::", remove leading
|
| 16 |
+
zeroes, and make sure all hextets are lowercase.
|
| 17 |
+
|
| 18 |
+
Args:
|
| 19 |
+
ip_str: A valid IPv6 address.
|
| 20 |
+
unpack_ipv4: if an IPv4-mapped address is found,
|
| 21 |
+
return the plain IPv4 address (default=False).
|
| 22 |
+
error_message: An error message used in the ValidationError.
|
| 23 |
+
|
| 24 |
+
Return a compressed IPv6 address or the same value.
|
| 25 |
+
"""
|
| 26 |
+
try:
|
| 27 |
+
addr = ipaddress.IPv6Address(int(ipaddress.IPv6Address(ip_str)))
|
| 28 |
+
except ValueError:
|
| 29 |
+
raise ValidationError(error_message, code="invalid")
|
| 30 |
+
|
| 31 |
+
if unpack_ipv4 and addr.ipv4_mapped:
|
| 32 |
+
return str(addr.ipv4_mapped)
|
| 33 |
+
elif addr.ipv4_mapped:
|
| 34 |
+
return "::ffff:%s" % str(addr.ipv4_mapped)
|
| 35 |
+
|
| 36 |
+
return str(addr)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def is_valid_ipv6_address(ip_str):
|
| 40 |
+
"""
|
| 41 |
+
Return whether or not the `ip_str` string is a valid IPv6 address.
|
| 42 |
+
"""
|
| 43 |
+
try:
|
| 44 |
+
ipaddress.IPv6Address(ip_str)
|
| 45 |
+
except ValueError:
|
| 46 |
+
return False
|
| 47 |
+
return True
|
testbed/django__django/django/utils/log.py
ADDED
|
@@ -0,0 +1,250 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
import logging.config # needed when logging_config doesn't start with logging.config
|
| 3 |
+
from copy import copy
|
| 4 |
+
|
| 5 |
+
from django.conf import settings
|
| 6 |
+
from django.core import mail
|
| 7 |
+
from django.core.mail import get_connection
|
| 8 |
+
from django.core.management.color import color_style
|
| 9 |
+
from django.utils.module_loading import import_string
|
| 10 |
+
|
| 11 |
+
request_logger = logging.getLogger("django.request")
|
| 12 |
+
|
| 13 |
+
# Default logging for Django. This sends an email to the site admins on every
|
| 14 |
+
# HTTP 500 error. Depending on DEBUG, all other log records are either sent to
|
| 15 |
+
# the console (DEBUG=True) or discarded (DEBUG=False) by means of the
|
| 16 |
+
# require_debug_true filter. This configuration is quoted in
|
| 17 |
+
# docs/ref/logging.txt; please amend it there if edited here.
|
| 18 |
+
DEFAULT_LOGGING = {
|
| 19 |
+
"version": 1,
|
| 20 |
+
"disable_existing_loggers": False,
|
| 21 |
+
"filters": {
|
| 22 |
+
"require_debug_false": {
|
| 23 |
+
"()": "django.utils.log.RequireDebugFalse",
|
| 24 |
+
},
|
| 25 |
+
"require_debug_true": {
|
| 26 |
+
"()": "django.utils.log.RequireDebugTrue",
|
| 27 |
+
},
|
| 28 |
+
},
|
| 29 |
+
"formatters": {
|
| 30 |
+
"django.server": {
|
| 31 |
+
"()": "django.utils.log.ServerFormatter",
|
| 32 |
+
"format": "[{server_time}] {message}",
|
| 33 |
+
"style": "{",
|
| 34 |
+
}
|
| 35 |
+
},
|
| 36 |
+
"handlers": {
|
| 37 |
+
"console": {
|
| 38 |
+
"level": "INFO",
|
| 39 |
+
"filters": ["require_debug_true"],
|
| 40 |
+
"class": "logging.StreamHandler",
|
| 41 |
+
},
|
| 42 |
+
"django.server": {
|
| 43 |
+
"level": "INFO",
|
| 44 |
+
"class": "logging.StreamHandler",
|
| 45 |
+
"formatter": "django.server",
|
| 46 |
+
},
|
| 47 |
+
"mail_admins": {
|
| 48 |
+
"level": "ERROR",
|
| 49 |
+
"filters": ["require_debug_false"],
|
| 50 |
+
"class": "django.utils.log.AdminEmailHandler",
|
| 51 |
+
},
|
| 52 |
+
},
|
| 53 |
+
"loggers": {
|
| 54 |
+
"django": {
|
| 55 |
+
"handlers": ["console", "mail_admins"],
|
| 56 |
+
"level": "INFO",
|
| 57 |
+
},
|
| 58 |
+
"django.server": {
|
| 59 |
+
"handlers": ["django.server"],
|
| 60 |
+
"level": "INFO",
|
| 61 |
+
"propagate": False,
|
| 62 |
+
},
|
| 63 |
+
},
|
| 64 |
+
}
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def configure_logging(logging_config, logging_settings):
|
| 68 |
+
if logging_config:
|
| 69 |
+
# First find the logging configuration function ...
|
| 70 |
+
logging_config_func = import_string(logging_config)
|
| 71 |
+
|
| 72 |
+
logging.config.dictConfig(DEFAULT_LOGGING)
|
| 73 |
+
|
| 74 |
+
# ... then invoke it with the logging settings
|
| 75 |
+
if logging_settings:
|
| 76 |
+
logging_config_func(logging_settings)
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
class AdminEmailHandler(logging.Handler):
|
| 80 |
+
"""An exception log handler that emails log entries to site admins.
|
| 81 |
+
|
| 82 |
+
If the request is passed as the first argument to the log record,
|
| 83 |
+
request data will be provided in the email report.
|
| 84 |
+
"""
|
| 85 |
+
|
| 86 |
+
def __init__(self, include_html=False, email_backend=None, reporter_class=None):
|
| 87 |
+
super().__init__()
|
| 88 |
+
self.include_html = include_html
|
| 89 |
+
self.email_backend = email_backend
|
| 90 |
+
self.reporter_class = import_string(
|
| 91 |
+
reporter_class or settings.DEFAULT_EXCEPTION_REPORTER
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
def emit(self, record):
|
| 95 |
+
try:
|
| 96 |
+
request = record.request
|
| 97 |
+
subject = "%s (%s IP): %s" % (
|
| 98 |
+
record.levelname,
|
| 99 |
+
(
|
| 100 |
+
"internal"
|
| 101 |
+
if request.META.get("REMOTE_ADDR") in settings.INTERNAL_IPS
|
| 102 |
+
else "EXTERNAL"
|
| 103 |
+
),
|
| 104 |
+
record.getMessage(),
|
| 105 |
+
)
|
| 106 |
+
except Exception:
|
| 107 |
+
subject = "%s: %s" % (record.levelname, record.getMessage())
|
| 108 |
+
request = None
|
| 109 |
+
subject = self.format_subject(subject)
|
| 110 |
+
|
| 111 |
+
# Since we add a nicely formatted traceback on our own, create a copy
|
| 112 |
+
# of the log record without the exception data.
|
| 113 |
+
no_exc_record = copy(record)
|
| 114 |
+
no_exc_record.exc_info = None
|
| 115 |
+
no_exc_record.exc_text = None
|
| 116 |
+
|
| 117 |
+
if record.exc_info:
|
| 118 |
+
exc_info = record.exc_info
|
| 119 |
+
else:
|
| 120 |
+
exc_info = (None, record.getMessage(), None)
|
| 121 |
+
|
| 122 |
+
reporter = self.reporter_class(request, is_email=True, *exc_info)
|
| 123 |
+
message = "%s\n\n%s" % (
|
| 124 |
+
self.format(no_exc_record),
|
| 125 |
+
reporter.get_traceback_text(),
|
| 126 |
+
)
|
| 127 |
+
html_message = reporter.get_traceback_html() if self.include_html else None
|
| 128 |
+
self.send_mail(subject, message, fail_silently=True, html_message=html_message)
|
| 129 |
+
|
| 130 |
+
def send_mail(self, subject, message, *args, **kwargs):
|
| 131 |
+
mail.mail_admins(
|
| 132 |
+
subject, message, *args, connection=self.connection(), **kwargs
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
def connection(self):
|
| 136 |
+
return get_connection(backend=self.email_backend, fail_silently=True)
|
| 137 |
+
|
| 138 |
+
def format_subject(self, subject):
|
| 139 |
+
"""
|
| 140 |
+
Escape CR and LF characters.
|
| 141 |
+
"""
|
| 142 |
+
return subject.replace("\n", "\\n").replace("\r", "\\r")
|
| 143 |
+
|
| 144 |
+
|
| 145 |
+
class CallbackFilter(logging.Filter):
|
| 146 |
+
"""
|
| 147 |
+
A logging filter that checks the return value of a given callable (which
|
| 148 |
+
takes the record-to-be-logged as its only parameter) to decide whether to
|
| 149 |
+
log a record.
|
| 150 |
+
"""
|
| 151 |
+
|
| 152 |
+
def __init__(self, callback):
|
| 153 |
+
self.callback = callback
|
| 154 |
+
|
| 155 |
+
def filter(self, record):
|
| 156 |
+
if self.callback(record):
|
| 157 |
+
return 1
|
| 158 |
+
return 0
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
class RequireDebugFalse(logging.Filter):
|
| 162 |
+
def filter(self, record):
|
| 163 |
+
return not settings.DEBUG
|
| 164 |
+
|
| 165 |
+
|
| 166 |
+
class RequireDebugTrue(logging.Filter):
|
| 167 |
+
def filter(self, record):
|
| 168 |
+
return settings.DEBUG
|
| 169 |
+
|
| 170 |
+
|
| 171 |
+
class ServerFormatter(logging.Formatter):
|
| 172 |
+
default_time_format = "%d/%b/%Y %H:%M:%S"
|
| 173 |
+
|
| 174 |
+
def __init__(self, *args, **kwargs):
|
| 175 |
+
self.style = color_style()
|
| 176 |
+
super().__init__(*args, **kwargs)
|
| 177 |
+
|
| 178 |
+
def format(self, record):
|
| 179 |
+
msg = record.msg
|
| 180 |
+
status_code = getattr(record, "status_code", None)
|
| 181 |
+
|
| 182 |
+
if status_code:
|
| 183 |
+
if 200 <= status_code < 300:
|
| 184 |
+
# Put 2XX first, since it should be the common case
|
| 185 |
+
msg = self.style.HTTP_SUCCESS(msg)
|
| 186 |
+
elif 100 <= status_code < 200:
|
| 187 |
+
msg = self.style.HTTP_INFO(msg)
|
| 188 |
+
elif status_code == 304:
|
| 189 |
+
msg = self.style.HTTP_NOT_MODIFIED(msg)
|
| 190 |
+
elif 300 <= status_code < 400:
|
| 191 |
+
msg = self.style.HTTP_REDIRECT(msg)
|
| 192 |
+
elif status_code == 404:
|
| 193 |
+
msg = self.style.HTTP_NOT_FOUND(msg)
|
| 194 |
+
elif 400 <= status_code < 500:
|
| 195 |
+
msg = self.style.HTTP_BAD_REQUEST(msg)
|
| 196 |
+
else:
|
| 197 |
+
# Any 5XX, or any other status code
|
| 198 |
+
msg = self.style.HTTP_SERVER_ERROR(msg)
|
| 199 |
+
|
| 200 |
+
if self.uses_server_time() and not hasattr(record, "server_time"):
|
| 201 |
+
record.server_time = self.formatTime(record, self.datefmt)
|
| 202 |
+
|
| 203 |
+
record.msg = msg
|
| 204 |
+
return super().format(record)
|
| 205 |
+
|
| 206 |
+
def uses_server_time(self):
|
| 207 |
+
return self._fmt.find("{server_time}") >= 0
|
| 208 |
+
|
| 209 |
+
|
| 210 |
+
def log_response(
|
| 211 |
+
message,
|
| 212 |
+
*args,
|
| 213 |
+
response=None,
|
| 214 |
+
request=None,
|
| 215 |
+
logger=request_logger,
|
| 216 |
+
level=None,
|
| 217 |
+
exception=None,
|
| 218 |
+
):
|
| 219 |
+
"""
|
| 220 |
+
Log errors based on HttpResponse status.
|
| 221 |
+
|
| 222 |
+
Log 5xx responses as errors and 4xx responses as warnings (unless a level
|
| 223 |
+
is given as a keyword argument). The HttpResponse status_code and the
|
| 224 |
+
request are passed to the logger's extra parameter.
|
| 225 |
+
"""
|
| 226 |
+
# Check if the response has already been logged. Multiple requests to log
|
| 227 |
+
# the same response can be received in some cases, e.g., when the
|
| 228 |
+
# response is the result of an exception and is logged when the exception
|
| 229 |
+
# is caught, to record the exception.
|
| 230 |
+
if getattr(response, "_has_been_logged", False):
|
| 231 |
+
return
|
| 232 |
+
|
| 233 |
+
if level is None:
|
| 234 |
+
if response.status_code >= 500:
|
| 235 |
+
level = "error"
|
| 236 |
+
elif response.status_code >= 400:
|
| 237 |
+
level = "warning"
|
| 238 |
+
else:
|
| 239 |
+
level = "info"
|
| 240 |
+
|
| 241 |
+
getattr(logger, level)(
|
| 242 |
+
message,
|
| 243 |
+
*args,
|
| 244 |
+
extra={
|
| 245 |
+
"status_code": response.status_code,
|
| 246 |
+
"request": request,
|
| 247 |
+
},
|
| 248 |
+
exc_info=exception,
|
| 249 |
+
)
|
| 250 |
+
response._has_been_logged = True
|
testbed/django__django/django/utils/numberformat.py
ADDED
|
@@ -0,0 +1,105 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from decimal import Decimal
|
| 2 |
+
|
| 3 |
+
from django.conf import settings
|
| 4 |
+
from django.utils.safestring import mark_safe
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
def format(
|
| 8 |
+
number,
|
| 9 |
+
decimal_sep,
|
| 10 |
+
decimal_pos=None,
|
| 11 |
+
grouping=0,
|
| 12 |
+
thousand_sep="",
|
| 13 |
+
force_grouping=False,
|
| 14 |
+
use_l10n=None,
|
| 15 |
+
):
|
| 16 |
+
"""
|
| 17 |
+
Get a number (as a number or string), and return it as a string,
|
| 18 |
+
using formats defined as arguments:
|
| 19 |
+
|
| 20 |
+
* decimal_sep: Decimal separator symbol (for example ".")
|
| 21 |
+
* decimal_pos: Number of decimal positions
|
| 22 |
+
* grouping: Number of digits in every group limited by thousand separator.
|
| 23 |
+
For non-uniform digit grouping, it can be a sequence with the number
|
| 24 |
+
of digit group sizes following the format used by the Python locale
|
| 25 |
+
module in locale.localeconv() LC_NUMERIC grouping (e.g. (3, 2, 0)).
|
| 26 |
+
* thousand_sep: Thousand separator symbol (for example ",")
|
| 27 |
+
"""
|
| 28 |
+
if number is None or number == "":
|
| 29 |
+
return mark_safe(number)
|
| 30 |
+
if use_l10n is None:
|
| 31 |
+
use_l10n = True
|
| 32 |
+
use_grouping = use_l10n and settings.USE_THOUSAND_SEPARATOR
|
| 33 |
+
use_grouping = use_grouping or force_grouping
|
| 34 |
+
use_grouping = use_grouping and grouping != 0
|
| 35 |
+
# Make the common case fast
|
| 36 |
+
if isinstance(number, int) and not use_grouping and not decimal_pos:
|
| 37 |
+
return mark_safe(number)
|
| 38 |
+
# sign
|
| 39 |
+
sign = ""
|
| 40 |
+
# Treat potentially very large/small floats as Decimals.
|
| 41 |
+
if isinstance(number, float) and "e" in str(number).lower():
|
| 42 |
+
number = Decimal(str(number))
|
| 43 |
+
if isinstance(number, Decimal):
|
| 44 |
+
if decimal_pos is not None:
|
| 45 |
+
# If the provided number is too small to affect any of the visible
|
| 46 |
+
# decimal places, consider it equal to '0'.
|
| 47 |
+
cutoff = Decimal("0." + "1".rjust(decimal_pos, "0"))
|
| 48 |
+
if abs(number) < cutoff:
|
| 49 |
+
number = Decimal("0")
|
| 50 |
+
|
| 51 |
+
# Format values with more than 200 digits (an arbitrary cutoff) using
|
| 52 |
+
# scientific notation to avoid high memory usage in {:f}'.format().
|
| 53 |
+
_, digits, exponent = number.as_tuple()
|
| 54 |
+
if abs(exponent) + len(digits) > 200:
|
| 55 |
+
number = "{:e}".format(number)
|
| 56 |
+
coefficient, exponent = number.split("e")
|
| 57 |
+
# Format the coefficient.
|
| 58 |
+
coefficient = format(
|
| 59 |
+
coefficient,
|
| 60 |
+
decimal_sep,
|
| 61 |
+
decimal_pos,
|
| 62 |
+
grouping,
|
| 63 |
+
thousand_sep,
|
| 64 |
+
force_grouping,
|
| 65 |
+
use_l10n,
|
| 66 |
+
)
|
| 67 |
+
return "{}e{}".format(coefficient, exponent)
|
| 68 |
+
else:
|
| 69 |
+
str_number = "{:f}".format(number)
|
| 70 |
+
else:
|
| 71 |
+
str_number = str(number)
|
| 72 |
+
if str_number[0] == "-":
|
| 73 |
+
sign = "-"
|
| 74 |
+
str_number = str_number[1:]
|
| 75 |
+
# decimal part
|
| 76 |
+
if "." in str_number:
|
| 77 |
+
int_part, dec_part = str_number.split(".")
|
| 78 |
+
if decimal_pos is not None:
|
| 79 |
+
dec_part = dec_part[:decimal_pos]
|
| 80 |
+
else:
|
| 81 |
+
int_part, dec_part = str_number, ""
|
| 82 |
+
if decimal_pos is not None:
|
| 83 |
+
dec_part += "0" * (decimal_pos - len(dec_part))
|
| 84 |
+
dec_part = dec_part and decimal_sep + dec_part
|
| 85 |
+
# grouping
|
| 86 |
+
if use_grouping:
|
| 87 |
+
try:
|
| 88 |
+
# if grouping is a sequence
|
| 89 |
+
intervals = list(grouping)
|
| 90 |
+
except TypeError:
|
| 91 |
+
# grouping is a single value
|
| 92 |
+
intervals = [grouping, 0]
|
| 93 |
+
active_interval = intervals.pop(0)
|
| 94 |
+
int_part_gd = ""
|
| 95 |
+
cnt = 0
|
| 96 |
+
for digit in int_part[::-1]:
|
| 97 |
+
if cnt and cnt == active_interval:
|
| 98 |
+
if intervals:
|
| 99 |
+
active_interval = intervals.pop(0) or active_interval
|
| 100 |
+
int_part_gd += thousand_sep[::-1]
|
| 101 |
+
cnt = 0
|
| 102 |
+
int_part_gd += digit
|
| 103 |
+
cnt += 1
|
| 104 |
+
int_part = int_part_gd[::-1]
|
| 105 |
+
return sign + int_part + dec_part
|
testbed/django__django/django/utils/safestring.py
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Functions for working with "safe strings": strings that can be displayed safely
|
| 3 |
+
without further escaping in HTML. Marking something as a "safe string" means
|
| 4 |
+
that the producer of the string has already turned characters that should not
|
| 5 |
+
be interpreted by the HTML engine (e.g. '<') into the appropriate entities.
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
from functools import wraps
|
| 9 |
+
|
| 10 |
+
from django.utils.functional import keep_lazy
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class SafeData:
|
| 14 |
+
__slots__ = ()
|
| 15 |
+
|
| 16 |
+
def __html__(self):
|
| 17 |
+
"""
|
| 18 |
+
Return the html representation of a string for interoperability.
|
| 19 |
+
|
| 20 |
+
This allows other template engines to understand Django's SafeData.
|
| 21 |
+
"""
|
| 22 |
+
return self
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class SafeString(str, SafeData):
|
| 26 |
+
"""
|
| 27 |
+
A str subclass that has been specifically marked as "safe" for HTML output
|
| 28 |
+
purposes.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
__slots__ = ()
|
| 32 |
+
|
| 33 |
+
def __add__(self, rhs):
|
| 34 |
+
"""
|
| 35 |
+
Concatenating a safe string with another safe bytestring or
|
| 36 |
+
safe string is safe. Otherwise, the result is no longer safe.
|
| 37 |
+
"""
|
| 38 |
+
t = super().__add__(rhs)
|
| 39 |
+
if isinstance(rhs, SafeData):
|
| 40 |
+
return SafeString(t)
|
| 41 |
+
return t
|
| 42 |
+
|
| 43 |
+
def __str__(self):
|
| 44 |
+
return self
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
SafeText = SafeString # For backwards compatibility since Django 2.0.
|
| 48 |
+
|
| 49 |
+
|
| 50 |
+
def _safety_decorator(safety_marker, func):
|
| 51 |
+
@wraps(func)
|
| 52 |
+
def wrapper(*args, **kwargs):
|
| 53 |
+
return safety_marker(func(*args, **kwargs))
|
| 54 |
+
|
| 55 |
+
return wrapper
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
@keep_lazy(SafeString)
|
| 59 |
+
def mark_safe(s):
|
| 60 |
+
"""
|
| 61 |
+
Explicitly mark a string as safe for (HTML) output purposes. The returned
|
| 62 |
+
object can be used everywhere a string is appropriate.
|
| 63 |
+
|
| 64 |
+
If used on a method as a decorator, mark the returned data as safe.
|
| 65 |
+
|
| 66 |
+
Can be called multiple times on a single string.
|
| 67 |
+
"""
|
| 68 |
+
if hasattr(s, "__html__"):
|
| 69 |
+
return s
|
| 70 |
+
if callable(s):
|
| 71 |
+
return _safety_decorator(mark_safe, s)
|
| 72 |
+
return SafeString(s)
|
testbed/django__django/django/utils/text.py
ADDED
|
@@ -0,0 +1,455 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gzip
|
| 2 |
+
import re
|
| 3 |
+
import secrets
|
| 4 |
+
import unicodedata
|
| 5 |
+
from gzip import GzipFile
|
| 6 |
+
from gzip import compress as gzip_compress
|
| 7 |
+
from io import BytesIO
|
| 8 |
+
|
| 9 |
+
from django.core.exceptions import SuspiciousFileOperation
|
| 10 |
+
from django.utils.functional import SimpleLazyObject, keep_lazy_text, lazy
|
| 11 |
+
from django.utils.regex_helper import _lazy_re_compile
|
| 12 |
+
from django.utils.translation import gettext as _
|
| 13 |
+
from django.utils.translation import gettext_lazy, pgettext
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
@keep_lazy_text
|
| 17 |
+
def capfirst(x):
|
| 18 |
+
"""Capitalize the first letter of a string."""
|
| 19 |
+
if not x:
|
| 20 |
+
return x
|
| 21 |
+
if not isinstance(x, str):
|
| 22 |
+
x = str(x)
|
| 23 |
+
return x[0].upper() + x[1:]
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
# Set up regular expressions
|
| 27 |
+
re_words = _lazy_re_compile(r"<[^>]+?>|([^<>\s]+)", re.S)
|
| 28 |
+
re_chars = _lazy_re_compile(r"<[^>]+?>|(.)", re.S)
|
| 29 |
+
re_tag = _lazy_re_compile(r"<(/)?(\S+?)(?:(\s*/)|\s.*?)?>", re.S)
|
| 30 |
+
re_newlines = _lazy_re_compile(r"\r\n|\r") # Used in normalize_newlines
|
| 31 |
+
re_camel_case = _lazy_re_compile(r"(((?<=[a-z])[A-Z])|([A-Z](?![A-Z]|$)))")
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@keep_lazy_text
|
| 35 |
+
def wrap(text, width):
|
| 36 |
+
"""
|
| 37 |
+
A word-wrap function that preserves existing line breaks. Expects that
|
| 38 |
+
existing line breaks are posix newlines.
|
| 39 |
+
|
| 40 |
+
Preserve all white space except added line breaks consume the space on
|
| 41 |
+
which they break the line.
|
| 42 |
+
|
| 43 |
+
Don't wrap long words, thus the output text may have lines longer than
|
| 44 |
+
``width``.
|
| 45 |
+
"""
|
| 46 |
+
|
| 47 |
+
def _generator():
|
| 48 |
+
for line in text.splitlines(True): # True keeps trailing linebreaks
|
| 49 |
+
max_width = min((line.endswith("\n") and width + 1 or width), width)
|
| 50 |
+
while len(line) > max_width:
|
| 51 |
+
space = line[: max_width + 1].rfind(" ") + 1
|
| 52 |
+
if space == 0:
|
| 53 |
+
space = line.find(" ") + 1
|
| 54 |
+
if space == 0:
|
| 55 |
+
yield line
|
| 56 |
+
line = ""
|
| 57 |
+
break
|
| 58 |
+
yield "%s\n" % line[: space - 1]
|
| 59 |
+
line = line[space:]
|
| 60 |
+
max_width = min((line.endswith("\n") and width + 1 or width), width)
|
| 61 |
+
if line:
|
| 62 |
+
yield line
|
| 63 |
+
|
| 64 |
+
return "".join(_generator())
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
class Truncator(SimpleLazyObject):
|
| 68 |
+
"""
|
| 69 |
+
An object used to truncate text, either by characters or words.
|
| 70 |
+
"""
|
| 71 |
+
|
| 72 |
+
def __init__(self, text):
|
| 73 |
+
super().__init__(lambda: str(text))
|
| 74 |
+
|
| 75 |
+
def add_truncation_text(self, text, truncate=None):
|
| 76 |
+
if truncate is None:
|
| 77 |
+
truncate = pgettext(
|
| 78 |
+
"String to return when truncating text", "%(truncated_text)s…"
|
| 79 |
+
)
|
| 80 |
+
if "%(truncated_text)s" in truncate:
|
| 81 |
+
return truncate % {"truncated_text": text}
|
| 82 |
+
# The truncation text didn't contain the %(truncated_text)s string
|
| 83 |
+
# replacement argument so just append it to the text.
|
| 84 |
+
if text.endswith(truncate):
|
| 85 |
+
# But don't append the truncation text if the current text already
|
| 86 |
+
# ends in this.
|
| 87 |
+
return text
|
| 88 |
+
return "%s%s" % (text, truncate)
|
| 89 |
+
|
| 90 |
+
def chars(self, num, truncate=None, html=False):
|
| 91 |
+
"""
|
| 92 |
+
Return the text truncated to be no longer than the specified number
|
| 93 |
+
of characters.
|
| 94 |
+
|
| 95 |
+
`truncate` specifies what should be used to notify that the string has
|
| 96 |
+
been truncated, defaulting to a translatable string of an ellipsis.
|
| 97 |
+
"""
|
| 98 |
+
self._setup()
|
| 99 |
+
length = int(num)
|
| 100 |
+
text = unicodedata.normalize("NFC", self._wrapped)
|
| 101 |
+
|
| 102 |
+
# Calculate the length to truncate to (max length - end_text length)
|
| 103 |
+
truncate_len = length
|
| 104 |
+
for char in self.add_truncation_text("", truncate):
|
| 105 |
+
if not unicodedata.combining(char):
|
| 106 |
+
truncate_len -= 1
|
| 107 |
+
if truncate_len == 0:
|
| 108 |
+
break
|
| 109 |
+
if html:
|
| 110 |
+
return self._truncate_html(length, truncate, text, truncate_len, False)
|
| 111 |
+
return self._text_chars(length, truncate, text, truncate_len)
|
| 112 |
+
|
| 113 |
+
def _text_chars(self, length, truncate, text, truncate_len):
|
| 114 |
+
"""Truncate a string after a certain number of chars."""
|
| 115 |
+
s_len = 0
|
| 116 |
+
end_index = None
|
| 117 |
+
for i, char in enumerate(text):
|
| 118 |
+
if unicodedata.combining(char):
|
| 119 |
+
# Don't consider combining characters
|
| 120 |
+
# as adding to the string length
|
| 121 |
+
continue
|
| 122 |
+
s_len += 1
|
| 123 |
+
if end_index is None and s_len > truncate_len:
|
| 124 |
+
end_index = i
|
| 125 |
+
if s_len > length:
|
| 126 |
+
# Return the truncated string
|
| 127 |
+
return self.add_truncation_text(text[: end_index or 0], truncate)
|
| 128 |
+
|
| 129 |
+
# Return the original string since no truncation was necessary
|
| 130 |
+
return text
|
| 131 |
+
|
| 132 |
+
def words(self, num, truncate=None, html=False):
|
| 133 |
+
"""
|
| 134 |
+
Truncate a string after a certain number of words. `truncate` specifies
|
| 135 |
+
what should be used to notify that the string has been truncated,
|
| 136 |
+
defaulting to ellipsis.
|
| 137 |
+
"""
|
| 138 |
+
self._setup()
|
| 139 |
+
length = int(num)
|
| 140 |
+
if html:
|
| 141 |
+
return self._truncate_html(length, truncate, self._wrapped, length, True)
|
| 142 |
+
return self._text_words(length, truncate)
|
| 143 |
+
|
| 144 |
+
def _text_words(self, length, truncate):
|
| 145 |
+
"""
|
| 146 |
+
Truncate a string after a certain number of words.
|
| 147 |
+
|
| 148 |
+
Strip newlines in the string.
|
| 149 |
+
"""
|
| 150 |
+
words = self._wrapped.split()
|
| 151 |
+
if len(words) > length:
|
| 152 |
+
words = words[:length]
|
| 153 |
+
return self.add_truncation_text(" ".join(words), truncate)
|
| 154 |
+
return " ".join(words)
|
| 155 |
+
|
| 156 |
+
def _truncate_html(self, length, truncate, text, truncate_len, words):
|
| 157 |
+
"""
|
| 158 |
+
Truncate HTML to a certain number of chars (not counting tags and
|
| 159 |
+
comments), or, if words is True, then to a certain number of words.
|
| 160 |
+
Close opened tags if they were correctly closed in the given HTML.
|
| 161 |
+
|
| 162 |
+
Preserve newlines in the HTML.
|
| 163 |
+
"""
|
| 164 |
+
if words and length <= 0:
|
| 165 |
+
return ""
|
| 166 |
+
|
| 167 |
+
html4_singlets = (
|
| 168 |
+
"br",
|
| 169 |
+
"col",
|
| 170 |
+
"link",
|
| 171 |
+
"base",
|
| 172 |
+
"img",
|
| 173 |
+
"param",
|
| 174 |
+
"area",
|
| 175 |
+
"hr",
|
| 176 |
+
"input",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
# Count non-HTML chars/words and keep note of open tags
|
| 180 |
+
pos = 0
|
| 181 |
+
end_text_pos = 0
|
| 182 |
+
current_len = 0
|
| 183 |
+
open_tags = []
|
| 184 |
+
|
| 185 |
+
regex = re_words if words else re_chars
|
| 186 |
+
|
| 187 |
+
while current_len <= length:
|
| 188 |
+
m = regex.search(text, pos)
|
| 189 |
+
if not m:
|
| 190 |
+
# Checked through whole string
|
| 191 |
+
break
|
| 192 |
+
pos = m.end(0)
|
| 193 |
+
if m[1]:
|
| 194 |
+
# It's an actual non-HTML word or char
|
| 195 |
+
current_len += 1
|
| 196 |
+
if current_len == truncate_len:
|
| 197 |
+
end_text_pos = pos
|
| 198 |
+
continue
|
| 199 |
+
# Check for tag
|
| 200 |
+
tag = re_tag.match(m[0])
|
| 201 |
+
if not tag or current_len >= truncate_len:
|
| 202 |
+
# Don't worry about non tags or tags after our truncate point
|
| 203 |
+
continue
|
| 204 |
+
closing_tag, tagname, self_closing = tag.groups()
|
| 205 |
+
# Element names are always case-insensitive
|
| 206 |
+
tagname = tagname.lower()
|
| 207 |
+
if self_closing or tagname in html4_singlets:
|
| 208 |
+
pass
|
| 209 |
+
elif closing_tag:
|
| 210 |
+
# Check for match in open tags list
|
| 211 |
+
try:
|
| 212 |
+
i = open_tags.index(tagname)
|
| 213 |
+
except ValueError:
|
| 214 |
+
pass
|
| 215 |
+
else:
|
| 216 |
+
# SGML: An end tag closes, back to the matching start tag,
|
| 217 |
+
# all unclosed intervening start tags with omitted end tags
|
| 218 |
+
open_tags = open_tags[i + 1 :]
|
| 219 |
+
else:
|
| 220 |
+
# Add it to the start of the open tags list
|
| 221 |
+
open_tags.insert(0, tagname)
|
| 222 |
+
|
| 223 |
+
if current_len <= length:
|
| 224 |
+
return text
|
| 225 |
+
out = text[:end_text_pos]
|
| 226 |
+
truncate_text = self.add_truncation_text("", truncate)
|
| 227 |
+
if truncate_text:
|
| 228 |
+
out += truncate_text
|
| 229 |
+
# Close any tags still open
|
| 230 |
+
for tag in open_tags:
|
| 231 |
+
out += "</%s>" % tag
|
| 232 |
+
# Return string
|
| 233 |
+
return out
|
| 234 |
+
|
| 235 |
+
|
| 236 |
+
@keep_lazy_text
|
| 237 |
+
def get_valid_filename(name):
|
| 238 |
+
"""
|
| 239 |
+
Return the given string converted to a string that can be used for a clean
|
| 240 |
+
filename. Remove leading and trailing spaces; convert other spaces to
|
| 241 |
+
underscores; and remove anything that is not an alphanumeric, dash,
|
| 242 |
+
underscore, or dot.
|
| 243 |
+
>>> get_valid_filename("john's portrait in 2004.jpg")
|
| 244 |
+
'johns_portrait_in_2004.jpg'
|
| 245 |
+
"""
|
| 246 |
+
s = str(name).strip().replace(" ", "_")
|
| 247 |
+
s = re.sub(r"(?u)[^-\w.]", "", s)
|
| 248 |
+
if s in {"", ".", ".."}:
|
| 249 |
+
raise SuspiciousFileOperation("Could not derive file name from '%s'" % name)
|
| 250 |
+
return s
|
| 251 |
+
|
| 252 |
+
|
| 253 |
+
@keep_lazy_text
|
| 254 |
+
def get_text_list(list_, last_word=gettext_lazy("or")):
|
| 255 |
+
"""
|
| 256 |
+
>>> get_text_list(['a', 'b', 'c', 'd'])
|
| 257 |
+
'a, b, c or d'
|
| 258 |
+
>>> get_text_list(['a', 'b', 'c'], 'and')
|
| 259 |
+
'a, b and c'
|
| 260 |
+
>>> get_text_list(['a', 'b'], 'and')
|
| 261 |
+
'a and b'
|
| 262 |
+
>>> get_text_list(['a'])
|
| 263 |
+
'a'
|
| 264 |
+
>>> get_text_list([])
|
| 265 |
+
''
|
| 266 |
+
"""
|
| 267 |
+
if not list_:
|
| 268 |
+
return ""
|
| 269 |
+
if len(list_) == 1:
|
| 270 |
+
return str(list_[0])
|
| 271 |
+
return "%s %s %s" % (
|
| 272 |
+
# Translators: This string is used as a separator between list elements
|
| 273 |
+
_(", ").join(str(i) for i in list_[:-1]),
|
| 274 |
+
str(last_word),
|
| 275 |
+
str(list_[-1]),
|
| 276 |
+
)
|
| 277 |
+
|
| 278 |
+
|
| 279 |
+
@keep_lazy_text
|
| 280 |
+
def normalize_newlines(text):
|
| 281 |
+
"""Normalize CRLF and CR newlines to just LF."""
|
| 282 |
+
return re_newlines.sub("\n", str(text))
|
| 283 |
+
|
| 284 |
+
|
| 285 |
+
@keep_lazy_text
|
| 286 |
+
def phone2numeric(phone):
|
| 287 |
+
"""Convert a phone number with letters into its numeric equivalent."""
|
| 288 |
+
char2number = {
|
| 289 |
+
"a": "2",
|
| 290 |
+
"b": "2",
|
| 291 |
+
"c": "2",
|
| 292 |
+
"d": "3",
|
| 293 |
+
"e": "3",
|
| 294 |
+
"f": "3",
|
| 295 |
+
"g": "4",
|
| 296 |
+
"h": "4",
|
| 297 |
+
"i": "4",
|
| 298 |
+
"j": "5",
|
| 299 |
+
"k": "5",
|
| 300 |
+
"l": "5",
|
| 301 |
+
"m": "6",
|
| 302 |
+
"n": "6",
|
| 303 |
+
"o": "6",
|
| 304 |
+
"p": "7",
|
| 305 |
+
"q": "7",
|
| 306 |
+
"r": "7",
|
| 307 |
+
"s": "7",
|
| 308 |
+
"t": "8",
|
| 309 |
+
"u": "8",
|
| 310 |
+
"v": "8",
|
| 311 |
+
"w": "9",
|
| 312 |
+
"x": "9",
|
| 313 |
+
"y": "9",
|
| 314 |
+
"z": "9",
|
| 315 |
+
}
|
| 316 |
+
return "".join(char2number.get(c, c) for c in phone.lower())
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _get_random_filename(max_random_bytes):
|
| 320 |
+
return b"a" * secrets.randbelow(max_random_bytes)
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def compress_string(s, *, max_random_bytes=None):
|
| 324 |
+
compressed_data = gzip_compress(s, compresslevel=6, mtime=0)
|
| 325 |
+
|
| 326 |
+
if not max_random_bytes:
|
| 327 |
+
return compressed_data
|
| 328 |
+
|
| 329 |
+
compressed_view = memoryview(compressed_data)
|
| 330 |
+
header = bytearray(compressed_view[:10])
|
| 331 |
+
header[3] = gzip.FNAME
|
| 332 |
+
|
| 333 |
+
filename = _get_random_filename(max_random_bytes) + b"\x00"
|
| 334 |
+
|
| 335 |
+
return bytes(header) + filename + compressed_view[10:]
|
| 336 |
+
|
| 337 |
+
|
| 338 |
+
class StreamingBuffer(BytesIO):
|
| 339 |
+
def read(self):
|
| 340 |
+
ret = self.getvalue()
|
| 341 |
+
self.seek(0)
|
| 342 |
+
self.truncate()
|
| 343 |
+
return ret
|
| 344 |
+
|
| 345 |
+
|
| 346 |
+
# Like compress_string, but for iterators of strings.
|
| 347 |
+
def compress_sequence(sequence, *, max_random_bytes=None):
|
| 348 |
+
buf = StreamingBuffer()
|
| 349 |
+
filename = _get_random_filename(max_random_bytes) if max_random_bytes else None
|
| 350 |
+
with GzipFile(
|
| 351 |
+
filename=filename, mode="wb", compresslevel=6, fileobj=buf, mtime=0
|
| 352 |
+
) as zfile:
|
| 353 |
+
# Output headers...
|
| 354 |
+
yield buf.read()
|
| 355 |
+
for item in sequence:
|
| 356 |
+
zfile.write(item)
|
| 357 |
+
data = buf.read()
|
| 358 |
+
if data:
|
| 359 |
+
yield data
|
| 360 |
+
yield buf.read()
|
| 361 |
+
|
| 362 |
+
|
| 363 |
+
# Expression to match some_token and some_token="with spaces" (and similarly
|
| 364 |
+
# for single-quoted strings).
|
| 365 |
+
smart_split_re = _lazy_re_compile(
|
| 366 |
+
r"""
|
| 367 |
+
((?:
|
| 368 |
+
[^\s'"]*
|
| 369 |
+
(?:
|
| 370 |
+
(?:"(?:[^"\\]|\\.)*" | '(?:[^'\\]|\\.)*')
|
| 371 |
+
[^\s'"]*
|
| 372 |
+
)+
|
| 373 |
+
) | \S+)
|
| 374 |
+
""",
|
| 375 |
+
re.VERBOSE,
|
| 376 |
+
)
|
| 377 |
+
|
| 378 |
+
|
| 379 |
+
def smart_split(text):
|
| 380 |
+
r"""
|
| 381 |
+
Generator that splits a string by spaces, leaving quoted phrases together.
|
| 382 |
+
Supports both single and double quotes, and supports escaping quotes with
|
| 383 |
+
backslashes. In the output, strings will keep their initial and trailing
|
| 384 |
+
quote marks and escaped quotes will remain escaped (the results can then
|
| 385 |
+
be further processed with unescape_string_literal()).
|
| 386 |
+
|
| 387 |
+
>>> list(smart_split(r'This is "a person\'s" test.'))
|
| 388 |
+
['This', 'is', '"a person\\\'s"', 'test.']
|
| 389 |
+
>>> list(smart_split(r"Another 'person\'s' test."))
|
| 390 |
+
['Another', "'person\\'s'", 'test.']
|
| 391 |
+
>>> list(smart_split(r'A "\"funky\" style" test.'))
|
| 392 |
+
['A', '"\\"funky\\" style"', 'test.']
|
| 393 |
+
"""
|
| 394 |
+
for bit in smart_split_re.finditer(str(text)):
|
| 395 |
+
yield bit[0]
|
| 396 |
+
|
| 397 |
+
|
| 398 |
+
@keep_lazy_text
|
| 399 |
+
def unescape_string_literal(s):
|
| 400 |
+
r"""
|
| 401 |
+
Convert quoted string literals to unquoted strings with escaped quotes and
|
| 402 |
+
backslashes unquoted::
|
| 403 |
+
|
| 404 |
+
>>> unescape_string_literal('"abc"')
|
| 405 |
+
'abc'
|
| 406 |
+
>>> unescape_string_literal("'abc'")
|
| 407 |
+
'abc'
|
| 408 |
+
>>> unescape_string_literal('"a \"bc\""')
|
| 409 |
+
'a "bc"'
|
| 410 |
+
>>> unescape_string_literal("'\'ab\' c'")
|
| 411 |
+
"'ab' c"
|
| 412 |
+
"""
|
| 413 |
+
if not s or s[0] not in "\"'" or s[-1] != s[0]:
|
| 414 |
+
raise ValueError("Not a string literal: %r" % s)
|
| 415 |
+
quote = s[0]
|
| 416 |
+
return s[1:-1].replace(r"\%s" % quote, quote).replace(r"\\", "\\")
|
| 417 |
+
|
| 418 |
+
|
| 419 |
+
@keep_lazy_text
|
| 420 |
+
def slugify(value, allow_unicode=False):
|
| 421 |
+
"""
|
| 422 |
+
Convert to ASCII if 'allow_unicode' is False. Convert spaces or repeated
|
| 423 |
+
dashes to single dashes. Remove characters that aren't alphanumerics,
|
| 424 |
+
underscores, or hyphens. Convert to lowercase. Also strip leading and
|
| 425 |
+
trailing whitespace, dashes, and underscores.
|
| 426 |
+
"""
|
| 427 |
+
value = str(value)
|
| 428 |
+
if allow_unicode:
|
| 429 |
+
value = unicodedata.normalize("NFKC", value)
|
| 430 |
+
else:
|
| 431 |
+
value = (
|
| 432 |
+
unicodedata.normalize("NFKD", value)
|
| 433 |
+
.encode("ascii", "ignore")
|
| 434 |
+
.decode("ascii")
|
| 435 |
+
)
|
| 436 |
+
value = re.sub(r"[^\w\s-]", "", value.lower())
|
| 437 |
+
return re.sub(r"[-\s]+", "-", value).strip("-_")
|
| 438 |
+
|
| 439 |
+
|
| 440 |
+
def camel_case_to_spaces(value):
|
| 441 |
+
"""
|
| 442 |
+
Split CamelCase and convert to lowercase. Strip surrounding whitespace.
|
| 443 |
+
"""
|
| 444 |
+
return re_camel_case.sub(r" \1", value).strip().lower()
|
| 445 |
+
|
| 446 |
+
|
| 447 |
+
def _format_lazy(format_string, *args, **kwargs):
|
| 448 |
+
"""
|
| 449 |
+
Apply str.format() on 'format_string' where format_string, args,
|
| 450 |
+
and/or kwargs might be lazy.
|
| 451 |
+
"""
|
| 452 |
+
return format_string.format(*args, **kwargs)
|
| 453 |
+
|
| 454 |
+
|
| 455 |
+
format_lazy = lazy(_format_lazy, str)
|
testbed/django__django/django/utils/timezone.py
ADDED
|
@@ -0,0 +1,259 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
Timezone-related classes and functions.
|
| 3 |
+
"""
|
| 4 |
+
|
| 5 |
+
import functools
|
| 6 |
+
import zoneinfo
|
| 7 |
+
from contextlib import ContextDecorator
|
| 8 |
+
from datetime import datetime, timedelta, timezone, tzinfo
|
| 9 |
+
|
| 10 |
+
from asgiref.local import Local
|
| 11 |
+
|
| 12 |
+
from django.conf import settings
|
| 13 |
+
|
| 14 |
+
__all__ = [
|
| 15 |
+
"get_fixed_timezone",
|
| 16 |
+
"get_default_timezone",
|
| 17 |
+
"get_default_timezone_name",
|
| 18 |
+
"get_current_timezone",
|
| 19 |
+
"get_current_timezone_name",
|
| 20 |
+
"activate",
|
| 21 |
+
"deactivate",
|
| 22 |
+
"override",
|
| 23 |
+
"localtime",
|
| 24 |
+
"localdate",
|
| 25 |
+
"now",
|
| 26 |
+
"is_aware",
|
| 27 |
+
"is_naive",
|
| 28 |
+
"make_aware",
|
| 29 |
+
"make_naive",
|
| 30 |
+
]
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def get_fixed_timezone(offset):
|
| 34 |
+
"""Return a tzinfo instance with a fixed offset from UTC."""
|
| 35 |
+
if isinstance(offset, timedelta):
|
| 36 |
+
offset = offset.total_seconds() // 60
|
| 37 |
+
sign = "-" if offset < 0 else "+"
|
| 38 |
+
hhmm = "%02d%02d" % divmod(abs(offset), 60)
|
| 39 |
+
name = sign + hhmm
|
| 40 |
+
return timezone(timedelta(minutes=offset), name)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
# In order to avoid accessing settings at compile time,
|
| 44 |
+
# wrap the logic in a function and cache the result.
|
| 45 |
+
@functools.lru_cache
|
| 46 |
+
def get_default_timezone():
|
| 47 |
+
"""
|
| 48 |
+
Return the default time zone as a tzinfo instance.
|
| 49 |
+
|
| 50 |
+
This is the time zone defined by settings.TIME_ZONE.
|
| 51 |
+
"""
|
| 52 |
+
return zoneinfo.ZoneInfo(settings.TIME_ZONE)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
# This function exists for consistency with get_current_timezone_name
|
| 56 |
+
def get_default_timezone_name():
|
| 57 |
+
"""Return the name of the default time zone."""
|
| 58 |
+
return _get_timezone_name(get_default_timezone())
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
_active = Local()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def get_current_timezone():
|
| 65 |
+
"""Return the currently active time zone as a tzinfo instance."""
|
| 66 |
+
return getattr(_active, "value", get_default_timezone())
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def get_current_timezone_name():
|
| 70 |
+
"""Return the name of the currently active time zone."""
|
| 71 |
+
return _get_timezone_name(get_current_timezone())
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _get_timezone_name(timezone):
|
| 75 |
+
"""
|
| 76 |
+
Return the offset for fixed offset timezones, or the name of timezone if
|
| 77 |
+
not set.
|
| 78 |
+
"""
|
| 79 |
+
return timezone.tzname(None) or str(timezone)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
# Timezone selection functions.
|
| 83 |
+
|
| 84 |
+
# These functions don't change os.environ['TZ'] and call time.tzset()
|
| 85 |
+
# because it isn't thread safe.
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def activate(timezone):
|
| 89 |
+
"""
|
| 90 |
+
Set the time zone for the current thread.
|
| 91 |
+
|
| 92 |
+
The ``timezone`` argument must be an instance of a tzinfo subclass or a
|
| 93 |
+
time zone name.
|
| 94 |
+
"""
|
| 95 |
+
if isinstance(timezone, tzinfo):
|
| 96 |
+
_active.value = timezone
|
| 97 |
+
elif isinstance(timezone, str):
|
| 98 |
+
_active.value = zoneinfo.ZoneInfo(timezone)
|
| 99 |
+
else:
|
| 100 |
+
raise ValueError("Invalid timezone: %r" % timezone)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def deactivate():
|
| 104 |
+
"""
|
| 105 |
+
Unset the time zone for the current thread.
|
| 106 |
+
|
| 107 |
+
Django will then use the time zone defined by settings.TIME_ZONE.
|
| 108 |
+
"""
|
| 109 |
+
if hasattr(_active, "value"):
|
| 110 |
+
del _active.value
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class override(ContextDecorator):
|
| 114 |
+
"""
|
| 115 |
+
Temporarily set the time zone for the current thread.
|
| 116 |
+
|
| 117 |
+
This is a context manager that uses django.utils.timezone.activate()
|
| 118 |
+
to set the timezone on entry and restores the previously active timezone
|
| 119 |
+
on exit.
|
| 120 |
+
|
| 121 |
+
The ``timezone`` argument must be an instance of a ``tzinfo`` subclass, a
|
| 122 |
+
time zone name, or ``None``. If it is ``None``, Django enables the default
|
| 123 |
+
time zone.
|
| 124 |
+
"""
|
| 125 |
+
|
| 126 |
+
def __init__(self, timezone):
|
| 127 |
+
self.timezone = timezone
|
| 128 |
+
|
| 129 |
+
def __enter__(self):
|
| 130 |
+
self.old_timezone = getattr(_active, "value", None)
|
| 131 |
+
if self.timezone is None:
|
| 132 |
+
deactivate()
|
| 133 |
+
else:
|
| 134 |
+
activate(self.timezone)
|
| 135 |
+
|
| 136 |
+
def __exit__(self, exc_type, exc_value, traceback):
|
| 137 |
+
if self.old_timezone is None:
|
| 138 |
+
deactivate()
|
| 139 |
+
else:
|
| 140 |
+
_active.value = self.old_timezone
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
# Templates
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def template_localtime(value, use_tz=None):
|
| 147 |
+
"""
|
| 148 |
+
Check if value is a datetime and converts it to local time if necessary.
|
| 149 |
+
|
| 150 |
+
If use_tz is provided and is not None, that will force the value to
|
| 151 |
+
be converted (or not), overriding the value of settings.USE_TZ.
|
| 152 |
+
|
| 153 |
+
This function is designed for use by the template engine.
|
| 154 |
+
"""
|
| 155 |
+
should_convert = (
|
| 156 |
+
isinstance(value, datetime)
|
| 157 |
+
and (settings.USE_TZ if use_tz is None else use_tz)
|
| 158 |
+
and not is_naive(value)
|
| 159 |
+
and getattr(value, "convert_to_local_time", True)
|
| 160 |
+
)
|
| 161 |
+
return localtime(value) if should_convert else value
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
# Utilities
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def localtime(value=None, timezone=None):
|
| 168 |
+
"""
|
| 169 |
+
Convert an aware datetime.datetime to local time.
|
| 170 |
+
|
| 171 |
+
Only aware datetimes are allowed. When value is omitted, it defaults to
|
| 172 |
+
now().
|
| 173 |
+
|
| 174 |
+
Local time is defined by the current time zone, unless another time zone
|
| 175 |
+
is specified.
|
| 176 |
+
"""
|
| 177 |
+
if value is None:
|
| 178 |
+
value = now()
|
| 179 |
+
if timezone is None:
|
| 180 |
+
timezone = get_current_timezone()
|
| 181 |
+
# Emulate the behavior of astimezone() on Python < 3.6.
|
| 182 |
+
if is_naive(value):
|
| 183 |
+
raise ValueError("localtime() cannot be applied to a naive datetime")
|
| 184 |
+
return value.astimezone(timezone)
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
def localdate(value=None, timezone=None):
|
| 188 |
+
"""
|
| 189 |
+
Convert an aware datetime to local time and return the value's date.
|
| 190 |
+
|
| 191 |
+
Only aware datetimes are allowed. When value is omitted, it defaults to
|
| 192 |
+
now().
|
| 193 |
+
|
| 194 |
+
Local time is defined by the current time zone, unless another time zone is
|
| 195 |
+
specified.
|
| 196 |
+
"""
|
| 197 |
+
return localtime(value, timezone).date()
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def now():
|
| 201 |
+
"""
|
| 202 |
+
Return an aware or naive datetime.datetime, depending on settings.USE_TZ.
|
| 203 |
+
"""
|
| 204 |
+
return datetime.now(tz=timezone.utc if settings.USE_TZ else None)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
# By design, these four functions don't perform any checks on their arguments.
|
| 208 |
+
# The caller should ensure that they don't receive an invalid value like None.
|
| 209 |
+
|
| 210 |
+
|
| 211 |
+
def is_aware(value):
|
| 212 |
+
"""
|
| 213 |
+
Determine if a given datetime.datetime is aware.
|
| 214 |
+
|
| 215 |
+
The concept is defined in Python's docs:
|
| 216 |
+
https://docs.python.org/library/datetime.html#datetime.tzinfo
|
| 217 |
+
|
| 218 |
+
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
|
| 219 |
+
value.utcoffset() implements the appropriate logic.
|
| 220 |
+
"""
|
| 221 |
+
return value.utcoffset() is not None
|
| 222 |
+
|
| 223 |
+
|
| 224 |
+
def is_naive(value):
|
| 225 |
+
"""
|
| 226 |
+
Determine if a given datetime.datetime is naive.
|
| 227 |
+
|
| 228 |
+
The concept is defined in Python's docs:
|
| 229 |
+
https://docs.python.org/library/datetime.html#datetime.tzinfo
|
| 230 |
+
|
| 231 |
+
Assuming value.tzinfo is either None or a proper datetime.tzinfo,
|
| 232 |
+
value.utcoffset() implements the appropriate logic.
|
| 233 |
+
"""
|
| 234 |
+
return value.utcoffset() is None
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def make_aware(value, timezone=None):
|
| 238 |
+
"""Make a naive datetime.datetime in a given time zone aware."""
|
| 239 |
+
if timezone is None:
|
| 240 |
+
timezone = get_current_timezone()
|
| 241 |
+
# Check that we won't overwrite the timezone of an aware datetime.
|
| 242 |
+
if is_aware(value):
|
| 243 |
+
raise ValueError("make_aware expects a naive datetime, got %s" % value)
|
| 244 |
+
# This may be wrong around DST changes!
|
| 245 |
+
return value.replace(tzinfo=timezone)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def make_naive(value, timezone=None):
|
| 249 |
+
"""Make an aware datetime.datetime naive in a given time zone."""
|
| 250 |
+
if timezone is None:
|
| 251 |
+
timezone = get_current_timezone()
|
| 252 |
+
# Emulate the behavior of astimezone() on Python < 3.6.
|
| 253 |
+
if is_naive(value):
|
| 254 |
+
raise ValueError("make_naive() cannot be applied to a naive datetime")
|
| 255 |
+
return value.astimezone(timezone).replace(tzinfo=None)
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _datetime_ambiguous_or_imaginary(dt, tz):
|
| 259 |
+
return tz.utcoffset(dt.replace(fold=not dt.fold)) != tz.utcoffset(dt)
|
testbed/django__django/django/utils/version.py
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import datetime
|
| 2 |
+
import functools
|
| 3 |
+
import os
|
| 4 |
+
import subprocess
|
| 5 |
+
import sys
|
| 6 |
+
|
| 7 |
+
from django.utils.regex_helper import _lazy_re_compile
|
| 8 |
+
|
| 9 |
+
# Private, stable API for detecting the Python version. PYXY means "Python X.Y
|
| 10 |
+
# or later". So that third-party apps can use these values, each constant
|
| 11 |
+
# should remain as long as the oldest supported Django version supports that
|
| 12 |
+
# Python version.
|
| 13 |
+
PY36 = sys.version_info >= (3, 6)
|
| 14 |
+
PY37 = sys.version_info >= (3, 7)
|
| 15 |
+
PY38 = sys.version_info >= (3, 8)
|
| 16 |
+
PY39 = sys.version_info >= (3, 9)
|
| 17 |
+
PY310 = sys.version_info >= (3, 10)
|
| 18 |
+
PY311 = sys.version_info >= (3, 11)
|
| 19 |
+
PY312 = sys.version_info >= (3, 12)
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def get_version(version=None):
|
| 23 |
+
"""Return a PEP 440-compliant version number from VERSION."""
|
| 24 |
+
version = get_complete_version(version)
|
| 25 |
+
|
| 26 |
+
# Now build the two parts of the version number:
|
| 27 |
+
# main = X.Y[.Z]
|
| 28 |
+
# sub = .devN - for pre-alpha releases
|
| 29 |
+
# | {a|b|rc}N - for alpha, beta, and rc releases
|
| 30 |
+
|
| 31 |
+
main = get_main_version(version)
|
| 32 |
+
|
| 33 |
+
sub = ""
|
| 34 |
+
if version[3] == "alpha" and version[4] == 0:
|
| 35 |
+
git_changeset = get_git_changeset()
|
| 36 |
+
if git_changeset:
|
| 37 |
+
sub = ".dev%s" % git_changeset
|
| 38 |
+
|
| 39 |
+
elif version[3] != "final":
|
| 40 |
+
mapping = {"alpha": "a", "beta": "b", "rc": "rc"}
|
| 41 |
+
sub = mapping[version[3]] + str(version[4])
|
| 42 |
+
|
| 43 |
+
return main + sub
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def get_main_version(version=None):
|
| 47 |
+
"""Return main version (X.Y[.Z]) from VERSION."""
|
| 48 |
+
version = get_complete_version(version)
|
| 49 |
+
parts = 2 if version[2] == 0 else 3
|
| 50 |
+
return ".".join(str(x) for x in version[:parts])
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def get_complete_version(version=None):
|
| 54 |
+
"""
|
| 55 |
+
Return a tuple of the django version. If version argument is non-empty,
|
| 56 |
+
check for correctness of the tuple provided.
|
| 57 |
+
"""
|
| 58 |
+
if version is None:
|
| 59 |
+
from django import VERSION as version
|
| 60 |
+
else:
|
| 61 |
+
assert len(version) == 5
|
| 62 |
+
assert version[3] in ("alpha", "beta", "rc", "final")
|
| 63 |
+
|
| 64 |
+
return version
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_docs_version(version=None):
|
| 68 |
+
version = get_complete_version(version)
|
| 69 |
+
if version[3] != "final":
|
| 70 |
+
return "dev"
|
| 71 |
+
else:
|
| 72 |
+
return "%d.%d" % version[:2]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
@functools.lru_cache
|
| 76 |
+
def get_git_changeset():
|
| 77 |
+
"""Return a numeric identifier of the latest git changeset.
|
| 78 |
+
|
| 79 |
+
The result is the UTC timestamp of the changeset in YYYYMMDDHHMMSS format.
|
| 80 |
+
This value isn't guaranteed to be unique, but collisions are very unlikely,
|
| 81 |
+
so it's sufficient for generating the development version numbers.
|
| 82 |
+
"""
|
| 83 |
+
# Repository may not be found if __file__ is undefined, e.g. in a frozen
|
| 84 |
+
# module.
|
| 85 |
+
if "__file__" not in globals():
|
| 86 |
+
return None
|
| 87 |
+
repo_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
| 88 |
+
git_log = subprocess.run(
|
| 89 |
+
"git log --pretty=format:%ct --quiet -1 HEAD",
|
| 90 |
+
capture_output=True,
|
| 91 |
+
shell=True,
|
| 92 |
+
cwd=repo_dir,
|
| 93 |
+
text=True,
|
| 94 |
+
)
|
| 95 |
+
timestamp = git_log.stdout
|
| 96 |
+
tz = datetime.timezone.utc
|
| 97 |
+
try:
|
| 98 |
+
timestamp = datetime.datetime.fromtimestamp(int(timestamp), tz=tz)
|
| 99 |
+
except ValueError:
|
| 100 |
+
return None
|
| 101 |
+
return timestamp.strftime("%Y%m%d%H%M%S")
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
version_component_re = _lazy_re_compile(r"(\d+|[a-z]+|\.)")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
def get_version_tuple(version):
|
| 108 |
+
"""
|
| 109 |
+
Return a tuple of version numbers (e.g. (1, 2, 3)) from the version
|
| 110 |
+
string (e.g. '1.2.3').
|
| 111 |
+
"""
|
| 112 |
+
version_numbers = []
|
| 113 |
+
for item in version_component_re.split(version):
|
| 114 |
+
if item and item != ".":
|
| 115 |
+
try:
|
| 116 |
+
component = int(item)
|
| 117 |
+
except ValueError:
|
| 118 |
+
break
|
| 119 |
+
else:
|
| 120 |
+
version_numbers.append(component)
|
| 121 |
+
return tuple(version_numbers)
|
testbed/django__django/django/views/decorators/__init__.py
ADDED
|
File without changes
|
testbed/django__django/django/views/decorators/cache.py
ADDED
|
@@ -0,0 +1,84 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import wraps
|
| 2 |
+
|
| 3 |
+
from asgiref.sync import iscoroutinefunction
|
| 4 |
+
|
| 5 |
+
from django.middleware.cache import CacheMiddleware
|
| 6 |
+
from django.utils.cache import add_never_cache_headers, patch_cache_control
|
| 7 |
+
from django.utils.decorators import decorator_from_middleware_with_args
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
def cache_page(timeout, *, cache=None, key_prefix=None):
|
| 11 |
+
"""
|
| 12 |
+
Decorator for views that tries getting the page from the cache and
|
| 13 |
+
populates the cache if the page isn't in the cache yet.
|
| 14 |
+
|
| 15 |
+
The cache is keyed by the URL and some data from the headers.
|
| 16 |
+
Additionally there is the key prefix that is used to distinguish different
|
| 17 |
+
cache areas in a multi-site setup. You could use the
|
| 18 |
+
get_current_site().domain, for example, as that is unique across a Django
|
| 19 |
+
project.
|
| 20 |
+
|
| 21 |
+
Additionally, all headers from the response's Vary header will be taken
|
| 22 |
+
into account on caching -- just like the middleware does.
|
| 23 |
+
"""
|
| 24 |
+
return decorator_from_middleware_with_args(CacheMiddleware)(
|
| 25 |
+
page_timeout=timeout,
|
| 26 |
+
cache_alias=cache,
|
| 27 |
+
key_prefix=key_prefix,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
def _check_request(request, decorator_name):
|
| 32 |
+
# Ensure argument looks like a request.
|
| 33 |
+
if not hasattr(request, "META"):
|
| 34 |
+
raise TypeError(
|
| 35 |
+
f"{decorator_name} didn't receive an HttpRequest. If you are "
|
| 36 |
+
"decorating a classmethod, be sure to use @method_decorator."
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def cache_control(**kwargs):
|
| 41 |
+
def _cache_controller(viewfunc):
|
| 42 |
+
if iscoroutinefunction(viewfunc):
|
| 43 |
+
|
| 44 |
+
async def _view_wrapper(request, *args, **kw):
|
| 45 |
+
_check_request(request, "cache_control")
|
| 46 |
+
response = await viewfunc(request, *args, **kw)
|
| 47 |
+
patch_cache_control(response, **kwargs)
|
| 48 |
+
return response
|
| 49 |
+
|
| 50 |
+
else:
|
| 51 |
+
|
| 52 |
+
def _view_wrapper(request, *args, **kw):
|
| 53 |
+
_check_request(request, "cache_control")
|
| 54 |
+
response = viewfunc(request, *args, **kw)
|
| 55 |
+
patch_cache_control(response, **kwargs)
|
| 56 |
+
return response
|
| 57 |
+
|
| 58 |
+
return wraps(viewfunc)(_view_wrapper)
|
| 59 |
+
|
| 60 |
+
return _cache_controller
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def never_cache(view_func):
|
| 64 |
+
"""
|
| 65 |
+
Decorator that adds headers to a response so that it will never be cached.
|
| 66 |
+
"""
|
| 67 |
+
|
| 68 |
+
if iscoroutinefunction(view_func):
|
| 69 |
+
|
| 70 |
+
async def _view_wrapper(request, *args, **kwargs):
|
| 71 |
+
_check_request(request, "never_cache")
|
| 72 |
+
response = await view_func(request, *args, **kwargs)
|
| 73 |
+
add_never_cache_headers(response)
|
| 74 |
+
return response
|
| 75 |
+
|
| 76 |
+
else:
|
| 77 |
+
|
| 78 |
+
def _view_wrapper(request, *args, **kwargs):
|
| 79 |
+
_check_request(request, "never_cache")
|
| 80 |
+
response = view_func(request, *args, **kwargs)
|
| 81 |
+
add_never_cache_headers(response)
|
| 82 |
+
return response
|
| 83 |
+
|
| 84 |
+
return wraps(view_func)(_view_wrapper)
|
testbed/django__django/django/views/decorators/common.py
ADDED
|
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import wraps
|
| 2 |
+
|
| 3 |
+
from asgiref.sync import iscoroutinefunction
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
def no_append_slash(view_func):
|
| 7 |
+
"""
|
| 8 |
+
Mark a view function as excluded from CommonMiddleware's APPEND_SLASH
|
| 9 |
+
redirection.
|
| 10 |
+
"""
|
| 11 |
+
|
| 12 |
+
# view_func.should_append_slash = False would also work, but decorators are
|
| 13 |
+
# nicer if they don't have side effects, so return a new function.
|
| 14 |
+
|
| 15 |
+
if iscoroutinefunction(view_func):
|
| 16 |
+
|
| 17 |
+
async def _view_wrapper(request, *args, **kwargs):
|
| 18 |
+
return await view_func(request, *args, **kwargs)
|
| 19 |
+
|
| 20 |
+
else:
|
| 21 |
+
|
| 22 |
+
def _view_wrapper(request, *args, **kwargs):
|
| 23 |
+
return view_func(request, *args, **kwargs)
|
| 24 |
+
|
| 25 |
+
_view_wrapper.should_append_slash = False
|
| 26 |
+
|
| 27 |
+
return wraps(view_func)(_view_wrapper)
|
testbed/django__django/django/views/decorators/csrf.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from functools import wraps
|
| 2 |
+
|
| 3 |
+
from asgiref.sync import iscoroutinefunction
|
| 4 |
+
|
| 5 |
+
from django.middleware.csrf import CsrfViewMiddleware, get_token
|
| 6 |
+
from django.utils.decorators import decorator_from_middleware
|
| 7 |
+
|
| 8 |
+
csrf_protect = decorator_from_middleware(CsrfViewMiddleware)
|
| 9 |
+
csrf_protect.__name__ = "csrf_protect"
|
| 10 |
+
csrf_protect.__doc__ = """
|
| 11 |
+
This decorator adds CSRF protection in exactly the same way as
|
| 12 |
+
CsrfViewMiddleware, but it can be used on a per view basis. Using both, or
|
| 13 |
+
using the decorator multiple times, is harmless and efficient.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
class _EnsureCsrfToken(CsrfViewMiddleware):
|
| 18 |
+
# Behave like CsrfViewMiddleware but don't reject requests or log warnings.
|
| 19 |
+
def _reject(self, request, reason):
|
| 20 |
+
return None
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
requires_csrf_token = decorator_from_middleware(_EnsureCsrfToken)
|
| 24 |
+
requires_csrf_token.__name__ = "requires_csrf_token"
|
| 25 |
+
requires_csrf_token.__doc__ = """
|
| 26 |
+
Use this decorator on views that need a correct csrf_token available to
|
| 27 |
+
RequestContext, but without the CSRF protection that csrf_protect
|
| 28 |
+
enforces.
|
| 29 |
+
"""
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class _EnsureCsrfCookie(CsrfViewMiddleware):
|
| 33 |
+
def _reject(self, request, reason):
|
| 34 |
+
return None
|
| 35 |
+
|
| 36 |
+
def process_view(self, request, callback, callback_args, callback_kwargs):
|
| 37 |
+
retval = super().process_view(request, callback, callback_args, callback_kwargs)
|
| 38 |
+
# Force process_response to send the cookie
|
| 39 |
+
get_token(request)
|
| 40 |
+
return retval
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
ensure_csrf_cookie = decorator_from_middleware(_EnsureCsrfCookie)
|
| 44 |
+
ensure_csrf_cookie.__name__ = "ensure_csrf_cookie"
|
| 45 |
+
ensure_csrf_cookie.__doc__ = """
|
| 46 |
+
Use this decorator to ensure that a view sets a CSRF cookie, whether or not it
|
| 47 |
+
uses the csrf_token template tag, or the CsrfViewMiddleware is used.
|
| 48 |
+
"""
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def csrf_exempt(view_func):
|
| 52 |
+
"""Mark a view function as being exempt from the CSRF view protection."""
|
| 53 |
+
|
| 54 |
+
# view_func.csrf_exempt = True would also work, but decorators are nicer
|
| 55 |
+
# if they don't have side effects, so return a new function.
|
| 56 |
+
|
| 57 |
+
if iscoroutinefunction(view_func):
|
| 58 |
+
|
| 59 |
+
async def _view_wrapper(request, *args, **kwargs):
|
| 60 |
+
return await view_func(request, *args, **kwargs)
|
| 61 |
+
|
| 62 |
+
else:
|
| 63 |
+
|
| 64 |
+
def _view_wrapper(request, *args, **kwargs):
|
| 65 |
+
return view_func(request, *args, **kwargs)
|
| 66 |
+
|
| 67 |
+
_view_wrapper.csrf_exempt = True
|
| 68 |
+
|
| 69 |
+
return wraps(view_func)(_view_wrapper)
|
testbed/django__django/django/views/decorators/gzip.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.middleware.gzip import GZipMiddleware
|
| 2 |
+
from django.utils.decorators import decorator_from_middleware
|
| 3 |
+
|
| 4 |
+
gzip_page = decorator_from_middleware(GZipMiddleware)
|
| 5 |
+
gzip_page.__doc__ = "Decorator for views that gzips pages if the client supports it."
|
testbed/django__django/django/views/defaults.py
ADDED
|
@@ -0,0 +1,149 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from urllib.parse import quote
|
| 2 |
+
|
| 3 |
+
from django.http import (
|
| 4 |
+
HttpResponseBadRequest,
|
| 5 |
+
HttpResponseForbidden,
|
| 6 |
+
HttpResponseNotFound,
|
| 7 |
+
HttpResponseServerError,
|
| 8 |
+
)
|
| 9 |
+
from django.template import Context, Engine, TemplateDoesNotExist, loader
|
| 10 |
+
from django.views.decorators.csrf import requires_csrf_token
|
| 11 |
+
|
| 12 |
+
ERROR_404_TEMPLATE_NAME = "404.html"
|
| 13 |
+
ERROR_403_TEMPLATE_NAME = "403.html"
|
| 14 |
+
ERROR_400_TEMPLATE_NAME = "400.html"
|
| 15 |
+
ERROR_500_TEMPLATE_NAME = "500.html"
|
| 16 |
+
ERROR_PAGE_TEMPLATE = """
|
| 17 |
+
<!doctype html>
|
| 18 |
+
<html lang="en">
|
| 19 |
+
<head>
|
| 20 |
+
<title>%(title)s</title>
|
| 21 |
+
</head>
|
| 22 |
+
<body>
|
| 23 |
+
<h1>%(title)s</h1><p>%(details)s</p>
|
| 24 |
+
</body>
|
| 25 |
+
</html>
|
| 26 |
+
"""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
# These views can be called when CsrfViewMiddleware.process_view() not run,
|
| 30 |
+
# therefore need @requires_csrf_token in case the template needs
|
| 31 |
+
# {% csrf_token %}.
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
@requires_csrf_token
|
| 35 |
+
def page_not_found(request, exception, template_name=ERROR_404_TEMPLATE_NAME):
|
| 36 |
+
"""
|
| 37 |
+
Default 404 handler.
|
| 38 |
+
|
| 39 |
+
Templates: :template:`404.html`
|
| 40 |
+
Context:
|
| 41 |
+
request_path
|
| 42 |
+
The path of the requested URL (e.g., '/app/pages/bad_page/'). It's
|
| 43 |
+
quoted to prevent a content injection attack.
|
| 44 |
+
exception
|
| 45 |
+
The message from the exception which triggered the 404 (if one was
|
| 46 |
+
supplied), or the exception class name
|
| 47 |
+
"""
|
| 48 |
+
exception_repr = exception.__class__.__name__
|
| 49 |
+
# Try to get an "interesting" exception message, if any (and not the ugly
|
| 50 |
+
# Resolver404 dictionary)
|
| 51 |
+
try:
|
| 52 |
+
message = exception.args[0]
|
| 53 |
+
except (AttributeError, IndexError):
|
| 54 |
+
pass
|
| 55 |
+
else:
|
| 56 |
+
if isinstance(message, str):
|
| 57 |
+
exception_repr = message
|
| 58 |
+
context = {
|
| 59 |
+
"request_path": quote(request.path),
|
| 60 |
+
"exception": exception_repr,
|
| 61 |
+
}
|
| 62 |
+
try:
|
| 63 |
+
template = loader.get_template(template_name)
|
| 64 |
+
body = template.render(context, request)
|
| 65 |
+
except TemplateDoesNotExist:
|
| 66 |
+
if template_name != ERROR_404_TEMPLATE_NAME:
|
| 67 |
+
# Reraise if it's a missing custom template.
|
| 68 |
+
raise
|
| 69 |
+
# Render template (even though there are no substitutions) to allow
|
| 70 |
+
# inspecting the context in tests.
|
| 71 |
+
template = Engine().from_string(
|
| 72 |
+
ERROR_PAGE_TEMPLATE
|
| 73 |
+
% {
|
| 74 |
+
"title": "Not Found",
|
| 75 |
+
"details": "The requested resource was not found on this server.",
|
| 76 |
+
},
|
| 77 |
+
)
|
| 78 |
+
body = template.render(Context(context))
|
| 79 |
+
return HttpResponseNotFound(body)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
@requires_csrf_token
|
| 83 |
+
def server_error(request, template_name=ERROR_500_TEMPLATE_NAME):
|
| 84 |
+
"""
|
| 85 |
+
500 error handler.
|
| 86 |
+
|
| 87 |
+
Templates: :template:`500.html`
|
| 88 |
+
Context: None
|
| 89 |
+
"""
|
| 90 |
+
try:
|
| 91 |
+
template = loader.get_template(template_name)
|
| 92 |
+
except TemplateDoesNotExist:
|
| 93 |
+
if template_name != ERROR_500_TEMPLATE_NAME:
|
| 94 |
+
# Reraise if it's a missing custom template.
|
| 95 |
+
raise
|
| 96 |
+
return HttpResponseServerError(
|
| 97 |
+
ERROR_PAGE_TEMPLATE % {"title": "Server Error (500)", "details": ""},
|
| 98 |
+
)
|
| 99 |
+
return HttpResponseServerError(template.render())
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
@requires_csrf_token
|
| 103 |
+
def bad_request(request, exception, template_name=ERROR_400_TEMPLATE_NAME):
|
| 104 |
+
"""
|
| 105 |
+
400 error handler.
|
| 106 |
+
|
| 107 |
+
Templates: :template:`400.html`
|
| 108 |
+
Context: None
|
| 109 |
+
"""
|
| 110 |
+
try:
|
| 111 |
+
template = loader.get_template(template_name)
|
| 112 |
+
except TemplateDoesNotExist:
|
| 113 |
+
if template_name != ERROR_400_TEMPLATE_NAME:
|
| 114 |
+
# Reraise if it's a missing custom template.
|
| 115 |
+
raise
|
| 116 |
+
return HttpResponseBadRequest(
|
| 117 |
+
ERROR_PAGE_TEMPLATE % {"title": "Bad Request (400)", "details": ""},
|
| 118 |
+
)
|
| 119 |
+
# No exception content is passed to the template, to not disclose any
|
| 120 |
+
# sensitive information.
|
| 121 |
+
return HttpResponseBadRequest(template.render())
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
@requires_csrf_token
|
| 125 |
+
def permission_denied(request, exception, template_name=ERROR_403_TEMPLATE_NAME):
|
| 126 |
+
"""
|
| 127 |
+
Permission denied (403) handler.
|
| 128 |
+
|
| 129 |
+
Templates: :template:`403.html`
|
| 130 |
+
Context:
|
| 131 |
+
exception
|
| 132 |
+
The message from the exception which triggered the 403 (if one was
|
| 133 |
+
supplied).
|
| 134 |
+
|
| 135 |
+
If the template does not exist, an Http403 response containing the text
|
| 136 |
+
"403 Forbidden" (as per RFC 9110 Section 15.5.4) will be returned.
|
| 137 |
+
"""
|
| 138 |
+
try:
|
| 139 |
+
template = loader.get_template(template_name)
|
| 140 |
+
except TemplateDoesNotExist:
|
| 141 |
+
if template_name != ERROR_403_TEMPLATE_NAME:
|
| 142 |
+
# Reraise if it's a missing custom template.
|
| 143 |
+
raise
|
| 144 |
+
return HttpResponseForbidden(
|
| 145 |
+
ERROR_PAGE_TEMPLATE % {"title": "403 Forbidden", "details": ""},
|
| 146 |
+
)
|
| 147 |
+
return HttpResponseForbidden(
|
| 148 |
+
template.render(request=request, context={"exception": str(exception)})
|
| 149 |
+
)
|
testbed/django__django/django/views/generic/base.py
ADDED
|
@@ -0,0 +1,285 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import logging
|
| 2 |
+
|
| 3 |
+
from asgiref.sync import iscoroutinefunction, markcoroutinefunction
|
| 4 |
+
|
| 5 |
+
from django.core.exceptions import ImproperlyConfigured
|
| 6 |
+
from django.http import (
|
| 7 |
+
HttpResponse,
|
| 8 |
+
HttpResponseGone,
|
| 9 |
+
HttpResponseNotAllowed,
|
| 10 |
+
HttpResponsePermanentRedirect,
|
| 11 |
+
HttpResponseRedirect,
|
| 12 |
+
)
|
| 13 |
+
from django.template.response import TemplateResponse
|
| 14 |
+
from django.urls import reverse
|
| 15 |
+
from django.utils.decorators import classonlymethod
|
| 16 |
+
from django.utils.functional import classproperty
|
| 17 |
+
|
| 18 |
+
logger = logging.getLogger("django.request")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class ContextMixin:
|
| 22 |
+
"""
|
| 23 |
+
A default context mixin that passes the keyword arguments received by
|
| 24 |
+
get_context_data() as the template context.
|
| 25 |
+
"""
|
| 26 |
+
|
| 27 |
+
extra_context = None
|
| 28 |
+
|
| 29 |
+
def get_context_data(self, **kwargs):
|
| 30 |
+
kwargs.setdefault("view", self)
|
| 31 |
+
if self.extra_context is not None:
|
| 32 |
+
kwargs.update(self.extra_context)
|
| 33 |
+
return kwargs
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class View:
|
| 37 |
+
"""
|
| 38 |
+
Intentionally simple parent class for all views. Only implements
|
| 39 |
+
dispatch-by-method and simple sanity checking.
|
| 40 |
+
"""
|
| 41 |
+
|
| 42 |
+
http_method_names = [
|
| 43 |
+
"get",
|
| 44 |
+
"post",
|
| 45 |
+
"put",
|
| 46 |
+
"patch",
|
| 47 |
+
"delete",
|
| 48 |
+
"head",
|
| 49 |
+
"options",
|
| 50 |
+
"trace",
|
| 51 |
+
]
|
| 52 |
+
|
| 53 |
+
def __init__(self, **kwargs):
|
| 54 |
+
"""
|
| 55 |
+
Constructor. Called in the URLconf; can contain helpful extra
|
| 56 |
+
keyword arguments, and other things.
|
| 57 |
+
"""
|
| 58 |
+
# Go through keyword arguments, and either save their values to our
|
| 59 |
+
# instance, or raise an error.
|
| 60 |
+
for key, value in kwargs.items():
|
| 61 |
+
setattr(self, key, value)
|
| 62 |
+
|
| 63 |
+
@classproperty
|
| 64 |
+
def view_is_async(cls):
|
| 65 |
+
handlers = [
|
| 66 |
+
getattr(cls, method)
|
| 67 |
+
for method in cls.http_method_names
|
| 68 |
+
if (method != "options" and hasattr(cls, method))
|
| 69 |
+
]
|
| 70 |
+
if not handlers:
|
| 71 |
+
return False
|
| 72 |
+
is_async = iscoroutinefunction(handlers[0])
|
| 73 |
+
if not all(iscoroutinefunction(h) == is_async for h in handlers[1:]):
|
| 74 |
+
raise ImproperlyConfigured(
|
| 75 |
+
f"{cls.__qualname__} HTTP handlers must either be all sync or all "
|
| 76 |
+
"async."
|
| 77 |
+
)
|
| 78 |
+
return is_async
|
| 79 |
+
|
| 80 |
+
@classonlymethod
|
| 81 |
+
def as_view(cls, **initkwargs):
|
| 82 |
+
"""Main entry point for a request-response process."""
|
| 83 |
+
for key in initkwargs:
|
| 84 |
+
if key in cls.http_method_names:
|
| 85 |
+
raise TypeError(
|
| 86 |
+
"The method name %s is not accepted as a keyword argument "
|
| 87 |
+
"to %s()." % (key, cls.__name__)
|
| 88 |
+
)
|
| 89 |
+
if not hasattr(cls, key):
|
| 90 |
+
raise TypeError(
|
| 91 |
+
"%s() received an invalid keyword %r. as_view "
|
| 92 |
+
"only accepts arguments that are already "
|
| 93 |
+
"attributes of the class." % (cls.__name__, key)
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
def view(request, *args, **kwargs):
|
| 97 |
+
self = cls(**initkwargs)
|
| 98 |
+
self.setup(request, *args, **kwargs)
|
| 99 |
+
if not hasattr(self, "request"):
|
| 100 |
+
raise AttributeError(
|
| 101 |
+
"%s instance has no 'request' attribute. Did you override "
|
| 102 |
+
"setup() and forget to call super()?" % cls.__name__
|
| 103 |
+
)
|
| 104 |
+
return self.dispatch(request, *args, **kwargs)
|
| 105 |
+
|
| 106 |
+
view.view_class = cls
|
| 107 |
+
view.view_initkwargs = initkwargs
|
| 108 |
+
|
| 109 |
+
# __name__ and __qualname__ are intentionally left unchanged as
|
| 110 |
+
# view_class should be used to robustly determine the name of the view
|
| 111 |
+
# instead.
|
| 112 |
+
view.__doc__ = cls.__doc__
|
| 113 |
+
view.__module__ = cls.__module__
|
| 114 |
+
view.__annotations__ = cls.dispatch.__annotations__
|
| 115 |
+
# Copy possible attributes set by decorators, e.g. @csrf_exempt, from
|
| 116 |
+
# the dispatch method.
|
| 117 |
+
view.__dict__.update(cls.dispatch.__dict__)
|
| 118 |
+
|
| 119 |
+
# Mark the callback if the view class is async.
|
| 120 |
+
if cls.view_is_async:
|
| 121 |
+
markcoroutinefunction(view)
|
| 122 |
+
|
| 123 |
+
return view
|
| 124 |
+
|
| 125 |
+
def setup(self, request, *args, **kwargs):
|
| 126 |
+
"""Initialize attributes shared by all view methods."""
|
| 127 |
+
if hasattr(self, "get") and not hasattr(self, "head"):
|
| 128 |
+
self.head = self.get
|
| 129 |
+
self.request = request
|
| 130 |
+
self.args = args
|
| 131 |
+
self.kwargs = kwargs
|
| 132 |
+
|
| 133 |
+
def dispatch(self, request, *args, **kwargs):
|
| 134 |
+
# Try to dispatch to the right method; if a method doesn't exist,
|
| 135 |
+
# defer to the error handler. Also defer to the error handler if the
|
| 136 |
+
# request method isn't on the approved list.
|
| 137 |
+
if request.method.lower() in self.http_method_names:
|
| 138 |
+
handler = getattr(
|
| 139 |
+
self, request.method.lower(), self.http_method_not_allowed
|
| 140 |
+
)
|
| 141 |
+
else:
|
| 142 |
+
handler = self.http_method_not_allowed
|
| 143 |
+
return handler(request, *args, **kwargs)
|
| 144 |
+
|
| 145 |
+
def http_method_not_allowed(self, request, *args, **kwargs):
|
| 146 |
+
logger.warning(
|
| 147 |
+
"Method Not Allowed (%s): %s",
|
| 148 |
+
request.method,
|
| 149 |
+
request.path,
|
| 150 |
+
extra={"status_code": 405, "request": request},
|
| 151 |
+
)
|
| 152 |
+
response = HttpResponseNotAllowed(self._allowed_methods())
|
| 153 |
+
|
| 154 |
+
if self.view_is_async:
|
| 155 |
+
|
| 156 |
+
async def func():
|
| 157 |
+
return response
|
| 158 |
+
|
| 159 |
+
return func()
|
| 160 |
+
else:
|
| 161 |
+
return response
|
| 162 |
+
|
| 163 |
+
def options(self, request, *args, **kwargs):
|
| 164 |
+
"""Handle responding to requests for the OPTIONS HTTP verb."""
|
| 165 |
+
response = HttpResponse()
|
| 166 |
+
response.headers["Allow"] = ", ".join(self._allowed_methods())
|
| 167 |
+
response.headers["Content-Length"] = "0"
|
| 168 |
+
|
| 169 |
+
if self.view_is_async:
|
| 170 |
+
|
| 171 |
+
async def func():
|
| 172 |
+
return response
|
| 173 |
+
|
| 174 |
+
return func()
|
| 175 |
+
else:
|
| 176 |
+
return response
|
| 177 |
+
|
| 178 |
+
def _allowed_methods(self):
|
| 179 |
+
return [m.upper() for m in self.http_method_names if hasattr(self, m)]
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
class TemplateResponseMixin:
|
| 183 |
+
"""A mixin that can be used to render a template."""
|
| 184 |
+
|
| 185 |
+
template_name = None
|
| 186 |
+
template_engine = None
|
| 187 |
+
response_class = TemplateResponse
|
| 188 |
+
content_type = None
|
| 189 |
+
|
| 190 |
+
def render_to_response(self, context, **response_kwargs):
|
| 191 |
+
"""
|
| 192 |
+
Return a response, using the `response_class` for this view, with a
|
| 193 |
+
template rendered with the given context.
|
| 194 |
+
|
| 195 |
+
Pass response_kwargs to the constructor of the response class.
|
| 196 |
+
"""
|
| 197 |
+
response_kwargs.setdefault("content_type", self.content_type)
|
| 198 |
+
return self.response_class(
|
| 199 |
+
request=self.request,
|
| 200 |
+
template=self.get_template_names(),
|
| 201 |
+
context=context,
|
| 202 |
+
using=self.template_engine,
|
| 203 |
+
**response_kwargs,
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
def get_template_names(self):
|
| 207 |
+
"""
|
| 208 |
+
Return a list of template names to be used for the request. Must return
|
| 209 |
+
a list. May not be called if render_to_response() is overridden.
|
| 210 |
+
"""
|
| 211 |
+
if self.template_name is None:
|
| 212 |
+
raise ImproperlyConfigured(
|
| 213 |
+
"TemplateResponseMixin requires either a definition of "
|
| 214 |
+
"'template_name' or an implementation of 'get_template_names()'"
|
| 215 |
+
)
|
| 216 |
+
else:
|
| 217 |
+
return [self.template_name]
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
class TemplateView(TemplateResponseMixin, ContextMixin, View):
|
| 221 |
+
"""
|
| 222 |
+
Render a template. Pass keyword arguments from the URLconf to the context.
|
| 223 |
+
"""
|
| 224 |
+
|
| 225 |
+
def get(self, request, *args, **kwargs):
|
| 226 |
+
context = self.get_context_data(**kwargs)
|
| 227 |
+
return self.render_to_response(context)
|
| 228 |
+
|
| 229 |
+
|
| 230 |
+
class RedirectView(View):
|
| 231 |
+
"""Provide a redirect on any GET request."""
|
| 232 |
+
|
| 233 |
+
permanent = False
|
| 234 |
+
url = None
|
| 235 |
+
pattern_name = None
|
| 236 |
+
query_string = False
|
| 237 |
+
|
| 238 |
+
def get_redirect_url(self, *args, **kwargs):
|
| 239 |
+
"""
|
| 240 |
+
Return the URL redirect to. Keyword arguments from the URL pattern
|
| 241 |
+
match generating the redirect request are provided as kwargs to this
|
| 242 |
+
method.
|
| 243 |
+
"""
|
| 244 |
+
if self.url:
|
| 245 |
+
url = self.url % kwargs
|
| 246 |
+
elif self.pattern_name:
|
| 247 |
+
url = reverse(self.pattern_name, args=args, kwargs=kwargs)
|
| 248 |
+
else:
|
| 249 |
+
return None
|
| 250 |
+
|
| 251 |
+
args = self.request.META.get("QUERY_STRING", "")
|
| 252 |
+
if args and self.query_string:
|
| 253 |
+
url = "%s?%s" % (url, args)
|
| 254 |
+
return url
|
| 255 |
+
|
| 256 |
+
def get(self, request, *args, **kwargs):
|
| 257 |
+
url = self.get_redirect_url(*args, **kwargs)
|
| 258 |
+
if url:
|
| 259 |
+
if self.permanent:
|
| 260 |
+
return HttpResponsePermanentRedirect(url)
|
| 261 |
+
else:
|
| 262 |
+
return HttpResponseRedirect(url)
|
| 263 |
+
else:
|
| 264 |
+
logger.warning(
|
| 265 |
+
"Gone: %s", request.path, extra={"status_code": 410, "request": request}
|
| 266 |
+
)
|
| 267 |
+
return HttpResponseGone()
|
| 268 |
+
|
| 269 |
+
def head(self, request, *args, **kwargs):
|
| 270 |
+
return self.get(request, *args, **kwargs)
|
| 271 |
+
|
| 272 |
+
def post(self, request, *args, **kwargs):
|
| 273 |
+
return self.get(request, *args, **kwargs)
|
| 274 |
+
|
| 275 |
+
def options(self, request, *args, **kwargs):
|
| 276 |
+
return self.get(request, *args, **kwargs)
|
| 277 |
+
|
| 278 |
+
def delete(self, request, *args, **kwargs):
|
| 279 |
+
return self.get(request, *args, **kwargs)
|
| 280 |
+
|
| 281 |
+
def put(self, request, *args, **kwargs):
|
| 282 |
+
return self.get(request, *args, **kwargs)
|
| 283 |
+
|
| 284 |
+
def patch(self, request, *args, **kwargs):
|
| 285 |
+
return self.get(request, *args, **kwargs)
|
testbed/django__django/django/views/generic/detail.py
ADDED
|
@@ -0,0 +1,180 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from django.core.exceptions import ImproperlyConfigured
|
| 2 |
+
from django.db import models
|
| 3 |
+
from django.http import Http404
|
| 4 |
+
from django.utils.translation import gettext as _
|
| 5 |
+
from django.views.generic.base import ContextMixin, TemplateResponseMixin, View
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
class SingleObjectMixin(ContextMixin):
|
| 9 |
+
"""
|
| 10 |
+
Provide the ability to retrieve a single object for further manipulation.
|
| 11 |
+
"""
|
| 12 |
+
|
| 13 |
+
model = None
|
| 14 |
+
queryset = None
|
| 15 |
+
slug_field = "slug"
|
| 16 |
+
context_object_name = None
|
| 17 |
+
slug_url_kwarg = "slug"
|
| 18 |
+
pk_url_kwarg = "pk"
|
| 19 |
+
query_pk_and_slug = False
|
| 20 |
+
|
| 21 |
+
def get_object(self, queryset=None):
|
| 22 |
+
"""
|
| 23 |
+
Return the object the view is displaying.
|
| 24 |
+
|
| 25 |
+
Require `self.queryset` and a `pk` or `slug` argument in the URLconf.
|
| 26 |
+
Subclasses can override this to return any object.
|
| 27 |
+
"""
|
| 28 |
+
# Use a custom queryset if provided; this is required for subclasses
|
| 29 |
+
# like DateDetailView
|
| 30 |
+
if queryset is None:
|
| 31 |
+
queryset = self.get_queryset()
|
| 32 |
+
|
| 33 |
+
# Next, try looking up by primary key.
|
| 34 |
+
pk = self.kwargs.get(self.pk_url_kwarg)
|
| 35 |
+
slug = self.kwargs.get(self.slug_url_kwarg)
|
| 36 |
+
if pk is not None:
|
| 37 |
+
queryset = queryset.filter(pk=pk)
|
| 38 |
+
|
| 39 |
+
# Next, try looking up by slug.
|
| 40 |
+
if slug is not None and (pk is None or self.query_pk_and_slug):
|
| 41 |
+
slug_field = self.get_slug_field()
|
| 42 |
+
queryset = queryset.filter(**{slug_field: slug})
|
| 43 |
+
|
| 44 |
+
# If none of those are defined, it's an error.
|
| 45 |
+
if pk is None and slug is None:
|
| 46 |
+
raise AttributeError(
|
| 47 |
+
"Generic detail view %s must be called with either an object "
|
| 48 |
+
"pk or a slug in the URLconf." % self.__class__.__name__
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
try:
|
| 52 |
+
# Get the single item from the filtered queryset
|
| 53 |
+
obj = queryset.get()
|
| 54 |
+
except queryset.model.DoesNotExist:
|
| 55 |
+
raise Http404(
|
| 56 |
+
_("No %(verbose_name)s found matching the query")
|
| 57 |
+
% {"verbose_name": queryset.model._meta.verbose_name}
|
| 58 |
+
)
|
| 59 |
+
return obj
|
| 60 |
+
|
| 61 |
+
def get_queryset(self):
|
| 62 |
+
"""
|
| 63 |
+
Return the `QuerySet` that will be used to look up the object.
|
| 64 |
+
|
| 65 |
+
This method is called by the default implementation of get_object() and
|
| 66 |
+
may not be called if get_object() is overridden.
|
| 67 |
+
"""
|
| 68 |
+
if self.queryset is None:
|
| 69 |
+
if self.model:
|
| 70 |
+
return self.model._default_manager.all()
|
| 71 |
+
else:
|
| 72 |
+
raise ImproperlyConfigured(
|
| 73 |
+
"%(cls)s is missing a QuerySet. Define "
|
| 74 |
+
"%(cls)s.model, %(cls)s.queryset, or override "
|
| 75 |
+
"%(cls)s.get_queryset()." % {"cls": self.__class__.__name__}
|
| 76 |
+
)
|
| 77 |
+
return self.queryset.all()
|
| 78 |
+
|
| 79 |
+
def get_slug_field(self):
|
| 80 |
+
"""Get the name of a slug field to be used to look up by slug."""
|
| 81 |
+
return self.slug_field
|
| 82 |
+
|
| 83 |
+
def get_context_object_name(self, obj):
|
| 84 |
+
"""Get the name to use for the object."""
|
| 85 |
+
if self.context_object_name:
|
| 86 |
+
return self.context_object_name
|
| 87 |
+
elif isinstance(obj, models.Model):
|
| 88 |
+
return obj._meta.model_name
|
| 89 |
+
else:
|
| 90 |
+
return None
|
| 91 |
+
|
| 92 |
+
def get_context_data(self, **kwargs):
|
| 93 |
+
"""Insert the single object into the context dict."""
|
| 94 |
+
context = {}
|
| 95 |
+
if self.object:
|
| 96 |
+
context["object"] = self.object
|
| 97 |
+
context_object_name = self.get_context_object_name(self.object)
|
| 98 |
+
if context_object_name:
|
| 99 |
+
context[context_object_name] = self.object
|
| 100 |
+
context.update(kwargs)
|
| 101 |
+
return super().get_context_data(**context)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
class BaseDetailView(SingleObjectMixin, View):
|
| 105 |
+
"""A base view for displaying a single object."""
|
| 106 |
+
|
| 107 |
+
def get(self, request, *args, **kwargs):
|
| 108 |
+
self.object = self.get_object()
|
| 109 |
+
context = self.get_context_data(object=self.object)
|
| 110 |
+
return self.render_to_response(context)
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
class SingleObjectTemplateResponseMixin(TemplateResponseMixin):
|
| 114 |
+
template_name_field = None
|
| 115 |
+
template_name_suffix = "_detail"
|
| 116 |
+
|
| 117 |
+
def get_template_names(self):
|
| 118 |
+
"""
|
| 119 |
+
Return a list of template names to be used for the request. May not be
|
| 120 |
+
called if render_to_response() is overridden. Return the following list:
|
| 121 |
+
|
| 122 |
+
* the value of ``template_name`` on the view (if provided)
|
| 123 |
+
* the contents of the ``template_name_field`` field on the
|
| 124 |
+
object instance that the view is operating upon (if available)
|
| 125 |
+
* ``<app_label>/<model_name><template_name_suffix>.html``
|
| 126 |
+
"""
|
| 127 |
+
try:
|
| 128 |
+
names = super().get_template_names()
|
| 129 |
+
except ImproperlyConfigured:
|
| 130 |
+
# If template_name isn't specified, it's not a problem --
|
| 131 |
+
# we just start with an empty list.
|
| 132 |
+
names = []
|
| 133 |
+
|
| 134 |
+
# If self.template_name_field is set, grab the value of the field
|
| 135 |
+
# of that name from the object; this is the most specific template
|
| 136 |
+
# name, if given.
|
| 137 |
+
if self.object and self.template_name_field:
|
| 138 |
+
name = getattr(self.object, self.template_name_field, None)
|
| 139 |
+
if name:
|
| 140 |
+
names.insert(0, name)
|
| 141 |
+
|
| 142 |
+
# The least-specific option is the default <app>/<model>_detail.html;
|
| 143 |
+
# only use this if the object in question is a model.
|
| 144 |
+
if isinstance(self.object, models.Model):
|
| 145 |
+
object_meta = self.object._meta
|
| 146 |
+
names.append(
|
| 147 |
+
"%s/%s%s.html"
|
| 148 |
+
% (
|
| 149 |
+
object_meta.app_label,
|
| 150 |
+
object_meta.model_name,
|
| 151 |
+
self.template_name_suffix,
|
| 152 |
+
)
|
| 153 |
+
)
|
| 154 |
+
elif getattr(self, "model", None) is not None and issubclass(
|
| 155 |
+
self.model, models.Model
|
| 156 |
+
):
|
| 157 |
+
names.append(
|
| 158 |
+
"%s/%s%s.html"
|
| 159 |
+
% (
|
| 160 |
+
self.model._meta.app_label,
|
| 161 |
+
self.model._meta.model_name,
|
| 162 |
+
self.template_name_suffix,
|
| 163 |
+
)
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
# If we still haven't managed to find any template names, we should
|
| 167 |
+
# re-raise the ImproperlyConfigured to alert the user.
|
| 168 |
+
if not names:
|
| 169 |
+
raise
|
| 170 |
+
|
| 171 |
+
return names
|
| 172 |
+
|
| 173 |
+
|
| 174 |
+
class DetailView(SingleObjectTemplateResponseMixin, BaseDetailView):
|
| 175 |
+
"""
|
| 176 |
+
Render a "detail" view of an object.
|
| 177 |
+
|
| 178 |
+
By default this is a model instance looked up from `self.queryset`, but the
|
| 179 |
+
view will support display of *any* object by overriding `self.get_object()`.
|
| 180 |
+
"""
|
testbed/django__django/django/views/templates/default_urlconf.html
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% load i18n %}
|
| 2 |
+
<!doctype html>
|
| 3 |
+
{% get_current_language as LANGUAGE_CODE %}{% get_current_language_bidi as LANGUAGE_BIDI %}
|
| 4 |
+
<html lang="{{ LANGUAGE_CODE|default:'en-us' }}" dir="{{ LANGUAGE_BIDI|yesno:'rtl,ltr,auto' }}">
|
| 5 |
+
<head>
|
| 6 |
+
<meta charset="utf-8">
|
| 7 |
+
<title>{% translate "The install worked successfully! Congratulations!" %}</title>
|
| 8 |
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
| 9 |
+
<style>
|
| 10 |
+
html {
|
| 11 |
+
line-height: 1.15;
|
| 12 |
+
}
|
| 13 |
+
a {
|
| 14 |
+
color: #19865C;
|
| 15 |
+
}
|
| 16 |
+
header {
|
| 17 |
+
border-bottom: 1px solid #efefef;
|
| 18 |
+
}
|
| 19 |
+
body {
|
| 20 |
+
max-width: 960px;
|
| 21 |
+
color: #525252;
|
| 22 |
+
font-family: "Segoe UI", system-ui, sans-serif;
|
| 23 |
+
margin: 0 auto;
|
| 24 |
+
}
|
| 25 |
+
main {
|
| 26 |
+
text-align: center;
|
| 27 |
+
}
|
| 28 |
+
h1, h2, h3, h4, h5, p, ul {
|
| 29 |
+
padding: 0;
|
| 30 |
+
margin: 0;
|
| 31 |
+
font-weight: 400;
|
| 32 |
+
}
|
| 33 |
+
header {
|
| 34 |
+
display: grid;
|
| 35 |
+
grid-template-columns: auto auto;
|
| 36 |
+
align-items: self-end;
|
| 37 |
+
justify-content: space-between;
|
| 38 |
+
gap: 7px;
|
| 39 |
+
padding-top: 20px;
|
| 40 |
+
padding-bottom: 10px;
|
| 41 |
+
}
|
| 42 |
+
.logo {
|
| 43 |
+
font-weight: 700;
|
| 44 |
+
font-size: 1.375rem;
|
| 45 |
+
text-decoration: none;
|
| 46 |
+
}
|
| 47 |
+
.figure {
|
| 48 |
+
margin-top: 19vh;
|
| 49 |
+
max-width: 265px;
|
| 50 |
+
position: relative;
|
| 51 |
+
z-index: -9;
|
| 52 |
+
overflow: visible;
|
| 53 |
+
}
|
| 54 |
+
.exhaust__line {
|
| 55 |
+
animation: thrust 70ms 100 ease-in-out alternate;
|
| 56 |
+
}
|
| 57 |
+
.smoke {
|
| 58 |
+
animation: smoke .1s 70 ease-in-out alternate;
|
| 59 |
+
}
|
| 60 |
+
@keyframes smoke {
|
| 61 |
+
0% {
|
| 62 |
+
transform: translate3d(-5px, 0, 0);
|
| 63 |
+
}
|
| 64 |
+
100% {
|
| 65 |
+
transform: translate3d(5px, 0, 0);
|
| 66 |
+
}
|
| 67 |
+
}
|
| 68 |
+
.flame {
|
| 69 |
+
animation: burnInner2 .1s 70 ease-in-out alternate;
|
| 70 |
+
}
|
| 71 |
+
@keyframes burnInner2 {
|
| 72 |
+
0% {
|
| 73 |
+
transform: translate3d(0, 0, 0);
|
| 74 |
+
}
|
| 75 |
+
100% {
|
| 76 |
+
transform: translate3d(0, 3px, 0);
|
| 77 |
+
}
|
| 78 |
+
}
|
| 79 |
+
@keyframes thrust {
|
| 80 |
+
0% {
|
| 81 |
+
opacity: 1;
|
| 82 |
+
}
|
| 83 |
+
100% {
|
| 84 |
+
opacity: .5;
|
| 85 |
+
}
|
| 86 |
+
}
|
| 87 |
+
@media (prefers-reduced-motion: reduce) {
|
| 88 |
+
.exhaust__line,
|
| 89 |
+
.smoke,
|
| 90 |
+
.flame {
|
| 91 |
+
animation: none;
|
| 92 |
+
}
|
| 93 |
+
}
|
| 94 |
+
h1 {
|
| 95 |
+
font-size: 1.375rem;
|
| 96 |
+
max-width: 32rem;
|
| 97 |
+
margin: 5px auto 0;
|
| 98 |
+
}
|
| 99 |
+
main p {
|
| 100 |
+
line-height: 1.25;
|
| 101 |
+
max-width: 26rem;
|
| 102 |
+
margin: 15px auto 0;
|
| 103 |
+
}
|
| 104 |
+
footer {
|
| 105 |
+
display: grid;
|
| 106 |
+
grid-template-columns: 1fr 1fr 1fr;
|
| 107 |
+
gap: 5px;
|
| 108 |
+
padding: 25px 0;
|
| 109 |
+
position: fixed;
|
| 110 |
+
box-sizing: border-box;
|
| 111 |
+
left: 50%;
|
| 112 |
+
bottom: 0;
|
| 113 |
+
width: 960px;
|
| 114 |
+
transform: translateX(-50%);
|
| 115 |
+
transform-style: preserve-3d;
|
| 116 |
+
border-top: 1px solid #efefef;
|
| 117 |
+
}
|
| 118 |
+
.option {
|
| 119 |
+
display: grid;
|
| 120 |
+
grid-template-columns: min-content 1fr;
|
| 121 |
+
gap: 10px;
|
| 122 |
+
box-sizing: border-box;
|
| 123 |
+
text-decoration: none;
|
| 124 |
+
}
|
| 125 |
+
.option svg {
|
| 126 |
+
width: 1.5rem;
|
| 127 |
+
height: 1.5rem;
|
| 128 |
+
fill: gray;
|
| 129 |
+
border: 1px solid #d6d6d6;
|
| 130 |
+
padding: 5px;
|
| 131 |
+
border-radius: 100%;
|
| 132 |
+
}
|
| 133 |
+
.option p {
|
| 134 |
+
font-weight: 300;
|
| 135 |
+
line-height: 1.25;
|
| 136 |
+
color: #525252;
|
| 137 |
+
display: table;
|
| 138 |
+
}
|
| 139 |
+
.option .option__heading {
|
| 140 |
+
color: #19865C;
|
| 141 |
+
font-size: 1.25rem;
|
| 142 |
+
font-weight: 400;
|
| 143 |
+
}
|
| 144 |
+
@media (max-width: 996px) {
|
| 145 |
+
body, footer {
|
| 146 |
+
max-width: 780px;
|
| 147 |
+
}
|
| 148 |
+
}
|
| 149 |
+
@media (max-width: 800px) {
|
| 150 |
+
footer {
|
| 151 |
+
height: 100%;
|
| 152 |
+
grid-template-columns: 1fr;
|
| 153 |
+
gap: 60px;
|
| 154 |
+
position: relative;
|
| 155 |
+
padding: 25px;
|
| 156 |
+
}
|
| 157 |
+
.figure {
|
| 158 |
+
margin-top: 10px;
|
| 159 |
+
}
|
| 160 |
+
main {
|
| 161 |
+
padding: 0 25px;
|
| 162 |
+
}
|
| 163 |
+
main h1 {
|
| 164 |
+
font-size: 1.25rem;
|
| 165 |
+
}
|
| 166 |
+
header {
|
| 167 |
+
grid-template-columns: 1fr;
|
| 168 |
+
padding-left: 20px;
|
| 169 |
+
padding-right: 20px;
|
| 170 |
+
}
|
| 171 |
+
footer {
|
| 172 |
+
width: 100%;
|
| 173 |
+
margin-top: 50px;
|
| 174 |
+
}
|
| 175 |
+
}
|
| 176 |
+
@media (min-width: 801px) and (max-height: 730px) {
|
| 177 |
+
.figure {
|
| 178 |
+
margin-top: 80px;
|
| 179 |
+
}
|
| 180 |
+
}
|
| 181 |
+
@media (min-width: 801px) and (max-height: 600px) {
|
| 182 |
+
footer {
|
| 183 |
+
position: relative;
|
| 184 |
+
margin: 135px auto 0;
|
| 185 |
+
}
|
| 186 |
+
.figure {
|
| 187 |
+
margin-top: 50px;
|
| 188 |
+
}
|
| 189 |
+
}
|
| 190 |
+
.sr-only {
|
| 191 |
+
clip: rect(1px, 1px, 1px, 1px);
|
| 192 |
+
clip-path: inset(50%);
|
| 193 |
+
height: 1px;
|
| 194 |
+
overflow: hidden;
|
| 195 |
+
position: absolute;
|
| 196 |
+
white-space: nowrap;
|
| 197 |
+
width: 1px;
|
| 198 |
+
}
|
| 199 |
+
</style>
|
| 200 |
+
</head>
|
| 201 |
+
<body>
|
| 202 |
+
<header>
|
| 203 |
+
<a class="logo" href="https://www.djangoproject.com/" target="_blank" rel="noopener">
|
| 204 |
+
django
|
| 205 |
+
</a>
|
| 206 |
+
<p>{% blocktranslate %}View <a href="https://docs.djangoproject.com/en/{{ version }}/releases/" target="_blank" rel="noopener">release notes</a> for Django {{ version }}{% endblocktranslate %}</p>
|
| 207 |
+
</header>
|
| 208 |
+
<main>
|
| 209 |
+
<svg class="figure" viewBox="0 0 508 268" aria-hidden="true">
|
| 210 |
+
<path d="M305.2 156.6c0 4.6-.5 9-1.6 13.2-2.5-4.4-5.6-8.4-9.2-12-4.6-4.6-10-8.4-16-11.2 2.8-11.2 4.5-22.9 5-34.6 1.8 1.4 3.5 2.9 5 4.5 10.5 10.3 16.8 24.5 16.8 40.1zm-75-10c-6 2.8-11.4 6.6-16 11.2-3.5 3.6-6.6 7.6-9.1 12-1-4.3-1.6-8.7-1.6-13.2 0-15.7 6.3-29.9 16.6-40.1 1.6-1.6 3.3-3.1 5.1-4.5.6 11.8 2.2 23.4 5 34.6z" fill="#2E3B39" fill-rule="nonzero"/>
|
| 211 |
+
<path d="M282.981 152.6c16.125-48.1 6.375-104-29.25-142.6-35.625 38.5-45.25 94.5-29.25 142.6h58.5z" stroke="#FFF" stroke-width="3.396" fill="#6DDCBD"/>
|
| 212 |
+
<path d="M271 29.7c-4.4-10.6-9.9-20.6-16.6-29.7-6.7 9-12.2 19-16.6 29.7H271z" stroke="#FFF" stroke-width="3" fill="#2E3B39"/>
|
| 213 |
+
<circle fill="#FFF" cx="254.3" cy="76.8" r="15.5"/>
|
| 214 |
+
<circle stroke="#FFF" stroke-width="7" fill="#6DDCBD" cx="254.3" cy="76.8" r="12.2"/>
|
| 215 |
+
<path class="smoke" d="M507.812 234.24c0-2.16-.632-4.32-1.58-6.24-3.318-6.72-11.85-11.52-21.804-11.52-1.106 0-2.212.12-3.318.24-.474-11.52-12.956-20.76-28.282-20.76-3.318 0-6.636.48-9.638 1.32-4.74-6.72-14.062-11.28-24.806-11.28-.79 0-1.58 0-2.37.12-.79 0-1.58-.12-2.37-.12-10.744 0-20.066 4.56-24.806 11.28a35.326 35.326 0 00-9.638-1.32c-15.642 0-28.282 9.6-28.282 21.48 0 1.32.158 2.76.474 3.96a26.09 26.09 0 00-4.424-.36c-8.058 0-15.01 3.12-19.118 7.8-3.476-1.68-7.742-2.76-12.324-2.76-12.008 0-21.804 7.08-22.752 15.96h-.158c-9.322 0-17.38 4.32-20.856 10.44-4.108-3.6-10.27-6-17.222-6h-1.264c-6.794 0-12.956 2.28-17.222 6-3.476-6.12-11.534-10.44-20.856-10.44h-.158c-.948-9-10.744-15.96-22.752-15.96-4.582 0-8.69.96-12.324 2.76-4.108-4.68-11.06-7.8-19.118-7.8-1.422 0-3.002.12-4.424.36.316-1.32.474-2.64.474-3.96 0-11.88-12.64-21.48-28.282-21.48-3.318 0-6.636.48-9.638 1.32-4.74-6.72-14.062-11.28-24.806-11.28-.79 0-1.58 0-2.37.12-.79 0-1.58-.12-2.37-.12-10.744 0-20.066 4.56-24.806 11.28a35.326 35.326 0 00-9.638-1.32c-15.326 0-27.808 9.24-28.282 20.76-1.106-.12-2.212-.24-3.318-.24-9.954 0-18.486 4.8-21.804 11.52-.948 1.92-1.58 4.08-1.58 6.24 0 4.8 2.528 9.12 6.636 12.36-.79 1.44-1.264 3.12-1.264 4.8 0 7.2 7.742 13.08 17.222 13.08h462.15c9.48 0 17.222-5.88 17.222-13.08 0-1.68-.474-3.36-1.264-4.8 4.582-3.24 7.11-7.56 7.11-12.36z" fill="#E6E9EE"/>
|
| 216 |
+
<path fill="#6DDCBD" d="M239 152h30v8h-30z"/>
|
| 217 |
+
<path class="exhaust__line" fill="#E6E9EE" d="M250 172h7v90h-7z"/>
|
| 218 |
+
<path class="flame" d="M250.27 178.834l-5.32-8.93s-2.47-5.7 3.458-6.118h10.26s6.232.266 3.306 6.194l-5.244 8.93s-3.23 4.37-6.46 0v-.076z" fill="#AA2247"/>
|
| 219 |
+
</svg>
|
| 220 |
+
<h1>{% translate "The install worked successfully! Congratulations!" %}</h1>
|
| 221 |
+
<p>{% blocktranslate %}You are seeing this page because <a href="https://docs.djangoproject.com/en/{{ version }}/ref/settings/#debug" target="_blank" rel="noopener">DEBUG=True</a> is in your settings file and you have not configured any URLs.{% endblocktranslate %}</p>
|
| 222 |
+
</main>
|
| 223 |
+
<footer>
|
| 224 |
+
<a class="option" href="https://docs.djangoproject.com/en/{{ version }}/" target="_blank" rel="noopener">
|
| 225 |
+
<svg viewBox="0 0 24 24" aria-hidden="true">
|
| 226 |
+
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6A4.997 4.997 0 017 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z"></path>
|
| 227 |
+
</svg>
|
| 228 |
+
<p>
|
| 229 |
+
<span class="option__heading">{% translate "Django Documentation" %}</span><span class="sr-only">.</span><br>
|
| 230 |
+
{% translate 'Topics, references, & how-to’s' %}
|
| 231 |
+
</p>
|
| 232 |
+
</a>
|
| 233 |
+
<a class="option" href="https://docs.djangoproject.com/en/{{ version }}/intro/tutorial01/" target="_blank" rel="noopener">
|
| 234 |
+
<svg viewBox="0 0 24 24" aria-hidden="true">
|
| 235 |
+
<path d="M9.4 16.6L4.8 12l4.6-4.6L8 6l-6 6 6 6 1.4-1.4zm5.2 0l4.6-4.6-4.6-4.6L16 6l6 6-6 6-1.4-1.4z"></path>
|
| 236 |
+
</svg>
|
| 237 |
+
<p>
|
| 238 |
+
<span class="option__heading">{% translate "Tutorial: A Polling App" %}</span><span class="sr-only">.</span><br>
|
| 239 |
+
{% translate "Get started with Django" %}
|
| 240 |
+
</p>
|
| 241 |
+
</a>
|
| 242 |
+
<a class="option" href="https://www.djangoproject.com/community/" target="_blank" rel="noopener">
|
| 243 |
+
<svg viewBox="0 0 24 24" aria-hidden="true">
|
| 244 |
+
<path d="M16.5 13c-1.2 0-3.07.34-4.5 1-1.43-.67-3.3-1-4.5-1C5.33 13 1 14.08 1 16.25V19h22v-2.75c0-2.17-4.33-3.25-6.5-3.25zm-4 4.5h-10v-1.25c0-.54 2.56-1.75 5-1.75s5 1.21 5 1.75v1.25zm9 0H14v-1.25c0-.46-.2-.86-.52-1.22.88-.3 1.96-.53 3.02-.53 2.44 0 5 1.21 5 1.75v1.25zM7.5 12c1.93 0 3.5-1.57 3.5-3.5S9.43 5 7.5 5 4 6.57 4 8.5 5.57 12 7.5 12zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 5.5c1.93 0 3.5-1.57 3.5-3.5S18.43 5 16.5 5 13 6.57 13 8.5s1.57 3.5 3.5 3.5zm0-5.5c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2z"></path>
|
| 245 |
+
</svg>
|
| 246 |
+
<p>
|
| 247 |
+
<span class="option__heading">{% translate "Django Community" %}</span><span class="sr-only">.</span><br>
|
| 248 |
+
{% translate "Connect, get help, or contribute" %}
|
| 249 |
+
</p>
|
| 250 |
+
</a>
|
| 251 |
+
</footer>
|
| 252 |
+
</body>
|
| 253 |
+
</html>
|
testbed/django__django/django/views/templates/i18n_catalog.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{% autoescape off %}
|
| 2 |
+
'use strict';
|
| 3 |
+
{
|
| 4 |
+
const globals = this;
|
| 5 |
+
const django = globals.django || (globals.django = {});
|
| 6 |
+
|
| 7 |
+
{% if plural %}
|
| 8 |
+
django.pluralidx = function(n) {
|
| 9 |
+
const v = {{ plural }};
|
| 10 |
+
if (typeof v === 'boolean') {
|
| 11 |
+
return v ? 1 : 0;
|
| 12 |
+
} else {
|
| 13 |
+
return v;
|
| 14 |
+
}
|
| 15 |
+
};
|
| 16 |
+
{% else %}
|
| 17 |
+
django.pluralidx = function(count) { return (count == 1) ? 0 : 1; };
|
| 18 |
+
{% endif %}
|
| 19 |
+
|
| 20 |
+
/* gettext library */
|
| 21 |
+
|
| 22 |
+
django.catalog = django.catalog || {};
|
| 23 |
+
{% if catalog_str %}
|
| 24 |
+
const newcatalog = {{ catalog_str }};
|
| 25 |
+
for (const key in newcatalog) {
|
| 26 |
+
django.catalog[key] = newcatalog[key];
|
| 27 |
+
}
|
| 28 |
+
{% endif %}
|
| 29 |
+
|
| 30 |
+
if (!django.jsi18n_initialized) {
|
| 31 |
+
django.gettext = function(msgid) {
|
| 32 |
+
const value = django.catalog[msgid];
|
| 33 |
+
if (typeof value === 'undefined') {
|
| 34 |
+
return msgid;
|
| 35 |
+
} else {
|
| 36 |
+
return (typeof value === 'string') ? value : value[0];
|
| 37 |
+
}
|
| 38 |
+
};
|
| 39 |
+
|
| 40 |
+
django.ngettext = function(singular, plural, count) {
|
| 41 |
+
const value = django.catalog[singular];
|
| 42 |
+
if (typeof value === 'undefined') {
|
| 43 |
+
return (count == 1) ? singular : plural;
|
| 44 |
+
} else {
|
| 45 |
+
return value.constructor === Array ? value[django.pluralidx(count)] : value;
|
| 46 |
+
}
|
| 47 |
+
};
|
| 48 |
+
|
| 49 |
+
django.gettext_noop = function(msgid) { return msgid; };
|
| 50 |
+
|
| 51 |
+
django.pgettext = function(context, msgid) {
|
| 52 |
+
let value = django.gettext(context + '\x04' + msgid);
|
| 53 |
+
if (value.includes('\x04')) {
|
| 54 |
+
value = msgid;
|
| 55 |
+
}
|
| 56 |
+
return value;
|
| 57 |
+
};
|
| 58 |
+
|
| 59 |
+
django.npgettext = function(context, singular, plural, count) {
|
| 60 |
+
let value = django.ngettext(context + '\x04' + singular, context + '\x04' + plural, count);
|
| 61 |
+
if (value.includes('\x04')) {
|
| 62 |
+
value = django.ngettext(singular, plural, count);
|
| 63 |
+
}
|
| 64 |
+
return value;
|
| 65 |
+
};
|
| 66 |
+
|
| 67 |
+
django.interpolate = function(fmt, obj, named) {
|
| 68 |
+
if (named) {
|
| 69 |
+
return fmt.replace(/%\(\w+\)s/g, function(match){return String(obj[match.slice(2,-2)])});
|
| 70 |
+
} else {
|
| 71 |
+
return fmt.replace(/%s/g, function(match){return String(obj.shift())});
|
| 72 |
+
}
|
| 73 |
+
};
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
/* formatting library */
|
| 77 |
+
|
| 78 |
+
django.formats = {{ formats_str }};
|
| 79 |
+
|
| 80 |
+
django.get_format = function(format_type) {
|
| 81 |
+
const value = django.formats[format_type];
|
| 82 |
+
if (typeof value === 'undefined') {
|
| 83 |
+
return format_type;
|
| 84 |
+
} else {
|
| 85 |
+
return value;
|
| 86 |
+
}
|
| 87 |
+
};
|
| 88 |
+
|
| 89 |
+
/* add to global namespace */
|
| 90 |
+
globals.pluralidx = django.pluralidx;
|
| 91 |
+
globals.gettext = django.gettext;
|
| 92 |
+
globals.ngettext = django.ngettext;
|
| 93 |
+
globals.gettext_noop = django.gettext_noop;
|
| 94 |
+
globals.pgettext = django.pgettext;
|
| 95 |
+
globals.npgettext = django.npgettext;
|
| 96 |
+
globals.interpolate = django.interpolate;
|
| 97 |
+
globals.get_format = django.get_format;
|
| 98 |
+
|
| 99 |
+
django.jsi18n_initialized = true;
|
| 100 |
+
}
|
| 101 |
+
};
|
| 102 |
+
{% endautoescape %}
|