Refs #27656 -- Updated django.core docstring verbs according to PEP 257.

This commit is contained in:
Anton Samarchyan 2017-01-25 14:02:33 -05:00 committed by Tim Graham
parent 3eb679a869
commit 5a6f70b428
38 changed files with 200 additions and 271 deletions

View File

@ -59,7 +59,7 @@ class CacheHandler:
"""
A Cache Handler to manage access to Cache instances.
Ensures only one instance of each alias exists per thread.
Ensure only one instance of each alias exists per thread.
"""
def __init__(self):
self._caches = local()

View File

@ -26,7 +26,7 @@ def default_key_func(key, key_prefix, version):
"""
Default function to generate keys.
Constructs the key used by all other methods. By default it prepends
Construct the key used by all other methods. By default, prepend
the `key_prefix'. KEY_FUNCTION can be used to specify an alternate
function with custom key making behavior.
"""
@ -37,7 +37,7 @@ def get_key_func(key_func):
"""
Function to decide which key function to use.
Defaults to ``default_key_func``.
Default to ``default_key_func``.
"""
if key_func is not None:
if callable(key_func):
@ -76,7 +76,7 @@ class BaseCache:
def get_backend_timeout(self, timeout=DEFAULT_TIMEOUT):
"""
Returns the timeout value usable by this backend based upon the provided
Return the timeout value usable by this backend based upon the provided
timeout.
"""
if timeout == DEFAULT_TIMEOUT:
@ -87,12 +87,12 @@ class BaseCache:
return None if timeout is None else time.time() + timeout
def make_key(self, key, version=None):
"""Constructs the key used by all other methods. By default it
uses the key_func to generate a key (which, by default,
prepends the `key_prefix' and 'version'). A different key
function can be provided at the time of cache construction;
alternatively, you can subclass the cache backend to provide
custom key making behavior.
"""
Construct the key used by all other methods. By default, use the
key_func to generate a key (which, by default, prepends the
`key_prefix' and 'version'). A different key function can be provided
at the time of cache construction; alternatively, you can subclass the
cache backend to provide custom key making behavior.
"""
if version is None:
version = self.version
@ -103,10 +103,10 @@ class BaseCache:
def add(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
"""
Set a value in the cache if the key does not already exist. If
timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.
timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
Returns True if the value was stored, False otherwise.
Return True if the value was stored, False otherwise.
"""
raise NotImplementedError('subclasses of BaseCache must provide an add() method')
@ -119,8 +119,8 @@ class BaseCache:
def set(self, key, value, timeout=DEFAULT_TIMEOUT, version=None):
"""
Set a value in the cache. If timeout is given, that timeout will be
used for the key; otherwise the default cache timeout will be used.
Set a value in the cache. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
"""
raise NotImplementedError('subclasses of BaseCache must provide a set() method')
@ -135,7 +135,7 @@ class BaseCache:
Fetch a bunch of keys from the cache. For certain backends (memcached,
pgsql) this can be *much* faster when fetching multiple values.
Returns a dict mapping each key in keys to its value. If the given
Return a dict mapping each key in keys to its value. If the given
key is missing, it will be missing from the response dict.
"""
d = {}
@ -148,9 +148,9 @@ class BaseCache:
def get_or_set(self, key, default, timeout=DEFAULT_TIMEOUT, version=None):
"""
Fetch a given key from the cache. If the key does not exist,
the key is added and set to the default value. The default value can
also be any callable. If timeout is given, that timeout will be used
for the key; otherwise the default cache timeout will be used.
add the key and set it to the default value. The default value can
also be any callable. If timeout is given, use that timeout for the
key; otherwise use the default cache timeout.
Return the value of the key stored or retrieved.
"""
@ -166,7 +166,7 @@ class BaseCache:
def has_key(self, key, version=None):
"""
Returns True if the key is in the cache and has not expired.
Return True if the key is in the cache and has not expired.
"""
return self.get(key, version=version) is not None
@ -191,7 +191,7 @@ class BaseCache:
def __contains__(self, key):
"""
Returns True if the key is in the cache and has not expired.
Return True if the key is in the cache and has not expired.
"""
# This is a separate method, rather than just a copy of has_key(),
# so that it always has the same functionality as has_key(), even
@ -204,8 +204,8 @@ class BaseCache:
pairs. For certain backends (memcached), this is much more efficient
than calling set() multiple times.
If timeout is given, that timeout will be used for the key; otherwise
the default cache timeout will be used.
If timeout is given, use that timeout for the key; otherwise use the
default cache timeout.
"""
for key, value in data.items():
self.set(key, value, timeout=timeout, version=version)
@ -243,8 +243,9 @@ class BaseCache:
break
def incr_version(self, key, delta=1, version=None):
"""Adds delta to the cache version for the supplied key. Returns the
new version.
"""
Add delta to the cache version for the supplied key. Return the new
version.
"""
if version is None:
version = self.version
@ -258,8 +259,9 @@ class BaseCache:
return version + delta
def decr_version(self, key, delta=1, version=None):
"""Subtracts delta from the cache version for the supplied key. Returns
the new version.
"""
Subtract delta from the cache version for the supplied key. Return the
new version.
"""
return self.incr_version(key, -delta, version)

View File

@ -75,7 +75,7 @@ class FileBasedCache(BaseCache):
def _cull(self):
"""
Removes random cache entries if max_entries is reached at a ratio
Remove random cache entries if max_entries is reached at a ratio
of num_entries / cull_frequency. A value of 0 for CULL_FREQUENCY means
that the entire cache will be purged.
"""
@ -119,8 +119,7 @@ class FileBasedCache(BaseCache):
def _is_expired(self, f):
"""
Takes an open cache file and determines if it has expired,
deletes the file if it is has passed its expiry time.
Take an open cache file `f` and delete it if it's expired.
"""
exp = pickle.load(f)
if exp is not None and exp < time.time():

View File

@ -30,7 +30,7 @@ class BaseMemcachedCache(BaseCache):
@property
def _cache(self):
"""
Implements transparent thread-safe access to a memcached client.
Implement transparent thread-safe access to a memcached client.
"""
if getattr(self, '_client', None) is None:
self._client = self._lib.Client(self._servers, **self._options)

View File

@ -76,7 +76,7 @@ class File(FileProxyMixin):
def multiple_chunks(self, chunk_size=None):
"""
Returns ``True`` if you can expect multiple chunks.
Return ``True`` if you can expect multiple chunks.
NB: If a particular file representation is in memory, subclasses should
always return ``False`` -- there's no good reason to read from memory in
@ -133,7 +133,7 @@ class File(FileProxyMixin):
class ContentFile(File):
"""
A File-like object that takes just raw content, rather than an actual file.
A File-like object that take just raw content, rather than an actual file.
"""
def __init__(self, content, name=None):
stream_class = StringIO if isinstance(content, str) else BytesIO
@ -154,21 +154,15 @@ class ContentFile(File):
def endswith_cr(line):
"""
Return True if line (a text or byte string) ends with '\r'.
"""
"""Return True if line (a text or byte string) ends with '\r'."""
return line.endswith('\r' if isinstance(line, str) else b'\r')
def endswith_lf(line):
"""
Return True if line (a text or byte string) ends with '\n'.
"""
"""Return True if line (a text or byte string) ends with '\n'."""
return line.endswith('\n' if isinstance(line, str) else b'\n')
def equals_lf(line):
"""
Return True if line (a text or byte string) equals '\n'.
"""
"""Return True if line (a text or byte string) equals '\n'."""
return line == ('\n' if isinstance(line, str) else b'\n')

View File

@ -32,7 +32,7 @@ class ImageFile(File):
def get_image_dimensions(file_or_path, close=False):
"""
Returns the (width, height) of an image, given an open file or a path. Set
Return the (width, height) of an image, given an open file or a path. Set
'close' to True to close the file at the end if it is initially in an open
state.
"""

View File

@ -28,15 +28,14 @@ def _samefile(src, dst):
def file_move_safe(old_file_name, new_file_name, chunk_size=1024 * 64, allow_overwrite=False):
"""
Moves a file from one location to another in the safest way possible.
Move a file from one location to another in the safest way possible.
First, tries ``os.rename``, which is simple but will break across filesystems.
If that fails, streams manually from one file to another in pure Python.
First, try ``os.rename``, which is simple but will break across filesystems.
If that fails, stream manually from one file to another in pure Python.
If the destination file exists and ``allow_overwrite`` is ``False``, this
function will throw an ``IOError``.
If the destination file exists and ``allow_overwrite`` is ``False``, raise
``IOError``.
"""
# There's no reason to move if we don't have to.
if _samefile(old_file_name, new_file_name):
return

View File

@ -29,14 +29,12 @@ class Storage:
# These shouldn't be overridden by subclasses unless absolutely necessary.
def open(self, name, mode='rb'):
"""
Retrieves the specified file from storage.
"""
"""Retrieve the specified file from storage."""
return self._open(name, mode)
def save(self, name, content, max_length=None):
"""
Saves new content to the file specified by name. The content should be
Save new content to the file specified by name. The content should be
a proper File object or any python file-like object, ready to be read
from the beginning.
"""
@ -54,14 +52,14 @@ class Storage:
def get_valid_name(self, name):
"""
Returns a filename, based on the provided filename, that's suitable for
Return a filename, based on the provided filename, that's suitable for
use in the target storage system.
"""
return get_valid_filename(name)
def get_available_name(self, name, max_length=None):
"""
Returns a filename that's free on the target storage system, and
Return a filename that's free on the target storage system and
available for new content to be written to.
"""
dir_name, file_name = os.path.split(name)
@ -101,7 +99,7 @@ class Storage:
def path(self, name):
"""
Returns a local filesystem path where the file can be retrieved using
Return a local filesystem path where the file can be retrieved using
Python's built-in open() function. Storage systems that can't be
accessed using open() should *not* implement this method.
"""
@ -112,33 +110,33 @@ class Storage:
def delete(self, name):
"""
Deletes the specified file from the storage system.
Delete the specified file from the storage system.
"""
raise NotImplementedError('subclasses of Storage must provide a delete() method')
def exists(self, name):
"""
Returns True if a file referenced by the given name already exists in the
Return True if a file referenced by the given name already exists in the
storage system, or False if the name is available for a new file.
"""
raise NotImplementedError('subclasses of Storage must provide an exists() method')
def listdir(self, path):
"""
Lists the contents of the specified path, returning a 2-tuple of lists;
List the contents of the specified path. Return a 2-tuple of lists:
the first item being directories, the second item being files.
"""
raise NotImplementedError('subclasses of Storage must provide a listdir() method')
def size(self, name):
"""
Returns the total size, in bytes, of the file specified by name.
Return the total size, in bytes, of the file specified by name.
"""
raise NotImplementedError('subclasses of Storage must provide a size() method')
def url(self, name):
"""
Returns an absolute URL where the file's contents can be accessed
Return an absolute URL where the file's contents can be accessed
directly by a Web browser.
"""
raise NotImplementedError('subclasses of Storage must provide a url() method')

View File

@ -62,9 +62,7 @@ class TemporaryUploadedFile(UploadedFile):
super().__init__(file, name, content_type, size, charset, content_type_extra)
def temporary_file_path(self):
"""
Returns the full path of this file.
"""
"""Return the full path of this file."""
return self.file.name
def close(self):
@ -108,8 +106,7 @@ class SimpleUploadedFile(InMemoryUploadedFile):
@classmethod
def from_dict(cls, file_dict):
"""
Creates a SimpleUploadedFile object from
a dictionary object with the following keys:
Create a SimpleUploadedFile object from a dictionary with keys:
- filename
- content-type
- content

View File

@ -158,7 +158,8 @@ class MemoryFileUploadHandler(FileUploadHandler):
def handle_raw_input(self, input_data, META, content_length, boundary, encoding=None):
"""
Use the content_length to signal whether or not this handler should be in use.
Use the content_length to signal whether or not this handler should be
used.
"""
# Check the content-length header to see if we should
# If the post is too large, we cannot use the Memory handler.
@ -174,18 +175,14 @@ class MemoryFileUploadHandler(FileUploadHandler):
raise StopFutureHandlers()
def receive_data_chunk(self, raw_data, start):
"""
Add the data to the BytesIO file.
"""
"""Add the data to the BytesIO file."""
if self.activated:
self.file.write(raw_data)
else:
return raw_data
def file_complete(self, file_size):
"""
Return a file object if we're activated.
"""
"""Return a file object if this handler is activated."""
if not self.activated:
return

View File

@ -15,10 +15,7 @@ _slashes_re = re.compile(br'/+')
class LimitedStream:
'''
LimitedStream wraps another stream in order to not allow reading from it
past specified amount of bytes.
'''
"""Wrap another stream to disallow reading it past a number of bytes."""
def __init__(self, stream, limit, buf_size=64 * 1024 * 1024):
self.stream = stream
self.remaining = limit
@ -161,9 +158,7 @@ class WSGIHandler(base.BaseHandler):
def get_path_info(environ):
"""
Return the HTTP request's PATH_INFO as a string.
"""
"""Return the HTTP request's PATH_INFO as a string."""
path_info = get_bytes_from_wsgi(environ, 'PATH_INFO', '/')
return repercent_broken_unicode(path_info).decode()
@ -171,8 +166,8 @@ def get_path_info(environ):
def get_script_name(environ):
"""
Returns the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite has been used, returns what would have been
Return the equivalent of the HTTP request's SCRIPT_NAME environment
variable. If Apache mod_rewrite is used, return what would have been
the script name prior to any rewriting (so it's the script name as seen
from the client's perspective), unless the FORCE_SCRIPT_NAME setting is
set (to anything).

View File

@ -26,7 +26,7 @@ __all__ = [
def get_connection(backend=None, fail_silently=False, **kwds):
"""Load an email backend and return an instance of it.
If backend is None (default) settings.EMAIL_BACKEND is used.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend.
@ -42,8 +42,8 @@ def send_mail(subject, message, from_email, recipient_list,
Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
If auth_user is None, use the EMAIL_HOST_USER setting.
If auth_password is None, use the EMAIL_HOST_PASSWORD setting.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
@ -63,13 +63,13 @@ def send_mail(subject, message, from_email, recipient_list,
def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None):
"""
Given a datatuple of (subject, message, from_email, recipient_list), sends
each message to each recipient list. Returns the number of emails sent.
Given a datatuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent.
If from_email is None, the DEFAULT_FROM_EMAIL setting is used.
If auth_user and auth_password are set, they're used to log in.
If auth_user is None, the EMAIL_HOST_USER setting is used.
If auth_password is None, the EMAIL_HOST_PASSWORD setting is used.
If from_email is None, use the DEFAULT_FROM_EMAIL setting.
If auth_user and auth_password are set, use them to log in.
If auth_user is None, use the EMAIL_HOST_USER setting.
If auth_password is None, use the EMAIL_HOST_PASSWORD setting.
Note: The API for this method is frozen. New code wanting to extend the
functionality should use the EmailMessage class directly.
@ -88,7 +88,7 @@ def send_mass_mail(datatuple, fail_silently=False, auth_user=None,
def mail_admins(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the admins, as defined by the ADMINS setting."""
"""Send a message to the admins, as defined by the ADMINS setting."""
if not settings.ADMINS:
return
mail = EmailMultiAlternatives(
@ -103,7 +103,7 @@ def mail_admins(subject, message, fail_silently=False, connection=None,
def mail_managers(subject, message, fail_silently=False, connection=None,
html_message=None):
"""Sends a message to the managers, as defined by the MANAGERS setting."""
"""Send a message to the managers, as defined by the MANAGERS setting."""
if not settings.MANAGERS:
return
mail = EmailMultiAlternatives(

View File

@ -18,7 +18,8 @@ class BaseEmailBackend:
self.fail_silently = fail_silently
def open(self):
"""Open a network connection.
"""
Open a network connection.
This method can be overwritten by backend implementations to
open a network connection.
@ -52,7 +53,7 @@ class BaseEmailBackend:
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
Send one or more EmailMessage objects and return the number of email
messages sent.
"""
raise NotImplementedError('subclasses of BaseEmailBackend must override send_messages() method')

View File

@ -7,7 +7,8 @@ from django.core.mail.backends.base import BaseEmailBackend
class EmailBackend(BaseEmailBackend):
"""A email backend for use during test sessions.
"""
An email backend for use during test sessions.
The test connection stores email messages in a dummy outbox,
rather than sending them out on the wire.

View File

@ -74,7 +74,7 @@ class EmailBackend(BaseEmailBackend):
raise
def close(self):
"""Closes the connection to the email server."""
"""Close the connection to the email server."""
if self.connection is None:
return
try:
@ -94,7 +94,7 @@ class EmailBackend(BaseEmailBackend):
def send_messages(self, email_messages):
"""
Sends one or more EmailMessage objects and returns the number of email
Send one or more EmailMessage objects and return the number of email
messages sent.
"""
if not email_messages:

View File

@ -53,7 +53,7 @@ ADDRESS_HEADERS = {
def forbid_multi_line_headers(name, val, encoding):
"""Forbids multi-line headers, to prevent header injection."""
"""Forbid multi-line headers to prevent header injection."""
encoding = encoding or settings.DEFAULT_CHARSET
val = force_text(val)
if '\n' in val or '\r' in val:
@ -73,7 +73,7 @@ def forbid_multi_line_headers(name, val, encoding):
def split_addr(addr, encoding):
"""
Split the address into local part and domain, properly encoded.
Split the address into local part and domain and encode them.
When non-ascii characters are present in the local part, it must be
MIME-word encoded. The domain name must be idna-encoded if it contains
@ -193,9 +193,7 @@ class SafeMIMEMultipart(MIMEMixin, MIMEMultipart):
class EmailMessage:
"""
A container for email information.
"""
"""A container for email information."""
content_subtype = 'plain'
mixed_subtype = 'mixed'
encoding = None # None => use settings default
@ -280,13 +278,13 @@ class EmailMessage:
def recipients(self):
"""
Returns a list of all recipients of the email (includes direct
Return a list of all recipients of the email (includes direct
addressees as well as Cc and Bcc entries).
"""
return [email for email in (self.to + self.cc + self.bcc) if email]
def send(self, fail_silently=False):
"""Sends the email message."""
"""Send the email message."""
if not self.recipients():
# Don't bother creating the network connection if there's nobody to
# send to.
@ -295,16 +293,15 @@ class EmailMessage:
def attach(self, filename=None, content=None, mimetype=None):
"""
Attaches a file with the given filename and content. The filename can
Attach a file with the given filename and content. The filename can
be omitted and the mimetype is guessed, if not provided.
If the first parameter is a MIMEBase subclass it is inserted directly
If the first parameter is a MIMEBase subclass, insert it directly
into the resulting message attachments.
For a text/* mimetype (guessed or specified), when a bytes object is
specified as content, it will be decoded as UTF-8. If that fails,
the mimetype will be set to DEFAULT_ATTACHMENT_MIME_TYPE and the
content is not decoded.
specified as content, decode it as UTF-8. If that fails, set the
mimetype to DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
"""
if isinstance(filename, MIMEBase):
assert content is None
@ -332,14 +329,14 @@ class EmailMessage:
def attach_file(self, path, mimetype=None):
"""
Attaches a file from the filesystem.
Attach a file from the filesystem.
The mimetype will be set to the DEFAULT_ATTACHMENT_MIME_TYPE if it is
not specified and cannot be guessed.
Set the mimetype to DEFAULT_ATTACHMENT_MIME_TYPE if it isn't specified
and cannot be guessed.
For a text/* mimetype (guessed or specified), the file's content
will be decoded as UTF-8. If that fails, the mimetype will be set to
DEFAULT_ATTACHMENT_MIME_TYPE and the content is not decoded.
For a text/* mimetype (guessed or specified), decode the file's content
as UTF-8. If that fails, set the mimetype to
DEFAULT_ATTACHMENT_MIME_TYPE and don't decode the content.
"""
filename = os.path.basename(path)
@ -366,7 +363,7 @@ class EmailMessage:
def _create_mime_attachment(self, content, mimetype):
"""
Converts the content, mimetype pair into a MIME attachment object.
Convert the content, mimetype pair into a MIME attachment object.
If the mimetype is message/rfc822, content may be an
email.Message or EmailMessage object, as well as a str.
@ -396,7 +393,7 @@ class EmailMessage:
def _create_attachment(self, filename, content, mimetype=None):
"""
Converts the filename, content, mimetype triple into a MIME attachment
Convert the filename, content, mimetype triple into a MIME attachment
object.
"""
attachment = self._create_mime_attachment(content, mimetype)

View File

@ -19,10 +19,8 @@ from django.utils.encoding import force_text
def find_commands(management_dir):
"""
Given a path to a management directory, returns a list of all the command
Given a path to a management directory, return a list of all the command
names that are available.
Returns an empty list if no commands are defined.
"""
command_dir = os.path.join(management_dir, 'commands')
return [name for _, name, is_pkg in pkgutil.iter_modules([command_dir])
@ -31,9 +29,9 @@ def find_commands(management_dir):
def load_command_class(app_name, name):
"""
Given a command name and an application name, returns the Command
class instance. All errors raised by the import process
(ImportError, AttributeError) are allowed to propagate.
Given a command name and an application name, return the Command
class instance. Allow all errors raised by the import process
(ImportError, AttributeError) to propagate.
"""
module = import_module('%s.management.commands.%s' % (app_name, name))
return module.Command()
@ -42,14 +40,14 @@ def load_command_class(app_name, name):
@functools.lru_cache(maxsize=None)
def get_commands():
"""
Returns a dictionary mapping command names to their callback applications.
Return a dictionary mapping command names to their callback applications.
This works by looking for a management.commands package in django.core, and
in each installed application -- if a commands package exists, all commands
in that package are registered.
Look for a management.commands package in django.core, and in each
installed application -- if a commands package exists, register all
commands in that package.
Core commands are always included. If a settings module has been
specified, user-defined commands will also be included.
specified, also include user-defined commands.
The dictionary is in the format {command_name: app_name}. Key-value
pairs from this dictionary can then be used in calls to
@ -76,7 +74,7 @@ def get_commands():
def call_command(command_name, *args, **options):
"""
Calls the given command, with the given options and args/kwargs.
Call the given command, with the given options and args/kwargs.
This is the primary API you should use for calling specific commands.
@ -130,7 +128,7 @@ def call_command(command_name, *args, **options):
class ManagementUtility:
"""
Encapsulates the logic of the django-admin and manage.py utilities.
Encapsulate the logic of the django-admin and manage.py utilities.
"""
def __init__(self, argv=None):
self.argv = argv or sys.argv[:]
@ -138,9 +136,7 @@ class ManagementUtility:
self.settings_exception = None
def main_help_text(self, commands_only=False):
"""
Returns the script's main help text, as a string.
"""
"""Return the script's main help text, as a string."""
if commands_only:
usage = sorted(get_commands().keys())
else:
@ -174,7 +170,7 @@ class ManagementUtility:
def fetch_command(self, subcommand):
"""
Tries to fetch the given subcommand, printing a message with the
Try to fetch the given subcommand, printing a message with the
appropriate command called from the command line (usually
"django-admin" or "manage.py") if it can't be found.
"""
@ -280,8 +276,8 @@ class ManagementUtility:
def execute(self):
"""
Given the command-line arguments, this figures out which subcommand is
being run, creates a parser appropriate to that command, and runs it.
Given the command-line arguments, figure out which subcommand is being
run, create a parser appropriate to that command, and run it.
"""
try:
subcommand = self.argv[1]
@ -354,8 +350,6 @@ class ManagementUtility:
def execute_from_command_line(argv=None):
"""
A simple method that runs a ManagementUtility.
"""
"""Run a ManagementUtility."""
utility = ManagementUtility(argv)
utility.execute()

View File

@ -345,10 +345,10 @@ class BaseCommand:
def check(self, app_configs=None, tags=None, display_num_errors=False,
include_deployment_checks=False, fail_level=checks.ERROR):
"""
Uses the system check framework to validate entire Django project.
Raises CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), they are printed to
stderr and no exception is raised.
Use the system check framework to validate entire Django project.
Raise CommandError for any serious message (error or critical errors).
If there are only light messages (like warnings), print them to stderr
and don't raise an exception.
"""
all_issues = self._run_checks(
app_configs=app_configs,

View File

@ -11,7 +11,7 @@ from django.utils import termcolors
def supports_color():
"""
Returns True if the running system's terminal supports color,
Return True if the running system's terminal supports color,
and False otherwise.
"""
plat = sys.platform
@ -61,14 +61,14 @@ def make_style(config_string=''):
@functools.lru_cache(maxsize=None)
def no_style():
"""
Returns a Style object with no color scheme.
Return a Style object with no color scheme.
"""
return make_style('nocolor')
def color_style():
"""
Returns a Style object from the Django color scheme.
Return a Style object from the Django color scheme.
"""
if not supports_color():
return no_style()

View File

@ -2,7 +2,7 @@ from django.core.management.base import BaseCommand
def module_to_dict(module, omittable=lambda k: k.startswith('_')):
"""Converts a module namespace to a Python dictionary."""
"""Convert a module namespace to a Python dictionary."""
return {k: repr(v) for k, v in module.__dict__.items() if not omittable(k)}

View File

@ -137,9 +137,7 @@ class Command(BaseCommand):
)
def load_label(self, fixture_label):
"""
Loads fixtures files for a given label.
"""
"""Load fixtures files for a given label."""
show_progress = self.verbosity >= 3
for fixture_file, fixture_dir, fixture_name in self.find_fixtures(fixture_label):
_, ser_fmt, cmp_fmt = self.parse_name(os.path.basename(fixture_file))
@ -203,9 +201,7 @@ class Command(BaseCommand):
@functools.lru_cache(maxsize=None)
def find_fixtures(self, fixture_label):
"""
Finds fixture files for a given label.
"""
"""Find fixture files for a given label."""
fixture_name, ser_fmt, cmp_fmt = self.parse_name(fixture_label)
databases = [self.using, None]
cmp_fmts = list(self.compression_formats.keys()) if cmp_fmt is None else [cmp_fmt]
@ -291,7 +287,7 @@ class Command(BaseCommand):
def parse_name(self, fixture_name):
"""
Splits fixture name in name, serialization format, compression format.
Split fixture name in name, serialization format, compression format.
"""
parts = fixture_name.rsplit('.', 2)

View File

@ -60,7 +60,7 @@ class TranslatableFile:
class BuildFile:
"""
Represents the state of a translatable file during the build process.
Represent the state of a translatable file during the build process.
"""
def __init__(self, command, domain, translatable):
self.command = command
@ -170,8 +170,8 @@ def normalize_eols(raw_contents):
def write_pot_file(potfile, msgs):
"""
Write the :param potfile: POT file with the :param msgs: contents,
previously making sure its format is valid.
Write the `potfile` with the `msgs` contents, making sure its format is
valid.
"""
pot_lines = msgs.splitlines()
if os.path.exists(potfile):
@ -423,10 +423,9 @@ class Command(BaseCommand):
def find_files(self, root):
"""
Helper method to get all files in the given root. Also check that there
is a matching locale dir for each file.
Get all files in the given root. Also check that there is a matching
locale dir for each file.
"""
def is_ignored(path, ignore_patterns):
"""
Check if the given path should be ignored or not.
@ -499,7 +498,7 @@ class Command(BaseCommand):
Extract translatable literals from the specified files, creating or
updating the POT file for a given locale directory.
Uses the xgettext GNU gettext utility.
Use the xgettext GNU gettext utility.
"""
build_files = []
for translatable in files:
@ -591,10 +590,10 @@ class Command(BaseCommand):
def write_po_file(self, potfile, locale):
"""
Creates or updates the PO file for self.domain and :param locale:.
Uses contents of the existing :param potfile:.
Create or update the PO file for self.domain and `locale`.
Use contents of the existing `potfile`.
Uses msgmerge, and msgattrib GNU gettext utilities.
Use msgmerge and msgattrib GNU gettext utilities.
"""
basedir = os.path.join(os.path.dirname(potfile), locale, 'LC_MESSAGES')
if not os.path.isdir(basedir):
@ -633,7 +632,7 @@ class Command(BaseCommand):
def copy_plural_forms(self, msgs, locale):
"""
Copies plural forms header contents from a Django catalog of locale to
Copy plural forms header contents from a Django catalog of locale to
the msgs string, inserting it at the right place. msgs should be the
contents of a newly created .po file.
"""

View File

@ -176,7 +176,7 @@ class Command(BaseCommand):
def write_migration_files(self, changes):
"""
Takes a changes dict and writes them out as migration files.
Take a changes dict and write them out as migration files.
"""
directory_created = {}
for app_label, app_migrations in changes.items():

View File

@ -62,9 +62,7 @@ class Command(BaseCommand):
super().execute(*args, **options)
def get_handler(self, *args, **options):
"""
Returns the default WSGI handler for the runner.
"""
"""Return the default WSGI handler for the runner."""
return get_internal_wsgi_application()
def handle(self, *args, **options):
@ -101,9 +99,7 @@ class Command(BaseCommand):
self.run(**options)
def run(self, **options):
"""
Runs the server, using the autoreloader if needed
"""
"""Run the server, using the autoreloader if needed."""
use_reloader = options['use_reloader']
if use_reloader:

View File

@ -54,7 +54,7 @@ class Command(BaseCommand):
def show_list(self, connection, app_names=None):
"""
Shows a list of all migrations on the system, or only those of
Show a list of all migrations on the system, or only those of
some named apps.
"""
# Load migrations from disk/DB
@ -90,7 +90,7 @@ class Command(BaseCommand):
def show_plan(self, connection, app_names=None):
"""
Shows all known migrations (or only those of the specified app_names)
Show all known migrations (or only those of the specified app_names)
in the order they will be applied.
"""
# Load migrations from disk/DB

View File

@ -4,10 +4,10 @@ from django.db import models
def sql_flush(style, connection, only_django=False, reset_sequences=True, allow_cascade=False):
"""
Returns a list of the SQL statements used to flush the database.
Return a list of the SQL statements used to flush the database.
If only_django is True, then only table names that have associated Django
models and are in INSTALLED_APPS will be included.
If only_django is True, only include the table names that have associated
Django models and are in INSTALLED_APPS .
"""
if only_django:
tables = connection.introspection.django_table_names(only_existing=True, include_views=False)

View File

@ -24,7 +24,7 @@ _url_drive_re = re.compile('^([a-z])[:|]', re.I)
class TemplateCommand(BaseCommand):
"""
Copies either a Django application layout template or a Django project
Copy either a Django application layout template or a Django project
layout template into the specified directory.
:param style: A color style object (see django.core.management.color).
@ -185,9 +185,9 @@ class TemplateCommand(BaseCommand):
def handle_template(self, template, subdir):
"""
Determines where the app or project templates are.
Use django.__path__[0] as the default because we don't
know into which directory Django has been installed.
Determine where the app or project templates are.
Use django.__path__[0] as the default because the Django install
directory isn't known.
"""
if template is None:
return path.join(django.__path__[0], 'conf', subdir)
@ -222,7 +222,7 @@ class TemplateCommand(BaseCommand):
def download(self, url):
"""
Downloads the given URL and returns the file name.
Download the given URL and return the file name.
"""
def cleanup_url(url):
tmp = url.rstrip('/')
@ -286,7 +286,7 @@ class TemplateCommand(BaseCommand):
def extract(self, filename):
"""
Extracts the given file to a temporarily and returns
Extract the given file to a temporarily and return
the path of the directory with the extracted content.
"""
prefix = 'django_%s_template_' % self.app_or_project
@ -302,9 +302,7 @@ class TemplateCommand(BaseCommand):
(filename, tempdir, e))
def is_url(self, template):
"""
Returns True if the name looks like a URL
"""
"""Return True if the name looks like a URL."""
if ':' not in template:
return False
scheme = template.split(':', 1)[0].lower()

View File

@ -12,7 +12,7 @@ def popen_wrapper(args, os_err_exc_type=CommandError, stdout_encoding='utf-8'):
"""
Friendly wrapper around Popen.
Returns stdout output, stderr output and OS status code.
Return stdout output, stderr output, and OS status code.
"""
try:
p = Popen(args, shell=False, stdout=PIPE, stderr=PIPE, close_fds=os.name != 'nt')
@ -28,7 +28,7 @@ def popen_wrapper(args, os_err_exc_type=CommandError, stdout_encoding='utf-8'):
def handle_extensions(extensions):
"""
Organizes multiple extensions that are separated with commas or passed by
Organize multiple extensions that are separated with commas or passed by
using --extension/-e multiple times.
For example: running 'django-admin makemessages -e js,txt -e xhtml -a'

View File

@ -33,9 +33,7 @@ class Paginator:
self.allow_empty_first_page = allow_empty_first_page
def validate_number(self, number):
"""
Validates the given 1-based page number.
"""
"""Validate the given 1-based page number."""
try:
number = int(number)
except (TypeError, ValueError):
@ -50,9 +48,7 @@ class Paginator:
return number
def page(self, number):
"""
Returns a Page object for the given 1-based page number.
"""
"""Return a Page object for the given 1-based page number."""
number = self.validate_number(number)
bottom = (number - 1) * self.per_page
top = bottom + self.per_page
@ -62,7 +58,7 @@ class Paginator:
def _get_page(self, *args, **kwargs):
"""
Returns an instance of a single page.
Return an instance of a single page.
This hook can be used by subclasses to use an alternative to the
standard :cls:`Page` object.
@ -71,9 +67,7 @@ class Paginator:
@cached_property
def count(self):
"""
Returns the total number of objects, across all pages.
"""
"""Return the total number of objects, across all pages."""
try:
return self.object_list.count()
except (AttributeError, TypeError):
@ -84,9 +78,7 @@ class Paginator:
@cached_property
def num_pages(self):
"""
Returns the total number of pages.
"""
"""Return the total number of pages."""
if self.count == 0 and not self.allow_empty_first_page:
return 0
hits = max(1, self.count - self.orphans)
@ -95,7 +87,7 @@ class Paginator:
@property
def page_range(self):
"""
Returns a 1-based range of pages for iterating through within
Return a 1-based range of pages for iterating through within
a template for loop.
"""
return range(1, self.num_pages + 1)
@ -154,7 +146,7 @@ class Page(collections.Sequence):
def start_index(self):
"""
Returns the 1-based index of the first object on this page,
Return the 1-based index of the first object on this page,
relative to total objects in the paginator.
"""
# Special case, return zero if no items.
@ -164,7 +156,7 @@ class Page(collections.Sequence):
def end_index(self):
"""
Returns the 1-based index of the last object on this page,
Return the 1-based index of the last object on this page,
relative to total objects found (hits).
"""
# Special case for the last page because there can be orphans.

View File

@ -131,7 +131,7 @@ def serialize(format, queryset, **options):
def deserialize(format, stream_or_string, **options):
"""
Deserialize a stream or a string. Returns an iterator that yields ``(obj,
Deserialize a stream or a string. Return an iterator that yields ``(obj,
m2m_relation_dict)``, where ``obj`` is an instantiated -- but *unsaved* --
object, and ``m2m_relation_dict`` is a dictionary of ``{m2m_field_name :
list_of_related_objects}``.

View File

@ -17,9 +17,7 @@ from django.utils.timezone import is_aware
class Serializer(PythonSerializer):
"""
Convert a queryset to JSON.
"""
"""Convert a queryset to JSON."""
internal_use_only = False
def _init_options(self):
@ -64,9 +62,7 @@ class Serializer(PythonSerializer):
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of JSON data.
"""
"""Deserialize a stream or string of JSON data."""
if not isinstance(stream_or_string, (bytes, str)):
stream_or_string = stream_or_string.read()
if isinstance(stream_or_string, bytes):
@ -83,7 +79,8 @@ def Deserializer(stream_or_string, **options):
class DjangoJSONEncoder(json.JSONEncoder):
"""
JSONEncoder subclass that knows how to encode date/time, decimal types and UUIDs.
JSONEncoder subclass that knows how to encode date/time, decimal types, and
UUIDs.
"""
def default(self, o):
# See "Date Time String Format" in the ECMA-262 specification.

View File

@ -14,7 +14,7 @@ from django.utils.encoding import force_text, is_protected_type
class Serializer(base.Serializer):
"""
Serializes a QuerySet to basic Python objects.
Serialize a QuerySet to basic Python objects.
"""
internal_use_only = True
@ -180,9 +180,7 @@ def Deserializer(object_list, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False
def _get_model(model_identifier):
"""
Helper to look up a model from an "app_label.model_name" string.
"""
"""Look up a model from an "app_label.model_name" string."""
try:
return apps.get_model(model_identifier)
except (LookupError, TypeError):

View File

@ -37,9 +37,7 @@ DjangoSafeDumper.add_representer(collections.OrderedDict, DjangoSafeDumper.repre
class Serializer(PythonSerializer):
"""
Convert a queryset to YAML.
"""
"""Convert a queryset to YAML."""
internal_use_only = False
@ -64,9 +62,7 @@ class Serializer(PythonSerializer):
def Deserializer(stream_or_string, **options):
"""
Deserialize a stream or string of YAML data.
"""
"""Deserialize a stream or string of YAML data."""
if isinstance(stream_or_string, bytes):
stream_or_string = stream_or_string.decode()
if isinstance(stream_or_string, str):

View File

@ -18,9 +18,7 @@ from django.utils.xmlutils import (
class Serializer(base.Serializer):
"""
Serializes a QuerySet to XML.
"""
"""Serialize a QuerySet to XML."""
def indent(self, level):
if self.options.get('indent') is not None:
@ -67,8 +65,8 @@ class Serializer(base.Serializer):
def handle_field(self, obj, field):
"""
Called to handle each field on an object (except for ForeignKeys and
ManyToManyFields)
Handle each field on an object (except for ForeignKeys and
ManyToManyFields).
"""
self.indent(2)
self.xml.startElement("field", OrderedDict([
@ -90,7 +88,7 @@ class Serializer(base.Serializer):
def handle_fk_field(self, obj, field):
"""
Called to handle a ForeignKey (we need to treat them slightly
Handle a ForeignKey (they need to be treated slightly
differently from regular fields).
"""
self._start_relational_field(field)
@ -113,9 +111,9 @@ class Serializer(base.Serializer):
def handle_m2m_field(self, obj, field):
"""
Called to handle a ManyToManyField. Related objects are only
serialized as references to the object's PK (i.e. the related *data*
is not dumped, just the relation).
Handle a ManyToManyField. Related objects are only serialized as
references to the object's PK (i.e. the related *data* is not dumped,
just the relation).
"""
if field.remote_field.through._meta.auto_created:
self._start_relational_field(field)
@ -141,9 +139,7 @@ class Serializer(base.Serializer):
self.xml.endElement("field")
def _start_relational_field(self, field):
"""
Helper to output the <field> element for relational fields
"""
"""Output the <field> element for relational fields."""
self.indent(2)
self.xml.startElement("field", OrderedDict([
("name", field.name),
@ -153,9 +149,7 @@ class Serializer(base.Serializer):
class Deserializer(base.Deserializer):
"""
Deserialize XML.
"""
"""Deserialize XML."""
def __init__(self, stream_or_string, *, using=DEFAULT_DB_ALIAS, ignorenonexistent=False, **options):
super().__init__(stream_or_string, **options)
@ -175,9 +169,7 @@ class Deserializer(base.Deserializer):
raise StopIteration
def _handle_object(self, node):
"""
Convert an <object> node to a DeserializedObject.
"""
"""Convert an <object> node to a DeserializedObject."""
# Look up the model using the model loading mechanism. If this fails,
# bail.
Model = self._get_model_from_node(node, "model")
@ -278,8 +270,8 @@ class Deserializer(base.Deserializer):
def _get_model_from_node(self, node, attr):
"""
Helper to look up a model from a <object model=...> or a <field
rel=... to=...> node.
Look up a model from a <object model=...> or a <field rel=... to=...>
node.
"""
model_identifier = node.getAttribute(attr)
if not model_identifier:
@ -295,9 +287,7 @@ class Deserializer(base.Deserializer):
def getInnerText(node):
"""
Get all the inner text of a DOM node (recursively).
"""
"""Get all the inner text of a DOM node (recursively)."""
# inspired by http://mail.python.org/pipermail/xml-sig/2005-March/011022.html
inner_text = []
for child in node.childNodes:
@ -317,7 +307,7 @@ class DefusedExpatParser(_ExpatParser):
"""
An expat parser hardened against XML bomb attacks.
Forbids DTDs, external entity references
Forbid DTDs, external entity references
"""
def __init__(self, *args, **kwargs):
_ExpatParser.__init__(self, *args, **kwargs)

View File

@ -24,7 +24,7 @@ logger = logging.getLogger('django.server')
def get_internal_wsgi_application():
"""
Loads and returns the WSGI application as configured by the user in
Load and return the WSGI application as configured by the user in
``settings.WSGI_APPLICATION``. With the default ``startproject`` layout,
this will be the ``application`` object in ``projectname/wsgi.py``.
@ -32,7 +32,7 @@ def get_internal_wsgi_application():
for Django's internal server (runserver); external WSGI servers should just
be configured to point to the correct application object directly.
If settings.WSGI_APPLICATION is not set (is ``None``), we just return
If settings.WSGI_APPLICATION is not set (is ``None``), return
whatever ``django.core.wsgi.get_wsgi_application`` returns.
"""
from django.conf import settings

View File

@ -50,16 +50,12 @@ _SEP_UNSAFE = re.compile(r'^[A-z0-9-_=]*$')
class BadSignature(Exception):
"""
Signature does not match
"""
"""Signature does not match."""
pass
class SignatureExpired(BadSignature):
"""
Signature timestamp is older than required max_age
"""
"""Signature timestamp is older than required max_age."""
pass
@ -96,11 +92,11 @@ class JSONSerializer:
def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer, compress=False):
"""
Returns URL-safe, sha1 signed base64 compressed JSON string. If key is
None, settings.SECRET_KEY is used instead.
Return URL-safe, sha1 signed base64 compressed JSON string. If key is
None, use settings.SECRET_KEY instead.
If compress is True (not the default) checks if compressing using zlib can
save some space. Prepends a '.' to signify compression. This is included
If compress is True (not the default), check if compressing using zlib can
save some space. Prepend a '.' to signify compression. This is included
in the signature, to protect against zip bombs.
Salt can be used to namespace the hash, so that a signed string is
@ -129,7 +125,7 @@ def dumps(obj, key=None, salt='django.core.signing', serializer=JSONSerializer,
def loads(s, key=None, salt='django.core.signing', serializer=JSONSerializer, max_age=None):
"""
Reverse of dumps(), raises BadSignature if signature fails.
Reverse of dumps(), raise BadSignature if signature fails.
The serializer is expected to accept a bytestring.
"""

View File

@ -52,8 +52,8 @@ class RegexValidator:
def __call__(self, value):
"""
Validates that the input matches the regular expression
if inverse_match is False, otherwise raises ValidationError.
Validate that the input matches the regular expression
if inverse_match is False, otherwise raise ValidationError.
"""
if not (self.inverse_match is not bool(self.regex.search(
force_text(value)))):
@ -280,10 +280,8 @@ ip_address_validator_map = {
def ip_address_validators(protocol, unpack_ipv4):
"""
Depending on the given parameters returns the appropriate validators for
Depending on the given parameters, return the appropriate validators for
the GenericIPAddressField.
This code is here, because it is exactly the same for the model and the form field.
"""
if protocol != 'both' and unpack_ipv4:
raise ValueError(

View File

@ -4,11 +4,10 @@ from django.core.handlers.wsgi import WSGIHandler
def get_wsgi_application():
"""
The public interface to Django's WSGI support. Should return a WSGI
callable.
The public interface to Django's WSGI support. Return a WSGI callable.
Allows us to avoid making django.core.handlers.WSGIHandler public API, in
case the internal WSGI implementation changes or moves in the future.
Avoids making django.core.handlers.WSGIHandler a public API, in case the
internal WSGI implementation changes or moves in the future.
"""
django.setup(set_prefix=False)
return WSGIHandler()