mirror of
https://github.com/django/django.git
synced 2025-03-12 18:30:48 +00:00
Ref #23919 -- Replaced some os.path usage with pathlib.Path.
This commit is contained in:
parent
5d923f2d8c
commit
11b8c30b9e
@ -10,6 +10,7 @@ import importlib
|
|||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
import warnings
|
import warnings
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.conf import global_settings
|
from django.conf import global_settings
|
||||||
from django.core.exceptions import ImproperlyConfigured
|
from django.core.exceptions import ImproperlyConfigured
|
||||||
@ -130,9 +131,9 @@ class Settings:
|
|||||||
if hasattr(time, 'tzset') and self.TIME_ZONE:
|
if hasattr(time, 'tzset') and self.TIME_ZONE:
|
||||||
# When we can, attempt to validate the timezone. If we can't find
|
# When we can, attempt to validate the timezone. If we can't find
|
||||||
# this file, no check happens and it's harmless.
|
# this file, no check happens and it's harmless.
|
||||||
zoneinfo_root = '/usr/share/zoneinfo'
|
zoneinfo_root = Path('/usr/share/zoneinfo')
|
||||||
if (os.path.exists(zoneinfo_root) and not
|
zone_info_file = zoneinfo_root.joinpath(*self.TIME_ZONE.split('/'))
|
||||||
os.path.exists(os.path.join(zoneinfo_root, *(self.TIME_ZONE.split('/'))))):
|
if zoneinfo_root.exists() and not zone_info_file.exists():
|
||||||
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
|
raise ValueError("Incorrect timezone setting: %s" % self.TIME_ZONE)
|
||||||
# Move the time zone info into os.environ. See ticket #2315 for why
|
# Move the time zone info into os.environ. See ticket #2315 for why
|
||||||
# we don't do this unconditionally (breaks Windows).
|
# we don't do this unconditionally (breaks Windows).
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import inspect
|
import inspect
|
||||||
import os
|
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@ -331,15 +331,15 @@ class TemplateDetailView(BaseAdminDocsView):
|
|||||||
else:
|
else:
|
||||||
# This doesn't account for template loaders (#24128).
|
# This doesn't account for template loaders (#24128).
|
||||||
for index, directory in enumerate(default_engine.dirs):
|
for index, directory in enumerate(default_engine.dirs):
|
||||||
template_file = os.path.join(directory, template)
|
template_file = Path(directory) / template
|
||||||
if os.path.exists(template_file):
|
if template_file.exists():
|
||||||
with open(template_file) as f:
|
with template_file.open() as f:
|
||||||
template_contents = f.read()
|
template_contents = f.read()
|
||||||
else:
|
else:
|
||||||
template_contents = ''
|
template_contents = ''
|
||||||
templates.append({
|
templates.append({
|
||||||
'file': template_file,
|
'file': template_file,
|
||||||
'exists': os.path.exists(template_file),
|
'exists': template_file.exists(),
|
||||||
'contents': template_contents,
|
'contents': template_contents,
|
||||||
'order': index,
|
'order': index,
|
||||||
})
|
})
|
||||||
|
@ -1,8 +1,8 @@
|
|||||||
import functools
|
import functools
|
||||||
import gzip
|
import gzip
|
||||||
import os
|
|
||||||
import re
|
import re
|
||||||
from difflib import SequenceMatcher
|
from difflib import SequenceMatcher
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.exceptions import (
|
from django.core.exceptions import (
|
||||||
@ -165,16 +165,14 @@ class CommonPasswordValidator:
|
|||||||
The list Django ships with contains 20000 common passwords, created by
|
The list Django ships with contains 20000 common passwords, created by
|
||||||
Royce Williams: https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7
|
Royce Williams: https://gist.github.com/roycewilliams/281ce539915a947a23db17137d91aeb7
|
||||||
"""
|
"""
|
||||||
DEFAULT_PASSWORD_LIST_PATH = os.path.join(
|
DEFAULT_PASSWORD_LIST_PATH = Path(__file__).resolve().parent / 'common-passwords.txt.gz'
|
||||||
os.path.dirname(os.path.realpath(__file__)), 'common-passwords.txt.gz'
|
|
||||||
)
|
|
||||||
|
|
||||||
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
|
def __init__(self, password_list_path=DEFAULT_PASSWORD_LIST_PATH):
|
||||||
try:
|
try:
|
||||||
with gzip.open(password_list_path) as f:
|
with gzip.open(str(password_list_path)) as f:
|
||||||
common_passwords_lines = f.read().decode().splitlines()
|
common_passwords_lines = f.read().decode().splitlines()
|
||||||
except IOError:
|
except IOError:
|
||||||
with open(password_list_path) as f:
|
with open(str(password_list_path)) as f:
|
||||||
common_passwords_lines = f.readlines()
|
common_passwords_lines = f.readlines()
|
||||||
|
|
||||||
self.passwords = {p.strip() for p in common_passwords_lines}
|
self.passwords = {p.strip() for p in common_passwords_lines}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import os
|
|
||||||
import socket
|
import socket
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
import geoip2.database
|
import geoip2.database
|
||||||
|
|
||||||
@ -79,27 +79,27 @@ class GeoIP2:
|
|||||||
if not isinstance(path, str):
|
if not isinstance(path, str):
|
||||||
raise TypeError('Invalid path type: %s' % type(path).__name__)
|
raise TypeError('Invalid path type: %s' % type(path).__name__)
|
||||||
|
|
||||||
if os.path.isdir(path):
|
path = Path(path)
|
||||||
|
if path.is_dir():
|
||||||
# Constructing the GeoIP database filenames using the settings
|
# Constructing the GeoIP database filenames using the settings
|
||||||
# dictionary. If the database files for the GeoLite country
|
# dictionary. If the database files for the GeoLite country
|
||||||
# and/or city datasets exist, then try to open them.
|
# and/or city datasets exist, then try to open them.
|
||||||
country_db = os.path.join(path, country or GEOIP_SETTINGS['GEOIP_COUNTRY'])
|
country_db = path / (country or GEOIP_SETTINGS['GEOIP_COUNTRY'])
|
||||||
if os.path.isfile(country_db):
|
if country_db.is_file():
|
||||||
self._country = geoip2.database.Reader(country_db, mode=cache)
|
self._country = geoip2.database.Reader(str(country_db), mode=cache)
|
||||||
self._country_file = country_db
|
self._country_file = country_db
|
||||||
|
|
||||||
city_db = os.path.join(path, city or GEOIP_SETTINGS['GEOIP_CITY'])
|
city_db = path / (city or GEOIP_SETTINGS['GEOIP_CITY'])
|
||||||
if os.path.isfile(city_db):
|
if city_db.is_file():
|
||||||
self._city = geoip2.database.Reader(city_db, mode=cache)
|
self._city = geoip2.database.Reader(str(city_db), mode=cache)
|
||||||
self._city_file = city_db
|
self._city_file = city_db
|
||||||
|
|
||||||
if not self._reader:
|
if not self._reader:
|
||||||
raise GeoIP2Exception('Could not load a database from %s.' % path)
|
raise GeoIP2Exception('Could not load a database from %s.' % path)
|
||||||
elif os.path.isfile(path):
|
elif path.is_file():
|
||||||
# Otherwise, some detective work will be needed to figure out
|
# Otherwise, some detective work will be needed to figure out
|
||||||
# whether the given database path is for the GeoIP country or city
|
# whether the given database path is for the GeoIP country or city
|
||||||
# databases.
|
# databases.
|
||||||
reader = geoip2.database.Reader(path, mode=cache)
|
reader = geoip2.database.Reader(str(path), mode=cache)
|
||||||
db_type = reader.metadata().database_type
|
db_type = reader.metadata().database_type
|
||||||
|
|
||||||
if db_type.endswith('City'):
|
if db_type.endswith('City'):
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
|
||||||
from email import (
|
from email import (
|
||||||
charset as Charset, encoders as Encoders, generator, message_from_string,
|
charset as Charset, encoders as Encoders, generator, message_from_string,
|
||||||
)
|
)
|
||||||
@ -13,6 +12,7 @@ from email.mime.multipart import MIMEMultipart
|
|||||||
from email.mime.text import MIMEText
|
from email.mime.text import MIMEText
|
||||||
from email.utils import formatdate, getaddresses, make_msgid, parseaddr
|
from email.utils import formatdate, getaddresses, make_msgid, parseaddr
|
||||||
from io import BytesIO, StringIO
|
from io import BytesIO, StringIO
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.core.mail.utils import DNS_NAME
|
from django.core.mail.utils import DNS_NAME
|
||||||
@ -333,11 +333,10 @@ class EmailMessage:
|
|||||||
as UTF-8. If that fails, set the mimetype to
|
as UTF-8. If that fails, set the mimetype to
|
||||||
DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
|
DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
|
||||||
"""
|
"""
|
||||||
filename = os.path.basename(path)
|
path = Path(path)
|
||||||
|
with path.open('rb') as file:
|
||||||
with open(path, 'rb') as file:
|
|
||||||
content = file.read()
|
content = file.read()
|
||||||
self.attach(filename, content, mimetype)
|
self.attach(path.name, content, mimetype)
|
||||||
|
|
||||||
def _create_message(self, msg):
|
def _create_message(self, msg):
|
||||||
return self._create_attachments(msg)
|
return self._create_attachments(msg)
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import ipaddress
|
import ipaddress
|
||||||
import os
|
|
||||||
import re
|
import re
|
||||||
|
from pathlib import Path
|
||||||
from urllib.parse import urlsplit, urlunsplit
|
from urllib.parse import urlsplit, urlunsplit
|
||||||
|
|
||||||
from django.core.exceptions import ValidationError
|
from django.core.exceptions import ValidationError
|
||||||
@ -480,7 +480,7 @@ class FileExtensionValidator:
|
|||||||
self.code = code
|
self.code = code
|
||||||
|
|
||||||
def __call__(self, value):
|
def __call__(self, value):
|
||||||
extension = os.path.splitext(value.name)[1][1:].lower()
|
extension = Path(value.name).suffix[1:].lower()
|
||||||
if self.allowed_extensions is not None and extension not in self.allowed_extensions:
|
if self.allowed_extensions is not None and extension not in self.allowed_extensions:
|
||||||
raise ValidationError(
|
raise ValidationError(
|
||||||
self.message,
|
self.message,
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import os
|
|
||||||
import pkgutil
|
import pkgutil
|
||||||
from importlib import import_module
|
from importlib import import_module
|
||||||
|
from pathlib import Path
|
||||||
from threading import local
|
from threading import local
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@ -111,7 +111,7 @@ def load_backend(backend_name):
|
|||||||
except ImportError as e_user:
|
except ImportError as e_user:
|
||||||
# The database backend wasn't found. Display a helpful error message
|
# The database backend wasn't found. Display a helpful error message
|
||||||
# listing all built-in database backends.
|
# listing all built-in database backends.
|
||||||
backend_dir = os.path.join(os.path.dirname(__file__), 'backends')
|
backend_dir = str(Path(__file__).parent / 'backends')
|
||||||
builtin_backends = [
|
builtin_backends = [
|
||||||
name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
|
name for _, name, ispkg in pkgutil.iter_modules([backend_dir])
|
||||||
if ispkg and name not in {'base', 'dummy', 'postgresql_psycopg2'}
|
if ispkg and name not in {'base', 'dummy', 'postgresql_psycopg2'}
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
import functools
|
import functools
|
||||||
import os
|
from pathlib import Path
|
||||||
|
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
from django.template.backends.django import DjangoTemplates
|
from django.template.backends.django import DjangoTemplates
|
||||||
@ -13,7 +13,7 @@ except ImportError:
|
|||||||
def Jinja2(params):
|
def Jinja2(params):
|
||||||
raise ImportError("jinja2 isn't installed")
|
raise ImportError("jinja2 isn't installed")
|
||||||
|
|
||||||
ROOT = os.path.dirname(__file__)
|
ROOT = Path(__file__).parent
|
||||||
|
|
||||||
|
|
||||||
@functools.lru_cache()
|
@functools.lru_cache()
|
||||||
@ -39,7 +39,7 @@ class EngineMixin:
|
|||||||
def engine(self):
|
def engine(self):
|
||||||
return self.backend({
|
return self.backend({
|
||||||
'APP_DIRS': True,
|
'APP_DIRS': True,
|
||||||
'DIRS': [os.path.join(ROOT, self.backend.app_dirname)],
|
'DIRS': [str(ROOT / self.backend.app_dirname)],
|
||||||
'NAME': 'djangoforms',
|
'NAME': 'djangoforms',
|
||||||
'OPTIONS': {},
|
'OPTIONS': {},
|
||||||
})
|
})
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
import functools
|
import functools
|
||||||
import os
|
|
||||||
from collections import Counter, OrderedDict
|
from collections import Counter, OrderedDict
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.apps import apps
|
from django.apps import apps
|
||||||
from django.conf import settings
|
from django.conf import settings
|
||||||
@ -98,12 +98,10 @@ def get_app_template_dirs(dirname):
|
|||||||
dirname is the name of the subdirectory containing templates inside
|
dirname is the name of the subdirectory containing templates inside
|
||||||
installed applications.
|
installed applications.
|
||||||
"""
|
"""
|
||||||
template_dirs = []
|
template_dirs = [
|
||||||
for app_config in apps.get_app_configs():
|
str(Path(app_config.path) / dirname)
|
||||||
if not app_config.path:
|
for app_config in apps.get_app_configs()
|
||||||
continue
|
if app_config.path and (Path(app_config.path) / dirname).is_dir()
|
||||||
template_dir = os.path.join(app_config.path, dirname)
|
]
|
||||||
if os.path.isdir(template_dir):
|
|
||||||
template_dirs.append(template_dir)
|
|
||||||
# Immutable return value because it will be cached and shared by callers.
|
# Immutable return value because it will be cached and shared by callers.
|
||||||
return tuple(template_dirs)
|
return tuple(template_dirs)
|
||||||
|
@ -3,10 +3,10 @@ Views and functions for serving static files. These are only to be used
|
|||||||
during development, and SHOULD NOT be used in a production setting.
|
during development, and SHOULD NOT be used in a production setting.
|
||||||
"""
|
"""
|
||||||
import mimetypes
|
import mimetypes
|
||||||
import os
|
|
||||||
import posixpath
|
import posixpath
|
||||||
import re
|
import re
|
||||||
import stat
|
import stat
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
from django.http import (
|
from django.http import (
|
||||||
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
|
FileResponse, Http404, HttpResponse, HttpResponseNotModified,
|
||||||
@ -34,21 +34,21 @@ def serve(request, path, document_root=None, show_indexes=False):
|
|||||||
``static/directory_index.html``.
|
``static/directory_index.html``.
|
||||||
"""
|
"""
|
||||||
path = posixpath.normpath(path).lstrip('/')
|
path = posixpath.normpath(path).lstrip('/')
|
||||||
fullpath = safe_join(document_root, path)
|
fullpath = Path(safe_join(document_root, path))
|
||||||
if os.path.isdir(fullpath):
|
if fullpath.is_dir():
|
||||||
if show_indexes:
|
if show_indexes:
|
||||||
return directory_index(path, fullpath)
|
return directory_index(path, fullpath)
|
||||||
raise Http404(_("Directory indexes are not allowed here."))
|
raise Http404(_("Directory indexes are not allowed here."))
|
||||||
if not os.path.exists(fullpath):
|
if not fullpath.exists():
|
||||||
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
|
raise Http404(_('"%(path)s" does not exist') % {'path': fullpath})
|
||||||
# Respect the If-Modified-Since header.
|
# Respect the If-Modified-Since header.
|
||||||
statobj = os.stat(fullpath)
|
statobj = fullpath.stat()
|
||||||
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
|
if not was_modified_since(request.META.get('HTTP_IF_MODIFIED_SINCE'),
|
||||||
statobj.st_mtime, statobj.st_size):
|
statobj.st_mtime, statobj.st_size):
|
||||||
return HttpResponseNotModified()
|
return HttpResponseNotModified()
|
||||||
content_type, encoding = mimetypes.guess_type(fullpath)
|
content_type, encoding = mimetypes.guess_type(str(fullpath))
|
||||||
content_type = content_type or 'application/octet-stream'
|
content_type = content_type or 'application/octet-stream'
|
||||||
response = FileResponse(open(fullpath, 'rb'), content_type=content_type)
|
response = FileResponse(fullpath.open('rb'), content_type=content_type)
|
||||||
response["Last-Modified"] = http_date(statobj.st_mtime)
|
response["Last-Modified"] = http_date(statobj.st_mtime)
|
||||||
if stat.S_ISREG(statobj.st_mode):
|
if stat.S_ISREG(statobj.st_mode):
|
||||||
response["Content-Length"] = statobj.st_size
|
response["Content-Length"] = statobj.st_size
|
||||||
@ -95,11 +95,12 @@ def directory_index(path, fullpath):
|
|||||||
else:
|
else:
|
||||||
c = {}
|
c = {}
|
||||||
files = []
|
files = []
|
||||||
for f in os.listdir(fullpath):
|
for f in fullpath.iterdir():
|
||||||
if not f.startswith('.'):
|
if not f.name.startswith('.'):
|
||||||
if os.path.isdir(os.path.join(fullpath, f)):
|
url = str(f.relative_to(fullpath))
|
||||||
f += '/'
|
if f.is_dir():
|
||||||
files.append(f)
|
url += '/'
|
||||||
|
files.append(url)
|
||||||
c.update({
|
c.update({
|
||||||
'directory': path + '/',
|
'directory': path + '/',
|
||||||
'file_list': files,
|
'file_list': files,
|
||||||
|
Loading…
x
Reference in New Issue
Block a user