index
int64 0
731k
| package
stringlengths 2
98
⌀ | name
stringlengths 1
76
| docstring
stringlengths 0
281k
⌀ | code
stringlengths 4
1.07M
⌀ | signature
stringlengths 2
42.8k
⌀ |
---|---|---|---|---|---|
723,714 | inflector | tableize | Converts a class name to its table name according to rails
naming conventions. Example. Converts "Person" to "people".
| def tableize(self, class_name):
''' Converts a class name to its table name according to rails
naming conventions. Example. Converts "Person" to "people".
'''
return self._language.tableize(class_name)
| (self, class_name) |
723,715 | inflector | titleize | Converts an underscored or CamelCase word into a sentence.
The titleize function converts text like "WelcomePage",
"welcome_page" or "welcome page" to this "Welcome Page".
If the "uppercase" parameter is set to 'first' it will only
capitalize the first character of the title.
| def titleize(self, word, uppercase=''):
'''Converts an underscored or CamelCase word into a sentence.
The titleize function converts text like "WelcomePage",
"welcome_page" or "welcome page" to this "Welcome Page".
If the "uppercase" parameter is set to 'first' it will only
capitalize the first character of the title.
'''
return self._language.titleize(word, uppercase)
| (self, word, uppercase='') |
723,716 | inflector | unaccent | Transforms a string to its unaccented version.
This might be useful for generating "friendly" URLs | def unaccent(self, text):
'''Transforms a string to its unaccented version.
This might be useful for generating "friendly" URLs'''
return self._language.unaccent(text)
| (self, text) |
723,717 | inflector | underscore | Converts a word "into_it_s_underscored_version"
Convert any "CamelCased" or "ordinary Word" into an
"underscored_word".
This can be really useful for creating friendly URLs.
| def underscore(self, word):
''' Converts a word "into_it_s_underscored_version"
Convert any "CamelCased" or "ordinary Word" into an
"underscored_word".
This can be really useful for creating friendly URLs.
'''
return self._language.underscore(word)
| (self, word) |
723,718 | inflector | urlize | Transform a string its unaccented and underscored
version ready to be inserted in friendly URLs.
| def urlize(self, text):
'''Transform a string its unaccented and underscored
version ready to be inserted in friendly URLs.
'''
return self._language.urlize(text)
| (self, text) |
723,719 | inflector | variablize | Same as camelize but first char is lowercased
Converts a word like "send_email" to "sendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "whoSOnline" | def variablize(self, word):
'''Same as camelize but first char is lowercased
Converts a word like "send_email" to "sendEmail". It
will remove non alphanumeric character from the word, so
"who's online" will be converted to "whoSOnline"'''
return self._language.variablize(word)
| (self, word) |
723,721 | plexapi.config | PlexConfig | PlexAPI configuration object. Settings are stored in an INI file within the
user's home directory and can be overridden after importing plexapi by simply
setting the value. See the documentation section 'Configuration' for more
details on available options.
Parameters:
path (str): Path of the configuration file to load.
| class PlexConfig(ConfigParser):
""" PlexAPI configuration object. Settings are stored in an INI file within the
user's home directory and can be overridden after importing plexapi by simply
setting the value. See the documentation section 'Configuration' for more
details on available options.
Parameters:
path (str): Path of the configuration file to load.
"""
def __init__(self, path):
ConfigParser.__init__(self)
self.read(path)
self.data = self._asDict()
def get(self, key, default=None, cast=None):
""" Returns the specified configuration value or <default> if not found.
Parameters:
key (str): Configuration variable to load in the format '<section>.<variable>'.
default: Default value to use if key not found.
cast (func): Cast the value to the specified type before returning.
"""
try:
# First: check environment variable is set
envkey = f"PLEXAPI_{key.upper().replace('.', '_')}"
value = os.environ.get(envkey)
if value is None:
# Second: check the config file has attr
section, name = key.lower().split('.')
value = self.data.get(section, {}).get(name, default)
return utils.cast(cast, value) if cast else value
except: # noqa: E722
return default
def _asDict(self):
""" Returns all configuration values as a dictionary. """
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config)
| (path) |
723,726 | plexapi.config | __init__ | null | def __init__(self, path):
ConfigParser.__init__(self)
self.read(path)
self.data = self._asDict()
| (self, path) |
723,730 | plexapi.config | _asDict | Returns all configuration values as a dictionary. | def _asDict(self):
""" Returns all configuration values as a dictionary. """
config = defaultdict(dict)
for section in self._sections:
for name, value in self._sections[section].items():
if name != '__name__':
config[section.lower()][name.lower()] = value
return dict(config)
| (self) |
723,744 | plexapi.config | get | Returns the specified configuration value or <default> if not found.
Parameters:
key (str): Configuration variable to load in the format '<section>.<variable>'.
default: Default value to use if key not found.
cast (func): Cast the value to the specified type before returning.
| def get(self, key, default=None, cast=None):
""" Returns the specified configuration value or <default> if not found.
Parameters:
key (str): Configuration variable to load in the format '<section>.<variable>'.
default: Default value to use if key not found.
cast (func): Cast the value to the specified type before returning.
"""
try:
# First: check environment variable is set
envkey = f"PLEXAPI_{key.upper().replace('.', '_')}"
value = os.environ.get(envkey)
if value is None:
# Second: check the config file has attr
section, name = key.lower().split('.')
value = self.data.get(section, {}).get(name, default)
return utils.cast(cast, value) if cast else value
except: # noqa: E722
return default
| (self, key, default=None, cast=None) |
723,795 | plexapi.utils | SecretsFilter | Logging filter to hide secrets. | class SecretsFilter(logging.Filter):
""" Logging filter to hide secrets. """
def __init__(self, secrets=None):
self.secrets = secrets or set()
def add_secret(self, secret):
if secret is not None and secret != '':
self.secrets.add(secret)
return secret
def filter(self, record):
cleanargs = list(record.args)
for i in range(len(cleanargs)):
if isinstance(cleanargs[i], str):
for secret in self.secrets:
cleanargs[i] = cleanargs[i].replace(secret, '<hidden>')
record.args = tuple(cleanargs)
return True
| (secrets=None) |
723,796 | plexapi.utils | __init__ | null | def __init__(self, secrets=None):
self.secrets = secrets or set()
| (self, secrets=None) |
723,797 | plexapi.utils | add_secret | null | def add_secret(self, secret):
if secret is not None and secret != '':
self.secrets.add(secret)
return secret
| (self, secret) |
723,798 | plexapi.utils | filter | null | def filter(self, record):
cleanargs = list(record.args)
for i in range(len(cleanargs)):
if isinstance(cleanargs[i], str):
for secret in self.secrets:
cleanargs[i] = cleanargs[i].replace(secret, '<hidden>')
record.args = tuple(cleanargs)
return True
| (self, record) |
723,805 | plexapi.config | reset_base_headers | Convenience function returns a dict of all base X-Plex-* headers for session requests. | def reset_base_headers():
""" Convenience function returns a dict of all base X-Plex-* headers for session requests. """
import plexapi
return {
'X-Plex-Platform': plexapi.X_PLEX_PLATFORM,
'X-Plex-Platform-Version': plexapi.X_PLEX_PLATFORM_VERSION,
'X-Plex-Provides': plexapi.X_PLEX_PROVIDES,
'X-Plex-Product': plexapi.X_PLEX_PRODUCT,
'X-Plex-Version': plexapi.X_PLEX_VERSION,
'X-Plex-Device': plexapi.X_PLEX_DEVICE,
'X-Plex-Device-Name': plexapi.X_PLEX_DEVICE_NAME,
'X-Plex-Client-Identifier': plexapi.X_PLEX_IDENTIFIER,
'X-Plex-Language': plexapi.X_PLEX_LANGUAGE,
'X-Plex-Sync-Version': '2',
'X-Plex-Features': 'external-media',
}
| () |
723,806 | platform | uname | Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
| def uname():
""" Fairly portable uname interface. Returns a tuple
of strings (system, node, release, version, machine, processor)
identifying the underlying platform.
Note that unlike the os.uname function this also returns
possible processor information as an additional tuple entry.
Entries which cannot be determined are set to ''.
"""
global _uname_cache
if _uname_cache is not None:
return _uname_cache
# Get some infos from the builtin os.uname API...
try:
system, node, release, version, machine = infos = os.uname()
except AttributeError:
system = sys.platform
node = _node()
release = version = machine = ''
infos = ()
if not any(infos):
# uname is not available
# Try win32_ver() on win32 platforms
if system == 'win32':
release, version, csd, ptype = win32_ver()
machine = machine or _get_machine_win32()
# Try the 'ver' system command available on some
# platforms
if not (release and version):
system, release, version = _syscmd_ver(system)
# Normalize system to what win32_ver() normally returns
# (_syscmd_ver() tends to return the vendor name as well)
if system == 'Microsoft Windows':
system = 'Windows'
elif system == 'Microsoft' and release == 'Windows':
# Under Windows Vista and Windows Server 2008,
# Microsoft changed the output of the ver command. The
# release is no longer printed. This causes the
# system and release to be misidentified.
system = 'Windows'
if '6.0' == version[:3]:
release = 'Vista'
else:
release = ''
# In case we still don't know anything useful, we'll try to
# help ourselves
if system in ('win32', 'win16'):
if not version:
if system == 'win32':
version = '32bit'
else:
version = '16bit'
system = 'Windows'
elif system[:4] == 'java':
release, vendor, vminfo, osinfo = java_ver()
system = 'Java'
version = ', '.join(vminfo)
if not version:
version = vendor
# System specific extensions
if system == 'OpenVMS':
# OpenVMS seems to have release and version mixed up
if not release or release == '0':
release = version
version = ''
# normalize name
if system == 'Microsoft' and release == 'Windows':
system = 'Windows'
release = 'Vista'
vals = system, node, release, version, machine
# Replace 'unknown' values with the more portable ''
_uname_cache = uname_result(*map(_unknown_as_blank, vals))
return _uname_cache
| () |
723,811 | csv23.readers | DictReader | :func:`csv23.reader` yielding dicts of :func:`py:unicode` strings (PY3: :class:`py3:str`). | class DictReader(csv.DictReader):
""":func:`csv23.reader` yielding dicts of :func:`py:unicode` strings (PY3: :class:`py3:str`)."""
def __init__(self, f, fieldnames=None, restkey=None, restval=None,
dialect=DIALECT, encoding=False, **kwds):
# NOTE: csv.DictReader is an old-style class on PY2
csv.DictReader.__init__(self, [], fieldnames, restkey, restval)
self.reader = reader(f, dialect, encoding, **kwds)
| (f, fieldnames=None, restkey=None, restval=None, dialect='excel', encoding=False, **kwds) |
723,812 | csv23.readers | __init__ | null | def __init__(self, f, fieldnames=None, restkey=None, restval=None,
dialect=DIALECT, encoding=False, **kwds):
# NOTE: csv.DictReader is an old-style class on PY2
csv.DictReader.__init__(self, [], fieldnames, restkey, restval)
self.reader = reader(f, dialect, encoding, **kwds)
| (self, f, fieldnames=None, restkey=None, restval=None, dialect='excel', encoding=False, **kwds) |
723,815 | csv23.writers | DictWriter | :func:`csv23.writer` for dicts where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`). | class DictWriter(csv.DictWriter):
""":func:`csv23.writer` for dicts where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`)."""
def __init__(self, f, fieldnames, restval='', extrasaction='raise',
dialect=DIALECT, encoding=False, **kwds):
# NOTE: csv.DictWrier is an old-style class on PY2
csv.DictWriter.__init__(self, mock.mock_open()(), fieldnames, restval,
extrasaction)
self.writer = writer(f, dialect, encoding, **kwds)
| (f, fieldnames, restval='', extrasaction='raise', dialect='excel', encoding=False, **kwds) |
723,816 | csv23.writers | __init__ | null | def __init__(self, f, fieldnames, restval='', extrasaction='raise',
dialect=DIALECT, encoding=False, **kwds):
# NOTE: csv.DictWrier is an old-style class on PY2
csv.DictWriter.__init__(self, mock.mock_open()(), fieldnames, restval,
extrasaction)
self.writer = writer(f, dialect, encoding, **kwds)
| (self, f, fieldnames, restval='', extrasaction='raise', dialect='excel', encoding=False, **kwds) |
723,822 | csv23.extras | NamedTupleReader | :func:`csv23.reader` yielding namedtuples of :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: Iterable of text (:func:`py:unicode`, PY3: :class:`py3:str`) lines.
If an ``encoding`` is given, iterable of encoded (:class:`py:str`, PY3: :class:`py3:bytes`)
lines in the given (8-bit clean) ``encoding``.
dialect: Dialect argument for the :func:`csv23.reader`.
rename: rename argument for :func:`py:collections.namedtuple`, or a
function that is mapped to the first row to turn it into the
``field_names`` of the namedtuple.
row_name: The ``typename`` for the row :func:`py:collections.namedtuple`.
encoding: If not ``False`` (default): name of the encoding needed to
decode the encoded (:class:`py:str`, PY3: :class:`py3:bytes`) lines from ``stream``.
\**kwargs: Keyword arguments for the :func:`csv23.reader`.
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
Notes:
- Creates a :func:`py:collections.namedtuple` when reading the first row (header).
- Uses the first row as ``field_names``. They must be valid Python identifiers
(e.g. no hyphen or dot, they cannot be Python keywords like `class`).
They cannot start with an underscore.
- ``rename=True`` replaces invalid ``field_names`` with positional names (``_0``, ``_1``, etc.).
- If ``rename`` is callable, it is applied to turn the first row strings into ``field_names``.
>>> import io
>>> text = u'coordinate.x,coordinate.y\r\n11,22\r\n'
>>> with io.StringIO(text, newline='') as f:
... for row in NamedTupleReader(f, rename=lambda x: x.replace('.', '_')):
... print('%s %s' % (row.coordinate_x, row.coordinate_y))
11 22
| class NamedTupleReader(object):
r""":func:`csv23.reader` yielding namedtuples of :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: Iterable of text (:func:`py:unicode`, PY3: :class:`py3:str`) lines.
If an ``encoding`` is given, iterable of encoded (:class:`py:str`, PY3: :class:`py3:bytes`)
lines in the given (8-bit clean) ``encoding``.
dialect: Dialect argument for the :func:`csv23.reader`.
rename: rename argument for :func:`py:collections.namedtuple`, or a
function that is mapped to the first row to turn it into the
``field_names`` of the namedtuple.
row_name: The ``typename`` for the row :func:`py:collections.namedtuple`.
encoding: If not ``False`` (default): name of the encoding needed to
decode the encoded (:class:`py:str`, PY3: :class:`py3:bytes`) lines from ``stream``.
\**kwargs: Keyword arguments for the :func:`csv23.reader`.
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
Notes:
- Creates a :func:`py:collections.namedtuple` when reading the first row (header).
- Uses the first row as ``field_names``. They must be valid Python identifiers
(e.g. no hyphen or dot, they cannot be Python keywords like `class`).
They cannot start with an underscore.
- ``rename=True`` replaces invalid ``field_names`` with positional names (``_0``, ``_1``, etc.).
- If ``rename`` is callable, it is applied to turn the first row strings into ``field_names``.
>>> import io
>>> text = u'coordinate.x,coordinate.y\r\n11,22\r\n'
>>> with io.StringIO(text, newline='') as f:
... for row in NamedTupleReader(f, rename=lambda x: x.replace('.', '_')):
... print('%s %s' % (row.coordinate_x, row.coordinate_y))
11 22
"""
def __init__(self, stream, dialect=DIALECT, rename=False, row_name=ROW_NAME,
encoding=False, **kwargs):
self._reader = readers.reader(stream, dialect, encoding, **kwargs)
self._rename = rename
self._row_name = row_name
self._row_cls = None
def __iter__(self):
return self
def __next__(self):
"""Return the next row of the reader's iterable object as a namedtuple,
parsed according to the current dialect.
Usually you should call this as next(reader)."""
make_row = self._make_row
return make_row(next(self._reader))
if PY2:
next = __next__
del __next__
@lazyproperty
def _make_row(self):
assert self._row_cls is None
try:
header = next(self._reader)
except StopIteration:
raise RuntimeError('missing header line for namedtuple fields')
if callable(self._rename):
header = map(self._rename, header)
rename = False
else:
rename = self._rename
self._row_cls = collections.namedtuple(self._row_name, header, rename=rename)
return self._row_cls._make
@property
def dialect(self):
"""A read-only description of the dialect in use by the parser."""
return self._reader.dialect
@property
def line_num(self):
"""The number of lines read from the source iterator.
This is not the same as the number of records returned,
as records can span multiple lines."""
return self._reader.line_num
@property
def row_cls(self):
"""The row tuple subclass from :func:`py:collections.namedtuple` (``None`` before the first row is read)."""
return self._row_cls
| (stream, dialect='excel', rename=False, row_name='Row', encoding=False, **kwargs) |
723,823 | csv23.extras | __init__ | null | def __init__(self, stream, dialect=DIALECT, rename=False, row_name=ROW_NAME,
encoding=False, **kwargs):
self._reader = readers.reader(stream, dialect, encoding, **kwargs)
self._rename = rename
self._row_name = row_name
self._row_cls = None
| (self, stream, dialect='excel', rename=False, row_name='Row', encoding=False, **kwargs) |
723,825 | csv23.extras | __next__ | Return the next row of the reader's iterable object as a namedtuple,
parsed according to the current dialect.
Usually you should call this as next(reader). | def __next__(self):
"""Return the next row of the reader's iterable object as a namedtuple,
parsed according to the current dialect.
Usually you should call this as next(reader)."""
make_row = self._make_row
return make_row(next(self._reader))
| (self) |
723,826 | csv23.extras | NamedTupleWriter | :func:`csv23.writer` for namedtuples where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: File-like object (in binary mode if ``encoding`` is given).
dialect: Dialect argument for the func:`csv23.writer`.
encoding: If not ``False`` (default): name of the encoding used to
encode the output lines.
\**kwargs: Keyword arguments for the :func:`csv23.writer`.
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
| class NamedTupleWriter(object):
r""":func:`csv23.writer` for namedtuples where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: File-like object (in binary mode if ``encoding`` is given).
dialect: Dialect argument for the func:`csv23.writer`.
encoding: If not ``False`` (default): name of the encoding used to
encode the output lines.
\**kwargs: Keyword arguments for the :func:`csv23.writer`.
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
"""
def __init__(self, stream, dialect=DIALECT, encoding=False, **kwargs):
self._writer = writers.writer(stream, dialect, encoding, **kwargs)
def writerow(self, row):
"""Write the row namedtuple to the writer's file object,
formatted according to the current dialect."""
self._writer.writerow(row._fields)
self._writer.writerow(row)
self.writerow = self._writer.writerow
def writerows(self, rows):
"""Write all the rows namedtuples to the writer's file object,
formatted according to the current dialect."""
for r in rows:
self.writerow(r)
@property
def dialect(self):
"""A read-only description of the dialect in use by the writer."""
return self._writer.dialect
| (stream, dialect='excel', encoding=False, **kwargs) |
723,827 | csv23.extras | __init__ | null | def __init__(self, stream, dialect=DIALECT, encoding=False, **kwargs):
self._writer = writers.writer(stream, dialect, encoding, **kwargs)
| (self, stream, dialect='excel', encoding=False, **kwargs) |
723,828 | csv23.extras | writerow | Write the row namedtuple to the writer's file object,
formatted according to the current dialect. | def writerow(self, row):
"""Write the row namedtuple to the writer's file object,
formatted according to the current dialect."""
self._writer.writerow(row._fields)
self._writer.writerow(row)
self.writerow = self._writer.writerow
| (self, row) |
723,829 | csv23.extras | writerows | Write all the rows namedtuples to the writer's file object,
formatted according to the current dialect. | def writerows(self, rows):
"""Write all the rows namedtuples to the writer's file object,
formatted according to the current dialect."""
for r in rows:
self.writerow(r)
| (self, rows) |
723,841 | csv23 | iterrows | Iterator yielding rows from a CSV file (closed on exaustion or error).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to decode the file content.
dialect: CSV dialect argument for :func:`csv23.reader`.
rowtype (str):
``'list'`` for ``list`` rows,
``'dict'`` for :class:`py:dict` rows,
``'namedtuple'`` for :func:`py:collections.namedtuple` rows.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`.
Yields:
``list``, :class:`py:dict`, or :func:`py:collections.namedtuple`:
The next row from the CSV file.
>>> for row in iterrows('spam.csv', encoding='utf-8'): # doctest: +SKIP
... print(row)
... break
[u'Wonderful Spam', u'Lovely Spam']
>>> rows = iterrows('spam.csv', encoding='utf-8') # doctest: +SKIP
>>> next(rows) # doctest: +SKIP
[u'Wonderful Spam', u'Lovely Spam']
>>> rows.close() # doctest: +SKIP
Notes:
- The rows are ``list`` or :class:`py:dict` of :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed automatically, i.e.
on exhaustion, in case of an exception, or by garbage collection.
To do it manually, call the ``.close()``.method of the returned generator object.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
| def iterrows(filename, encoding=ENCODING, dialect=DIALECT,
rowtype=ROWTYPE, **fmtparams):
r"""Iterator yielding rows from a CSV file (closed on exaustion or error).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to decode the file content.
dialect: CSV dialect argument for :func:`csv23.reader`.
rowtype (str):
``'list'`` for ``list`` rows,
``'dict'`` for :class:`py:dict` rows,
``'namedtuple'`` for :func:`py:collections.namedtuple` rows.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`.
Yields:
``list``, :class:`py:dict`, or :func:`py:collections.namedtuple`:
The next row from the CSV file.
>>> for row in iterrows('spam.csv', encoding='utf-8'): # doctest: +SKIP
... print(row)
... break
[u'Wonderful Spam', u'Lovely Spam']
>>> rows = iterrows('spam.csv', encoding='utf-8') # doctest: +SKIP
>>> next(rows) # doctest: +SKIP
[u'Wonderful Spam', u'Lovely Spam']
>>> rows.close() # doctest: +SKIP
Notes:
- The rows are ``list`` or :class:`py:dict` of :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed automatically, i.e.
on exhaustion, in case of an exception, or by garbage collection.
To do it manually, call the ``.close()``.method of the returned generator object.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
"""
with open_reader(filename, encoding, dialect, rowtype, **fmtparams) as reader:
for row in reader:
yield row
| (filename, encoding='utf-8', dialect='excel', rowtype='list', **fmtparams) |
723,842 | csv23 | open_csv | Context manager returning a CSV reader/writer (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
mode (str): ``'r'`` for a :func:`csv23.reader`, ``'w'`` for a :func:`csv23.writer`.
encoding (str): Name of the encoding used to de/encode the file content.
dialect: CSV dialect argument for the :func:`csv23.reader`/:func:`csv23.writer`.
rowtype (str):
``'list'`` for a :func:`csv23.reader`/:func:`csv23.writer`,
``'dict'`` for a :class:`csv23.DictReader`/:class:`csv23.DictWriter`,
``'namedtuple'`` for a :class:`csv23.NamedTupleReader`/:class:`csv23.NamedTupleWriter`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`/:func:`csv23.writer` (must include
``fieldnames`` if ``mode='w'`` and ``rowtype='dict'``).
Returns:
A context manager returning a Python 3 :func:`py3:csv.reader`/:func:`py3:csv.writer` stand-in when entering.
>>> row = [u'Wonderful Spam', u'Lovely Spam']
>>> with open_csv('spam.csv', 'w') as writer: # doctest: +SKIP
... writer.writerow(row)
>>> with open_csv('spam.csv') as reader: # doctest: +SKIP
... assert list(reader) == [row]
Raises:
TypeError: With ``mode='w'`` and ``rowtype='dict'`` but missing ``fieldnames`` keyword argument.
Notes:
- The ``reader``/``writer`` yields/expects string values as :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
| def open_csv(filename, mode='r', encoding=ENCODING, dialect=DIALECT,
rowtype=ROWTYPE, **fmtparams):
r"""Context manager returning a CSV reader/writer (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
mode (str): ``'r'`` for a :func:`csv23.reader`, ``'w'`` for a :func:`csv23.writer`.
encoding (str): Name of the encoding used to de/encode the file content.
dialect: CSV dialect argument for the :func:`csv23.reader`/:func:`csv23.writer`.
rowtype (str):
``'list'`` for a :func:`csv23.reader`/:func:`csv23.writer`,
``'dict'`` for a :class:`csv23.DictReader`/:class:`csv23.DictWriter`,
``'namedtuple'`` for a :class:`csv23.NamedTupleReader`/:class:`csv23.NamedTupleWriter`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`/:func:`csv23.writer` (must include
``fieldnames`` if ``mode='w'`` and ``rowtype='dict'``).
Returns:
A context manager returning a Python 3 :func:`py3:csv.reader`/:func:`py3:csv.writer` stand-in when entering.
>>> row = [u'Wonderful Spam', u'Lovely Spam']
>>> with open_csv('spam.csv', 'w') as writer: # doctest: +SKIP
... writer.writerow(row)
>>> with open_csv('spam.csv') as reader: # doctest: +SKIP
... assert list(reader) == [row]
Raises:
TypeError: With ``mode='w'`` and ``rowtype='dict'`` but missing ``fieldnames`` keyword argument.
Notes:
- The ``reader``/``writer`` yields/expects string values as :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
"""
try:
open_func = _OPEN_FUNCS[mode]
except (KeyError, TypeError):
raise ValueError('invalid mode: %r' % mode)
return open_func(filename, encoding, dialect, rowtype, **fmtparams)
| (filename, mode='r', encoding='utf-8', dialect='excel', rowtype='list', **fmtparams) |
723,843 | csv23.openers | open_reader | Context manager returning a CSV reader (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to decode the file content.
dialect: Dialect argument for the :func:`csv23.reader`.
rowtype (str): ``'list'`` for a :func:`csv23.reader`,
``'dict'`` for a :class:`csv23.DictReader`,
``'namedtuple'`` for a :class:`csv23.NamedTupleReader`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`.
Returns:
A context manager returning a Python 3 :func:`py3:csv.reader` stand-in when entering.
>>> with open_reader('spam.csv', encoding='utf-8') as reader: # doctest: +SKIP
... for row in reader:
... print(row)
[u'Spam!', u'Spam!', u'Spam!']
[u'Spam!', u'Lovely Spam!', u'Lovely Spam!']
>>> reader.line_num # doctest: +SKIP
2
Notes:
- The reader yields a ``list`` or :class:`py:dict` of :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
| def open_reader(filename, encoding=ENCODING, dialect=DIALECT, rowtype=ROWTYPE, **fmtparams):
r"""Context manager returning a CSV reader (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to decode the file content.
dialect: Dialect argument for the :func:`csv23.reader`.
rowtype (str): ``'list'`` for a :func:`csv23.reader`,
``'dict'`` for a :class:`csv23.DictReader`,
``'namedtuple'`` for a :class:`csv23.NamedTupleReader`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.reader`.
Returns:
A context manager returning a Python 3 :func:`py3:csv.reader` stand-in when entering.
>>> with open_reader('spam.csv', encoding='utf-8') as reader: # doctest: +SKIP
... for row in reader:
... print(row)
[u'Spam!', u'Spam!', u'Spam!']
[u'Spam!', u'Lovely Spam!', u'Lovely Spam!']
>>> reader.line_num # doctest: +SKIP
2
Notes:
- The reader yields a ``list`` or :class:`py:dict` of :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
"""
if encoding is None:
encoding = none_encoding()
if PY2 and is_8bit_clean(encoding): # avoid recoding
open_kwargs = {'mode': 'rb'}
reader_func = get_reader(rowtype, 'bytes')
reader_func = functools.partial(reader_func, encoding=encoding)
else:
open_kwargs = {'mode': 'r', 'encoding': encoding, 'newline': ''}
reader_func = get_reader(rowtype, 'text')
return _open_csv(filename, open_kwargs, reader_func, dialect, fmtparams)
| (filename, encoding='utf-8', dialect='excel', rowtype='list', **fmtparams) |
723,844 | csv23.openers | open_writer | Context manager returning a CSV writer (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to encode the output lines.
dialect: Dialect argument for the :func:`csv23.writer`.
rowtype (str): ``'list'`` for a :func:`csv23.writer`,
``'dict'`` for a :class:`csv23.DictWriter`,
``'namedtuple'`` for a :class:`csv23.NamedTupleWriter`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.writer` (must include ``fieldnames`` with
``rowtype='dict'``).
Returns:
A context manager returning a Python 3 :func:`py3:csv.writer` stand-in when entering.
>>> with open_writer('spam.csv', encoding='utf-8') as writer: # doctest: +SKIP
... writer.writerow([u'Spam!', u'Spam!', u'Spam!'])
... writer.writerow([u'Spam!', u'Lovely Spam!', u'Lovely Spam!'])
Raises:
TypeError: With ``rowtype='dict'`` but missing ``fieldnames`` keyword argument.
Notes
- The writer expects string values as :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
| def open_writer(filename, encoding=ENCODING, dialect=DIALECT, rowtype=ROWTYPE, **fmtparams):
r"""Context manager returning a CSV writer (closing the file on exit).
Args:
filename: File (name) argument for the :func:`py:io.open` call.
encoding (str): Name of the encoding used to encode the output lines.
dialect: Dialect argument for the :func:`csv23.writer`.
rowtype (str): ``'list'`` for a :func:`csv23.writer`,
``'dict'`` for a :class:`csv23.DictWriter`,
``'namedtuple'`` for a :class:`csv23.NamedTupleWriter`.
\**fmtparams: Keyword arguments (formatting parameters) for the
:func:`csv23.writer` (must include ``fieldnames`` with
``rowtype='dict'``).
Returns:
A context manager returning a Python 3 :func:`py3:csv.writer` stand-in when entering.
>>> with open_writer('spam.csv', encoding='utf-8') as writer: # doctest: +SKIP
... writer.writerow([u'Spam!', u'Spam!', u'Spam!'])
... writer.writerow([u'Spam!', u'Lovely Spam!', u'Lovely Spam!'])
Raises:
TypeError: With ``rowtype='dict'`` but missing ``fieldnames`` keyword argument.
Notes
- The writer expects string values as :func:`py:unicode` strings (PY3: :class:`py3:str`).
- The underlying opened file object is closed on leaving the ``with``-block.
- If ``encoding=None`` is given, :func:`py:locale.getpreferredencoding` is used.
- Under Python 2, an optimized implementation is used for 8-bit encodings
that are ASCII-compatible (e.g. the default ``'utf-8'``).
"""
if encoding is None:
encoding = none_encoding()
if PY2 and is_8bit_clean(encoding): # avoid recoding
open_kwargs = {'mode': 'wb'}
writer_func = get_writer(rowtype, 'bytes')
writer_func = functools.partial(writer_func, encoding=encoding)
else:
open_kwargs = {'mode': 'w', 'encoding': encoding, 'newline': ''}
writer_func = get_writer(rowtype, 'text')
if rowtype == 'dict' and 'fieldnames' not in fmtparams:
raise TypeError("open_writer(rowtype='dict') requires a 'fieldnames' "
"keyword argument to be passed to csv.DictWriter")
return _open_csv(filename, open_kwargs, writer_func, dialect, fmtparams)
| (filename, encoding='utf-8', dialect='excel', rowtype='list', **fmtparams) |
723,846 | csv23.shortcuts | read_csv | Iterator yielding rows from a file-like object with CSV data.
Args:
file: Source as readable file-like object or filename/:class:`py:os.PathLike`.
dialect: CSV dialect argument for the :func:`csv23.reader`.
encoding (str): Name of the encoding used to decode the file content.
as_list (bool): Return a :class:`py:list` of rows instead of an iterator.
autocompress(bool): Decompress if ``file`` is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'``.
Returns:
An iterator yielding a :class:`py:list` of row values for each row.
>>> read_csv(io.BytesIO(b'spam,eggs\r\n'), encoding='ascii', as_list=True)
[['spam', 'eggs']]
Raises:
TypeError: If ``file`` is a binary buffer or filename/path
and ``encoding`` is ``None``. Also if ``file`` is a text buffer
and ``encoding`` is not ``None``.
Warns:
UserWarning: If file is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'`` but ``autocompress=False`` is given.
Notes:
- ``encoding`` is required if ``file`` is binary or a filesystem path.
- if ``file`` is a text stream, ``encoding`` needs to be ``None``.
| def read_csv(file, dialect=DIALECT, encoding=ENCODING, as_list=False,
autocompress=False):
r"""Iterator yielding rows from a file-like object with CSV data.
Args:
file: Source as readable file-like object or filename/:class:`py:os.PathLike`.
dialect: CSV dialect argument for the :func:`csv23.reader`.
encoding (str): Name of the encoding used to decode the file content.
as_list (bool): Return a :class:`py:list` of rows instead of an iterator.
autocompress(bool): Decompress if ``file`` is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'``.
Returns:
An iterator yielding a :class:`py:list` of row values for each row.
>>> read_csv(io.BytesIO(b'spam,eggs\r\n'), encoding='ascii', as_list=True)
[['spam', 'eggs']]
Raises:
TypeError: If ``file`` is a binary buffer or filename/path
and ``encoding`` is ``None``. Also if ``file`` is a text buffer
and ``encoding`` is not ``None``.
Warns:
UserWarning: If file is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'`` but ``autocompress=False`` is given.
Notes:
- ``encoding`` is required if ``file`` is binary or a filesystem path.
- if ``file`` is a text stream, ``encoding`` needs to be ``None``.
"""
open_kwargs = {'encoding': encoding, 'newline': ''}
if hasattr(file, 'read'):
if isinstance(file, io.TextIOBase):
if encoding is not None:
raise TypeError('bytes-like object expected')
f = file
else:
if encoding is None:
raise TypeError('need encoding for wrapping byte-stream')
f = io.TextIOWrapper(file, **open_kwargs)
f = nullcontext(f)
else:
if encoding is None:
raise TypeError('need encoding for opening file by path')
filepath = str(file)
open_module = _get_open_module(filepath, autocompress=autocompress)
f = open_module.open(filepath, 'rt', **open_kwargs)
rows = iterrows(f, dialect=dialect)
if as_list:
rows = list(rows)
return rows
| (file, dialect='excel', encoding='utf-8', as_list=False, autocompress=False) |
723,847 | csv23.readers | reader | CSV reader yielding lists of :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: Iterable of text (:func:`py:unicode`, PY3: :class:`py3:str`) lines.
If an ``encoding`` is given, iterable of encoded (:class:`py:str`, PY3: :class:`py3:bytes`)
lines in the given (8-bit clean) ``encoding``.
dialect: Dialect argument for the underlying :func:`py:csv.reader`.
encoding: If not ``False`` (default): name of the encoding needed to
decode the encoded (:class:`py:str`, PY3: :class:`py3:bytes`) lines from ``stream``.
\**fmtparams: Keyword arguments (formatting parameters) for the
underlying :func:`py:csv.reader`.
Returns:
A Python 3 :func:`py3:csv.reader` stand-in yielding a list of :func:`py:unicode` strings
(PY3: :class:`py3:str`) for each row.
>>> import io
>>> text = u'Spam!,Spam!,Spam!\r\nSpam!,Lovely Spam!,Lovely Spam!\r\n'
>>> with io.StringIO(text, newline='') as f:
... for row in reader(f):
... print(', '.join(row))
Spam!, Spam!, Spam!
Spam!, Lovely Spam!, Lovely Spam!
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
| def reader(stream, dialect=DIALECT, encoding=False, **fmtparams):
r"""CSV reader yielding lists of :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: Iterable of text (:func:`py:unicode`, PY3: :class:`py3:str`) lines.
If an ``encoding`` is given, iterable of encoded (:class:`py:str`, PY3: :class:`py3:bytes`)
lines in the given (8-bit clean) ``encoding``.
dialect: Dialect argument for the underlying :func:`py:csv.reader`.
encoding: If not ``False`` (default): name of the encoding needed to
decode the encoded (:class:`py:str`, PY3: :class:`py3:bytes`) lines from ``stream``.
\**fmtparams: Keyword arguments (formatting parameters) for the
underlying :func:`py:csv.reader`.
Returns:
A Python 3 :func:`py3:csv.reader` stand-in yielding a list of :func:`py:unicode` strings
(PY3: :class:`py3:str`) for each row.
>>> import io
>>> text = u'Spam!,Spam!,Spam!\r\nSpam!,Lovely Spam!,Lovely Spam!\r\n'
>>> with io.StringIO(text, newline='') as f:
... for row in reader(f):
... print(', '.join(row))
Spam!, Spam!, Spam!
Spam!, Lovely Spam!, Lovely Spam!
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
"""
if encoding is False:
return UnicodeTextReader(stream, dialect, **fmtparams)
if encoding is None:
encoding = none_encoding()
if not is_8bit_clean(encoding):
raise NotImplementedError
return UnicodeBytesReader(stream, dialect, encoding, **fmtparams)
| (stream, dialect='excel', encoding=False, **fmtparams) |
723,853 | csv23.shortcuts | write_csv | Write rows into a file-like object using CSV format.
Args:
file: Target as writeable file-like object, or as filename
or :class:`py:os.Pathlike`, or as updateable hash,
or ``None`` for string output.
rows: CSV values to write as iterable of row value iterables.
header: Iterable of first row values or ``None`` for no header.
dialect: Dialect argument for the :func:`csv23.writer`.
encoding (str): Name of the encoding used to encode the file content.
autocompress(bool): Compress if ``file`` is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'``.
Returns:
If ``file`` is a filename/path, return it as :class:`py:pathlib.Path`.
If ``file`` is a file-like object or a hash return it (without closing).
If ``file`` is ``None`` return the CSV data as :class:`py:str`.
>>> write_csv(io.BytesIO(), iter([('spam', 'eggs')]), encoding='ascii').getvalue()
b'spam,eggs\r\n'
Raises:
TypeError: If ``file`` is a binary buffer or filename/path
and ``encoding`` is ``None``. Also if ``file`` is a text buffer
and ``encoding`` is not ``None``.
Warns:
UserWarning: If file is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'`` but ``autocompress=False`` is given.
Notes:
- ``encoding`` is required if ``file`` is binary or a filesystem path.
- if ``file`` is a text stream, ``encoding`` needs to be ``None``.
| def write_csv(file, rows, header=None, dialect=DIALECT, encoding=ENCODING,
autocompress=False):
r"""Write rows into a file-like object using CSV format.
Args:
file: Target as writeable file-like object, or as filename
or :class:`py:os.Pathlike`, or as updateable hash,
or ``None`` for string output.
rows: CSV values to write as iterable of row value iterables.
header: Iterable of first row values or ``None`` for no header.
dialect: Dialect argument for the :func:`csv23.writer`.
encoding (str): Name of the encoding used to encode the file content.
autocompress(bool): Compress if ``file`` is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'``.
Returns:
If ``file`` is a filename/path, return it as :class:`py:pathlib.Path`.
If ``file`` is a file-like object or a hash return it (without closing).
If ``file`` is ``None`` return the CSV data as :class:`py:str`.
>>> write_csv(io.BytesIO(), iter([('spam', 'eggs')]), encoding='ascii').getvalue()
b'spam,eggs\r\n'
Raises:
TypeError: If ``file`` is a binary buffer or filename/path
and ``encoding`` is ``None``. Also if ``file`` is a text buffer
and ``encoding`` is not ``None``.
Warns:
UserWarning: If file is a path that ends in
``'.bz2'``, ``'.gz'``, or ``'.xz'`` but ``autocompress=False`` is given.
Notes:
- ``encoding`` is required if ``file`` is binary or a filesystem path.
- if ``file`` is a text stream, ``encoding`` needs to be ``None``.
"""
open_kwargs = {'encoding': encoding, 'newline': ''}
textio_kwargs = dict(write_through=True, **open_kwargs)
hashsum = None
if file is None:
if encoding is None:
f = io.StringIO()
else:
f = io.TextIOWrapper(io.BytesIO(), **textio_kwargs)
elif hasattr(file, 'write'):
result = file
if encoding is None:
f = file
else:
f = io.TextIOWrapper(file, **textio_kwargs)
f = nullcontext(f)
elif hasattr(file, 'hexdigest'):
result = hashsum = file
if encoding is None:
raise TypeError('need encoding for wrapping byte-stream')
f = io.TextIOWrapper(io.BytesIO(), **textio_kwargs)
else:
result = pathlib.Path(file)
if encoding is None:
raise TypeError('need encoding for opening file by path')
filepath = str(file)
open_module = _get_open_module(filepath, autocompress=autocompress)
f = open_module.open(filepath, 'wt', **open_kwargs)
with f as f:
writer = csv23_writer(f, dialect=dialect, encoding=False)
if header is not None:
writer.writerows([header])
if hashsum is not None:
buf = f.buffer
for rows in iterslices(rows, 1000):
writer.writerows(rows)
hashsum.update(_get_update_bytes(buf))
# NOTE: f.truncate(0) would prepend zero-bytes
f.seek(0)
f.truncate()
else:
writer.writerows(rows)
if file is None:
if encoding is not None:
f = f.buffer
result = f.getvalue()
if hasattr(file, 'write') and encoding is not None:
f.detach()
return result
| (file, rows, header=None, dialect='excel', encoding='utf-8', autocompress=False) |
723,854 | csv23.writers | writer | CSV writer for rows where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: File-like object (in binary mode if ``encoding`` is given).
dialect: Dialect argument for the underlying :func:`py:csv.writer`.
encoding: If not ``False`` (default): name of the encoding used to
encode the output lines.
\**fmtparams: Keyword arguments (formatting parameters) for the
underlying :func:`py:csv.writer`.
Returns:
A Python 3 :func:`py3:csv.writer` stand-in taking a list of :func:`py:unicode` strings
(PY3: :class:`py3:str`) for each row.
>>> import io
>>> with io.StringIO(newline='') as f: # doctest: +SKIP
... w = writer(f)
... w.writerow([u'Wonderful Spam', u'Lovely Spam'])
... w.writerow([u'Spam!', u'Spam!', u'Spam!'])
... f.getvalue()
u'Spam!,Spam!,Spam!\r\nWonderful Spam,Lovely Spam\r\n'
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
| def writer(stream, dialect=DIALECT, encoding=False, **fmtparams):
r"""CSV writer for rows where string values are :func:`py:unicode` strings (PY3: :class:`py3:str`).
Args:
stream: File-like object (in binary mode if ``encoding`` is given).
dialect: Dialect argument for the underlying :func:`py:csv.writer`.
encoding: If not ``False`` (default): name of the encoding used to
encode the output lines.
\**fmtparams: Keyword arguments (formatting parameters) for the
underlying :func:`py:csv.writer`.
Returns:
A Python 3 :func:`py3:csv.writer` stand-in taking a list of :func:`py:unicode` strings
(PY3: :class:`py3:str`) for each row.
>>> import io
>>> with io.StringIO(newline='') as f: # doctest: +SKIP
... w = writer(f)
... w.writerow([u'Wonderful Spam', u'Lovely Spam'])
... w.writerow([u'Spam!', u'Spam!', u'Spam!'])
... f.getvalue()
u'Spam!,Spam!,Spam!\r\nWonderful Spam,Lovely Spam\r\n'
Raises:
NotImplementedError: If ``encoding`` is not 8-bit clean.
"""
if encoding is False:
return UnicodeTextWriter(stream, dialect, **fmtparams)
if encoding is None:
encoding = none_encoding()
if not is_8bit_clean(encoding):
raise NotImplementedError
return UnicodeBytesWriter(stream, dialect, encoding, **fmtparams)
| (stream, dialect='excel', encoding=False, **fmtparams) |
723,856 | paginate | Page | A list/iterator representing the items on one page of a larger collection.
An instance of the "Page" class is created from a _collection_ which is any
list-like object that allows random access to its elements.
The instance works as an iterator running from the first item to the last item on the given
page. The Page.pager() method creates a link list allowing the user to go to other pages.
A "Page" does not only carry the items on a certain page. It gives you additional information
about the page in these "Page" object attributes:
item_count
Number of items in the collection
**WARNING:** Unless you pass in an item_count, a count will be
performed on the collection every time a Page instance is created.
page
Number of the current page
items_per_page
Maximal number of items displayed on a page
first_page
Number of the first page - usually 1 :)
last_page
Number of the last page
previous_page
Number of the previous page. If this is the first page it returns None.
next_page
Number of the next page. If this is the first page it returns None.
page_count
Number of pages
items
Sequence/iterator of items on the current page
first_item
Index of first item on the current page - starts with 1
last_item
Index of last item on the current page
| class Page(list):
"""A list/iterator representing the items on one page of a larger collection.
An instance of the "Page" class is created from a _collection_ which is any
list-like object that allows random access to its elements.
The instance works as an iterator running from the first item to the last item on the given
page. The Page.pager() method creates a link list allowing the user to go to other pages.
A "Page" does not only carry the items on a certain page. It gives you additional information
about the page in these "Page" object attributes:
item_count
Number of items in the collection
**WARNING:** Unless you pass in an item_count, a count will be
performed on the collection every time a Page instance is created.
page
Number of the current page
items_per_page
Maximal number of items displayed on a page
first_page
Number of the first page - usually 1 :)
last_page
Number of the last page
previous_page
Number of the previous page. If this is the first page it returns None.
next_page
Number of the next page. If this is the first page it returns None.
page_count
Number of pages
items
Sequence/iterator of items on the current page
first_item
Index of first item on the current page - starts with 1
last_item
Index of last item on the current page
"""
def __init__(self, collection, page=1, items_per_page=20, item_count=None,
wrapper_class=None, url_maker=None, **kwargs):
"""Create a "Page" instance.
Parameters:
collection
Sequence representing the collection of items to page through.
page
The requested page number - starts with 1. Default: 1.
items_per_page
The maximal number of items to be displayed per page.
Default: 20.
item_count (optional)
The total number of items in the collection - if known.
If this parameter is not given then the paginator will count
the number of elements in the collection every time a "Page"
is created. Giving this parameter will speed up things. In a busy
real-life application you may want to cache the number of items.
url_maker (optional)
Callback to generate the URL of other pages, given its numbers.
Must accept one int parameter and return a URI string.
"""
if collection is not None:
if wrapper_class is None:
# Default case. The collection is already a list-type object.
self.collection = collection
else:
# Special case. A custom wrapper class is used to access elements of the collection.
self.collection = wrapper_class(collection)
else:
self.collection = []
self.collection_type = type(collection)
if url_maker is not None:
self.url_maker = url_maker
else:
self.url_maker = self._default_url_maker
# Assign kwargs to self
self.kwargs = kwargs
# The self.page is the number of the current page.
# The first page has the number 1!
try:
self.page = int(page) # make it int() if we get it as a string
except (ValueError, TypeError):
self.page = 1
# normally page should be always at least 1 but the original maintainer
# decided that for empty collection and empty page it can be...0? (based on tests)
# preserving behavior for BW compat
if self.page < 1:
self.page = 1
self.items_per_page = items_per_page
# We subclassed "list" so we need to call its init() method
# and fill the new list with the items to be displayed on the page.
# We use list() so that the items on the current page are retrieved
# only once. In an SQL context that could otherwise lead to running the
# same SQL query every time items would be accessed.
# We do this here, prior to calling len() on the collection so that a
# wrapper class can execute a query with the knowledge of what the
# slice will be (for efficiency) and, in the same query, ask for the
# total number of items and only execute one query.
try:
first = (self.page - 1) * items_per_page
last = first + items_per_page
self.items = list(self.collection[first:last])
except TypeError:
raise TypeError("Your collection of type {} cannot be handled "
"by paginate.".format(type(self.collection)))
# Unless the user tells us how many items the collections has
# we calculate that ourselves.
if item_count is not None:
self.item_count = item_count
else:
self.item_count = len(self.collection)
# Compute the number of the first and last available page
if self.item_count > 0:
self.first_page = 1
self.page_count = ((self.item_count - 1) // self.items_per_page) + 1
self.last_page = self.first_page + self.page_count - 1
# Make sure that the requested page number is the range of valid pages
if self.page > self.last_page:
self.page = self.last_page
elif self.page < self.first_page:
self.page = self.first_page
# Note: the number of items on this page can be less than
# items_per_page if the last page is not full
self.first_item = (self.page - 1) * items_per_page + 1
self.last_item = min(self.first_item + items_per_page - 1, self.item_count)
# Links to previous and next page
if self.page > self.first_page:
self.previous_page = self.page-1
else:
self.previous_page = None
if self.page < self.last_page:
self.next_page = self.page+1
else:
self.next_page = None
# No items available
else:
self.first_page = None
self.page_count = 0
self.last_page = None
self.first_item = None
self.last_item = None
self.previous_page = None
self.next_page = None
self.items = []
# This is a subclass of the 'list' type. Initialise the list now.
list.__init__(self, self.items)
def __str__(self):
return ("Page:\n"
"Collection type: {0.collection_type}\n"
"Current page: {0.page}\n"
"First item: {0.first_item}\n"
"Last item: {0.last_item}\n"
"First page: {0.first_page}\n"
"Last page: {0.last_page}\n"
"Previous page: {0.previous_page}\n"
"Next page: {0.next_page}\n"
"Items per page: {0.items_per_page}\n"
"Total number of items: {0.item_count}\n"
"Number of pages: {0.page_count}\n"
).format(self)
def __repr__(self):
return("<paginate.Page: Page {0}/{1}>".format(self.page, self.page_count))
def pager(self, format='~2~', url=None, show_if_single_page=False, separator=' ',
symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>',
link_attr=dict(), curpage_attr=dict(), dotdot_attr=dict(), link_tag=None):
"""
Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50').
format:
Format string that defines how the pager is rendered. The string
can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
link_tag (optional)
A callable that accepts single argument `page` (page link information)
and generates string with html that represents the link for specific page.
Page objects are supplied from `link_map()` so the keys are the same.
"""
self.curpage_attr = curpage_attr
self.separator = separator
self.link_attr = link_attr
self.dotdot_attr = dotdot_attr
self.url = url
self.link_tag = link_tag or self.default_link_tag
# Don't show navigator if there is no more than one page
if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
return ''
regex_res = re.search(r'~(\d+)~', format)
if regex_res:
radius = regex_res.group(1)
else:
radius = 2
radius = int(radius)
self.radius = radius
link_map = self.link_map(
format=format, url=url, show_if_single_page=show_if_single_page, separator=separator,
symbol_first=symbol_first, symbol_last=symbol_last, symbol_previous=symbol_previous,
symbol_next=symbol_next, link_attr=link_attr, curpage_attr=curpage_attr, dotdot_attr=dotdot_attr
)
links_markup = self._range(link_map, radius)
# Replace ~...~ in token format by range of pages
result = re.sub(r'~(\d+)~', links_markup, format)
# Interpolate '$' variables
result = Template(result).safe_substitute({
'first_page': self.first_page,
'last_page': self.last_page,
'page': self.page,
'page_count': self.page_count,
'items_per_page': self.items_per_page,
'first_item': self.first_item,
'last_item': self.last_item,
'item_count': self.item_count,
'link_first': self.page>self.first_page and self.link_tag(link_map['first_page']) or '',
'link_last': self.page<self.last_page and self.link_tag(link_map['last_page']) or '',
'link_previous': self.previous_page and self.link_tag(link_map['previous_page']) or '',
'link_next': self.next_page and self.link_tag(link_map['next_page']) or ''
})
return result
def link_map(self, format='~2~', url=None, show_if_single_page=False, separator=' ',
symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>',
link_attr=dict(), curpage_attr=dict(), dotdot_attr=dict()):
""" Return map with links to other pages if default pager() function is not suitable solution.
format:
Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager()
method, but returns a simple dictionary in form of:
{'current_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'value': 1},
'first_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'first_page',
'value': 1},
'last_page': {'attrs': {},
'href': 'http://example.org/foo/page=8',
'type': 'last_page',
'value': 8},
'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2},
'previous_page': None,
'range_pages': [{'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'current_page',
'value': 1},
....
{'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]}
The string can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
"""
self.curpage_attr = curpage_attr
self.separator = separator
self.link_attr = link_attr
self.dotdot_attr = dotdot_attr
self.url = url
regex_res = re.search(r'~(\d+)~', format)
if regex_res:
radius = regex_res.group(1)
else:
radius = 2
radius = int(radius)
self.radius = radius
# Compute the first and last page number within the radius
# e.g. '1 .. 5 6 [7] 8 9 .. 12'
# -> leftmost_page = 5
# -> rightmost_page = 9
leftmost_page = max(self.first_page, (self.page-radius)) if \
self.first_page else None
rightmost_page = min(self.last_page, (self.page+radius)) if \
self.last_page else None
nav_items = {
"first_page": None,
"last_page": None,
"previous_page": None,
"next_page": None,
"current_page": None,
"radius": self.radius,
"range_pages": []
}
if leftmost_page is None or rightmost_page is None:
return nav_items
nav_items["first_page"] = {"type": "first_page", "value": unicode(symbol_first), "attrs": self.link_attr,
"number": self.first_page, "href": self.url_maker(self.first_page)}
# Insert dots if there are pages between the first page
# and the currently displayed page range
if leftmost_page - self.first_page > 1:
# Wrap in a SPAN tag if dotdot_attr is set
nav_items["range_pages"].append({"type": "span", "value": '..', "attrs": self.dotdot_attr, "href": "",
"number": None})
for thispage in range(leftmost_page, rightmost_page+1):
# Highlight the current page number and do not use a link
if thispage == self.page:
# Wrap in a SPAN tag if curpage_attr is set
nav_items["range_pages"].append({"type": "current_page", "value": unicode(thispage), "number": thispage,
"attrs": self.curpage_attr, "href": self.url_maker(thispage)})
nav_items["current_page"] = {"value": thispage, "attrs": self.curpage_attr,
"type": "current_page", "href": self.url_maker(thispage)}
# Otherwise create just a link to that page
else:
nav_items["range_pages"].append({"type": "page", "value": unicode(thispage), "number": thispage,
"attrs": self.link_attr, "href": self.url_maker(thispage)})
# Insert dots if there are pages between the displayed
# page numbers and the end of the page range
if self.last_page - rightmost_page > 1:
# Wrap in a SPAN tag if dotdot_attr is set
nav_items["range_pages"].append({"type": "span", "value": '..', "attrs": self.dotdot_attr, "href": "",
"number":None})
# Create a link to the very last page (unless we are on the last
# page or there would be no need to insert '..' spacers)
nav_items["last_page"] = {"type": "last_page", "value": unicode(symbol_last), "attrs": self.link_attr,
"href": self.url_maker(self.last_page), "number":self.last_page}
nav_items["previous_page"] = {"type": "previous_page", "value": unicode(symbol_previous),
"attrs": self.link_attr, "number": self.previous_page or self.first_page,
"href": self.url_maker(self.previous_page or self.first_page)}
nav_items["next_page"] = {"type": "next_page", "value": unicode(symbol_next),
"attrs": self.link_attr, "number": self.next_page or self.last_page,
"href": self.url_maker(self.next_page or self.last_page)}
return nav_items
def _range(self, link_map, radius):
"""
Return range of linked pages to substiture placeholder in pattern
"""
leftmost_page = max(self.first_page, (self.page-radius))
rightmost_page = min(self.last_page, (self.page+radius))
nav_items = []
# Create a link to the first page (unless we are on the first page
# or there would be no need to insert '..' spacers)
if self.page != self.first_page and self.first_page < leftmost_page:
page = link_map['first_page'].copy()
page['value'] = unicode(page['number'])
nav_items.append(self.link_tag(page))
for item in link_map['range_pages']:
nav_items.append(self.link_tag(item))
# Create a link to the very last page (unless we are on the last
# page or there would be no need to insert '..' spacers)
if self.page != self.last_page and rightmost_page < self.last_page:
page = link_map['last_page'].copy()
page['value'] = unicode(page['number'])
nav_items.append(self.link_tag(page))
return self.separator.join(nav_items)
def _default_url_maker(self, page_number):
if self.url is None:
raise Exception(
"You need to specify a 'url' parameter containing a '$page' placeholder.")
if "$page" not in self.url:
raise Exception("The 'url' parameter must contain a '$page' placeholder.")
return self.url.replace('$page', unicode(page_number))
@staticmethod
def default_link_tag(item):
"""
Create an A-HREF tag that points to another page.
"""
text = item['value']
target_url = item['href']
if not item['href'] or item['type'] in ('span', 'current_page'):
if item['attrs']:
text = make_html_tag('span', **item['attrs']) + text + '</span>'
return text
return make_html_tag('a', text=text, href=target_url, **item['attrs'])
| (collection, page=1, items_per_page=20, item_count=None, wrapper_class=None, url_maker=None, **kwargs) |
723,857 | paginate | __init__ | Create a "Page" instance.
Parameters:
collection
Sequence representing the collection of items to page through.
page
The requested page number - starts with 1. Default: 1.
items_per_page
The maximal number of items to be displayed per page.
Default: 20.
item_count (optional)
The total number of items in the collection - if known.
If this parameter is not given then the paginator will count
the number of elements in the collection every time a "Page"
is created. Giving this parameter will speed up things. In a busy
real-life application you may want to cache the number of items.
url_maker (optional)
Callback to generate the URL of other pages, given its numbers.
Must accept one int parameter and return a URI string.
| def __init__(self, collection, page=1, items_per_page=20, item_count=None,
wrapper_class=None, url_maker=None, **kwargs):
"""Create a "Page" instance.
Parameters:
collection
Sequence representing the collection of items to page through.
page
The requested page number - starts with 1. Default: 1.
items_per_page
The maximal number of items to be displayed per page.
Default: 20.
item_count (optional)
The total number of items in the collection - if known.
If this parameter is not given then the paginator will count
the number of elements in the collection every time a "Page"
is created. Giving this parameter will speed up things. In a busy
real-life application you may want to cache the number of items.
url_maker (optional)
Callback to generate the URL of other pages, given its numbers.
Must accept one int parameter and return a URI string.
"""
if collection is not None:
if wrapper_class is None:
# Default case. The collection is already a list-type object.
self.collection = collection
else:
# Special case. A custom wrapper class is used to access elements of the collection.
self.collection = wrapper_class(collection)
else:
self.collection = []
self.collection_type = type(collection)
if url_maker is not None:
self.url_maker = url_maker
else:
self.url_maker = self._default_url_maker
# Assign kwargs to self
self.kwargs = kwargs
# The self.page is the number of the current page.
# The first page has the number 1!
try:
self.page = int(page) # make it int() if we get it as a string
except (ValueError, TypeError):
self.page = 1
# normally page should be always at least 1 but the original maintainer
# decided that for empty collection and empty page it can be...0? (based on tests)
# preserving behavior for BW compat
if self.page < 1:
self.page = 1
self.items_per_page = items_per_page
# We subclassed "list" so we need to call its init() method
# and fill the new list with the items to be displayed on the page.
# We use list() so that the items on the current page are retrieved
# only once. In an SQL context that could otherwise lead to running the
# same SQL query every time items would be accessed.
# We do this here, prior to calling len() on the collection so that a
# wrapper class can execute a query with the knowledge of what the
# slice will be (for efficiency) and, in the same query, ask for the
# total number of items and only execute one query.
try:
first = (self.page - 1) * items_per_page
last = first + items_per_page
self.items = list(self.collection[first:last])
except TypeError:
raise TypeError("Your collection of type {} cannot be handled "
"by paginate.".format(type(self.collection)))
# Unless the user tells us how many items the collections has
# we calculate that ourselves.
if item_count is not None:
self.item_count = item_count
else:
self.item_count = len(self.collection)
# Compute the number of the first and last available page
if self.item_count > 0:
self.first_page = 1
self.page_count = ((self.item_count - 1) // self.items_per_page) + 1
self.last_page = self.first_page + self.page_count - 1
# Make sure that the requested page number is the range of valid pages
if self.page > self.last_page:
self.page = self.last_page
elif self.page < self.first_page:
self.page = self.first_page
# Note: the number of items on this page can be less than
# items_per_page if the last page is not full
self.first_item = (self.page - 1) * items_per_page + 1
self.last_item = min(self.first_item + items_per_page - 1, self.item_count)
# Links to previous and next page
if self.page > self.first_page:
self.previous_page = self.page-1
else:
self.previous_page = None
if self.page < self.last_page:
self.next_page = self.page+1
else:
self.next_page = None
# No items available
else:
self.first_page = None
self.page_count = 0
self.last_page = None
self.first_item = None
self.last_item = None
self.previous_page = None
self.next_page = None
self.items = []
# This is a subclass of the 'list' type. Initialise the list now.
list.__init__(self, self.items)
| (self, collection, page=1, items_per_page=20, item_count=None, wrapper_class=None, url_maker=None, **kwargs) |
723,858 | paginate | __repr__ | null | def __repr__(self):
return("<paginate.Page: Page {0}/{1}>".format(self.page, self.page_count))
| (self) |
723,859 | paginate | __str__ | null | def __str__(self):
return ("Page:\n"
"Collection type: {0.collection_type}\n"
"Current page: {0.page}\n"
"First item: {0.first_item}\n"
"Last item: {0.last_item}\n"
"First page: {0.first_page}\n"
"Last page: {0.last_page}\n"
"Previous page: {0.previous_page}\n"
"Next page: {0.next_page}\n"
"Items per page: {0.items_per_page}\n"
"Total number of items: {0.item_count}\n"
"Number of pages: {0.page_count}\n"
).format(self)
| (self) |
723,860 | paginate | _default_url_maker | null | def _default_url_maker(self, page_number):
if self.url is None:
raise Exception(
"You need to specify a 'url' parameter containing a '$page' placeholder.")
if "$page" not in self.url:
raise Exception("The 'url' parameter must contain a '$page' placeholder.")
return self.url.replace('$page', unicode(page_number))
| (self, page_number) |
723,861 | paginate | _range |
Return range of linked pages to substiture placeholder in pattern
| def _range(self, link_map, radius):
"""
Return range of linked pages to substiture placeholder in pattern
"""
leftmost_page = max(self.first_page, (self.page-radius))
rightmost_page = min(self.last_page, (self.page+radius))
nav_items = []
# Create a link to the first page (unless we are on the first page
# or there would be no need to insert '..' spacers)
if self.page != self.first_page and self.first_page < leftmost_page:
page = link_map['first_page'].copy()
page['value'] = unicode(page['number'])
nav_items.append(self.link_tag(page))
for item in link_map['range_pages']:
nav_items.append(self.link_tag(item))
# Create a link to the very last page (unless we are on the last
# page or there would be no need to insert '..' spacers)
if self.page != self.last_page and rightmost_page < self.last_page:
page = link_map['last_page'].copy()
page['value'] = unicode(page['number'])
nav_items.append(self.link_tag(page))
return self.separator.join(nav_items)
| (self, link_map, radius) |
723,862 | paginate | default_link_tag |
Create an A-HREF tag that points to another page.
| @staticmethod
def default_link_tag(item):
"""
Create an A-HREF tag that points to another page.
"""
text = item['value']
target_url = item['href']
if not item['href'] or item['type'] in ('span', 'current_page'):
if item['attrs']:
text = make_html_tag('span', **item['attrs']) + text + '</span>'
return text
return make_html_tag('a', text=text, href=target_url, **item['attrs'])
| (item) |
723,863 | paginate | link_map | Return map with links to other pages if default pager() function is not suitable solution.
format:
Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager()
method, but returns a simple dictionary in form of:
{'current_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'value': 1},
'first_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'first_page',
'value': 1},
'last_page': {'attrs': {},
'href': 'http://example.org/foo/page=8',
'type': 'last_page',
'value': 8},
'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2},
'previous_page': None,
'range_pages': [{'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'current_page',
'value': 1},
....
{'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]}
The string can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
| def link_map(self, format='~2~', url=None, show_if_single_page=False, separator=' ',
symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>',
link_attr=dict(), curpage_attr=dict(), dotdot_attr=dict()):
""" Return map with links to other pages if default pager() function is not suitable solution.
format:
Format string that defines how the pager would be normally rendered rendered. Uses same arguments as pager()
method, but returns a simple dictionary in form of:
{'current_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'value': 1},
'first_page': {'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'first_page',
'value': 1},
'last_page': {'attrs': {},
'href': 'http://example.org/foo/page=8',
'type': 'last_page',
'value': 8},
'next_page': {'attrs': {}, 'href': 'HREF', 'type': 'next_page', 'value': 2},
'previous_page': None,
'range_pages': [{'attrs': {},
'href': 'http://example.org/foo/page=1',
'type': 'current_page',
'value': 1},
....
{'attrs': {}, 'href': '', 'type': 'span', 'value': '..'}]}
The string can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
"""
self.curpage_attr = curpage_attr
self.separator = separator
self.link_attr = link_attr
self.dotdot_attr = dotdot_attr
self.url = url
regex_res = re.search(r'~(\d+)~', format)
if regex_res:
radius = regex_res.group(1)
else:
radius = 2
radius = int(radius)
self.radius = radius
# Compute the first and last page number within the radius
# e.g. '1 .. 5 6 [7] 8 9 .. 12'
# -> leftmost_page = 5
# -> rightmost_page = 9
leftmost_page = max(self.first_page, (self.page-radius)) if \
self.first_page else None
rightmost_page = min(self.last_page, (self.page+radius)) if \
self.last_page else None
nav_items = {
"first_page": None,
"last_page": None,
"previous_page": None,
"next_page": None,
"current_page": None,
"radius": self.radius,
"range_pages": []
}
if leftmost_page is None or rightmost_page is None:
return nav_items
nav_items["first_page"] = {"type": "first_page", "value": unicode(symbol_first), "attrs": self.link_attr,
"number": self.first_page, "href": self.url_maker(self.first_page)}
# Insert dots if there are pages between the first page
# and the currently displayed page range
if leftmost_page - self.first_page > 1:
# Wrap in a SPAN tag if dotdot_attr is set
nav_items["range_pages"].append({"type": "span", "value": '..', "attrs": self.dotdot_attr, "href": "",
"number": None})
for thispage in range(leftmost_page, rightmost_page+1):
# Highlight the current page number and do not use a link
if thispage == self.page:
# Wrap in a SPAN tag if curpage_attr is set
nav_items["range_pages"].append({"type": "current_page", "value": unicode(thispage), "number": thispage,
"attrs": self.curpage_attr, "href": self.url_maker(thispage)})
nav_items["current_page"] = {"value": thispage, "attrs": self.curpage_attr,
"type": "current_page", "href": self.url_maker(thispage)}
# Otherwise create just a link to that page
else:
nav_items["range_pages"].append({"type": "page", "value": unicode(thispage), "number": thispage,
"attrs": self.link_attr, "href": self.url_maker(thispage)})
# Insert dots if there are pages between the displayed
# page numbers and the end of the page range
if self.last_page - rightmost_page > 1:
# Wrap in a SPAN tag if dotdot_attr is set
nav_items["range_pages"].append({"type": "span", "value": '..', "attrs": self.dotdot_attr, "href": "",
"number":None})
# Create a link to the very last page (unless we are on the last
# page or there would be no need to insert '..' spacers)
nav_items["last_page"] = {"type": "last_page", "value": unicode(symbol_last), "attrs": self.link_attr,
"href": self.url_maker(self.last_page), "number":self.last_page}
nav_items["previous_page"] = {"type": "previous_page", "value": unicode(symbol_previous),
"attrs": self.link_attr, "number": self.previous_page or self.first_page,
"href": self.url_maker(self.previous_page or self.first_page)}
nav_items["next_page"] = {"type": "next_page", "value": unicode(symbol_next),
"attrs": self.link_attr, "number": self.next_page or self.last_page,
"href": self.url_maker(self.next_page or self.last_page)}
return nav_items
| (self, format='~2~', url=None, show_if_single_page=False, separator=' ', symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>', link_attr={}, curpage_attr={}, dotdot_attr={}) |
723,864 | paginate | pager |
Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50').
format:
Format string that defines how the pager is rendered. The string
can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
link_tag (optional)
A callable that accepts single argument `page` (page link information)
and generates string with html that represents the link for specific page.
Page objects are supplied from `link_map()` so the keys are the same.
| def pager(self, format='~2~', url=None, show_if_single_page=False, separator=' ',
symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>',
link_attr=dict(), curpage_attr=dict(), dotdot_attr=dict(), link_tag=None):
"""
Return string with links to other pages (e.g. '1 .. 5 6 7 [8] 9 10 11 .. 50').
format:
Format string that defines how the pager is rendered. The string
can contain the following $-tokens that are substituted by the
string.Template module:
- $first_page: number of first reachable page
- $last_page: number of last reachable page
- $page: number of currently selected page
- $page_count: number of reachable pages
- $items_per_page: maximal number of items per page
- $first_item: index of first item on the current page
- $last_item: index of last item on the current page
- $item_count: total number of items
- $link_first: link to first page (unless this is first page)
- $link_last: link to last page (unless this is last page)
- $link_previous: link to previous page (unless this is first page)
- $link_next: link to next page (unless this is last page)
To render a range of pages the token '~3~' can be used. The
number sets the radius of pages around the current page.
Example for a range with radius 3:
'1 .. 5 6 7 [8] 9 10 11 .. 50'
Default: '~2~'
url
The URL that page links will point to. Make sure it contains the string
$page which will be replaced by the actual page number.
Must be given unless a url_maker is specified to __init__, in which
case this parameter is ignored.
symbol_first
String to be displayed as the text for the $link_first link above.
Default: '<<' (<<)
symbol_last
String to be displayed as the text for the $link_last link above.
Default: '>>' (>>)
symbol_previous
String to be displayed as the text for the $link_previous link above.
Default: '<' (<)
symbol_next
String to be displayed as the text for the $link_next link above.
Default: '>' (>)
separator:
String that is used to separate page links/numbers in the above range of pages.
Default: ' '
show_if_single_page:
if True the navigator will be shown even if there is only one page.
Default: False
link_attr (optional)
A dictionary of attributes that get added to A-HREF links pointing to other pages. Can
be used to define a CSS style or class to customize the look of links.
Example: { 'style':'border: 1px solid green' }
Example: { 'class':'pager_link' }
curpage_attr (optional)
A dictionary of attributes that get added to the current page number in the pager (which
is obviously not a link). If this dictionary is not empty then the elements will be
wrapped in a SPAN tag with the given attributes.
Example: { 'style':'border: 3px solid blue' }
Example: { 'class':'pager_curpage' }
dotdot_attr (optional)
A dictionary of attributes that get added to the '..' string in the pager (which is
obviously not a link). If this dictionary is not empty then the elements will be wrapped
in a SPAN tag with the given attributes.
Example: { 'style':'color: #808080' }
Example: { 'class':'pager_dotdot' }
link_tag (optional)
A callable that accepts single argument `page` (page link information)
and generates string with html that represents the link for specific page.
Page objects are supplied from `link_map()` so the keys are the same.
"""
self.curpage_attr = curpage_attr
self.separator = separator
self.link_attr = link_attr
self.dotdot_attr = dotdot_attr
self.url = url
self.link_tag = link_tag or self.default_link_tag
# Don't show navigator if there is no more than one page
if self.page_count == 0 or (self.page_count == 1 and not show_if_single_page):
return ''
regex_res = re.search(r'~(\d+)~', format)
if regex_res:
radius = regex_res.group(1)
else:
radius = 2
radius = int(radius)
self.radius = radius
link_map = self.link_map(
format=format, url=url, show_if_single_page=show_if_single_page, separator=separator,
symbol_first=symbol_first, symbol_last=symbol_last, symbol_previous=symbol_previous,
symbol_next=symbol_next, link_attr=link_attr, curpage_attr=curpage_attr, dotdot_attr=dotdot_attr
)
links_markup = self._range(link_map, radius)
# Replace ~...~ in token format by range of pages
result = re.sub(r'~(\d+)~', links_markup, format)
# Interpolate '$' variables
result = Template(result).safe_substitute({
'first_page': self.first_page,
'last_page': self.last_page,
'page': self.page,
'page_count': self.page_count,
'items_per_page': self.items_per_page,
'first_item': self.first_item,
'last_item': self.last_item,
'item_count': self.item_count,
'link_first': self.page>self.first_page and self.link_tag(link_map['first_page']) or '',
'link_last': self.page<self.last_page and self.link_tag(link_map['last_page']) or '',
'link_previous': self.previous_page and self.link_tag(link_map['previous_page']) or '',
'link_next': self.next_page and self.link_tag(link_map['next_page']) or ''
})
return result
| (self, format='~2~', url=None, show_if_single_page=False, separator=' ', symbol_first='<<', symbol_last='>>', symbol_previous='<', symbol_next='>', link_attr={}, curpage_attr={}, dotdot_attr={}, link_tag=None) |
723,870 | paginate | make_html_tag | Create an HTML tag string.
tag
The HTML tag to use (e.g. 'a', 'span' or 'div')
text
The text to enclose between opening and closing tag. If no text is specified then only
the opening tag is returned.
Example::
make_html_tag('a', text="Hello", href="/another/page")
-> <a href="/another/page">Hello</a>
To use reserved Python keywords like "class" as a parameter prepend it with
an underscore. Instead of "class='green'" use "_class='green'".
Warning: Quotes and apostrophes are not escaped. | def make_html_tag(tag, text=None, **params):
"""Create an HTML tag string.
tag
The HTML tag to use (e.g. 'a', 'span' or 'div')
text
The text to enclose between opening and closing tag. If no text is specified then only
the opening tag is returned.
Example::
make_html_tag('a', text="Hello", href="/another/page")
-> <a href="/another/page">Hello</a>
To use reserved Python keywords like "class" as a parameter prepend it with
an underscore. Instead of "class='green'" use "_class='green'".
Warning: Quotes and apostrophes are not escaped."""
params_string = ''
# Parameters are passed. Turn the dict into a string like "a=1 b=2 c=3" string.
for key, value in sorted(params.items()):
# Strip off a leading underscore from the attribute's key to allow attributes like '_class'
# to be used as a CSS class specification instead of the reserved Python keyword 'class'.
key = key.lstrip('_')
params_string += u' {0}="{1}"'.format(key, value)
# Create the tag string
tag_string = u'<{0}{1}>'.format(tag, params_string)
# Add text and closing tag if required.
if text:
tag_string += u'{0}</{1}>'.format(text, tag)
return tag_string
| (tag, text=None, **params) |
723,874 | asgi_correlation_id.log_filters | CeleryTracingIdsFilter | null | class CeleryTracingIdsFilter(Filter):
def __init__(self, name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None):
super().__init__(name=name)
self.uuid_length = uuid_length
self.default_value = default_value
def filter(self, record: 'LogRecord') -> bool:
"""
Append a parent- and current ID to the log record.
The celery current ID is a unique ID generated for each new worker process.
The celery parent ID is the current ID of the worker process that spawned
the current process. If the worker process was spawned by a beat process
or from an endpoint, the parent ID will be None.
"""
pid = celery_parent_id.get(self.default_value)
record.celery_parent_id = _trim_string(pid, self.uuid_length)
cid = celery_current_id.get(self.default_value)
record.celery_current_id = _trim_string(cid, self.uuid_length)
return True
| (name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None) |
723,875 | asgi_correlation_id.log_filters | __init__ | null | def __init__(self, name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None):
super().__init__(name=name)
self.uuid_length = uuid_length
self.default_value = default_value
| (self, name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None) |
723,876 | asgi_correlation_id.log_filters | filter |
Append a parent- and current ID to the log record.
The celery current ID is a unique ID generated for each new worker process.
The celery parent ID is the current ID of the worker process that spawned
the current process. If the worker process was spawned by a beat process
or from an endpoint, the parent ID will be None.
| def filter(self, record: 'LogRecord') -> bool:
"""
Append a parent- and current ID to the log record.
The celery current ID is a unique ID generated for each new worker process.
The celery parent ID is the current ID of the worker process that spawned
the current process. If the worker process was spawned by a beat process
or from an endpoint, the parent ID will be None.
"""
pid = celery_parent_id.get(self.default_value)
record.celery_parent_id = _trim_string(pid, self.uuid_length)
cid = celery_current_id.get(self.default_value)
record.celery_current_id = _trim_string(cid, self.uuid_length)
return True
| (self, record: 'LogRecord') -> bool |
723,877 | asgi_correlation_id.log_filters | CorrelationIdFilter | Logging filter to attached correlation IDs to log records | class CorrelationIdFilter(Filter):
"""Logging filter to attached correlation IDs to log records"""
def __init__(self, name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None):
super().__init__(name=name)
self.uuid_length = uuid_length
self.default_value = default_value
def filter(self, record: 'LogRecord') -> bool:
"""
Attach a correlation ID to the log record.
Since the correlation ID is defined in the middleware layer, any
log generated from a request after this point can easily be searched
for, if the correlation ID is added to the message, or included as
metadata.
"""
cid = correlation_id.get(self.default_value)
record.correlation_id = _trim_string(cid, self.uuid_length)
return True
| (name: str = '', uuid_length: Optional[int] = None, default_value: Optional[str] = None) |
723,879 | asgi_correlation_id.log_filters | filter |
Attach a correlation ID to the log record.
Since the correlation ID is defined in the middleware layer, any
log generated from a request after this point can easily be searched
for, if the correlation ID is added to the message, or included as
metadata.
| def filter(self, record: 'LogRecord') -> bool:
"""
Attach a correlation ID to the log record.
Since the correlation ID is defined in the middleware layer, any
log generated from a request after this point can easily be searched
for, if the correlation ID is added to the message, or included as
metadata.
"""
cid = correlation_id.get(self.default_value)
record.correlation_id = _trim_string(cid, self.uuid_length)
return True
| (self, record: 'LogRecord') -> bool |
723,880 | asgi_correlation_id.middleware | CorrelationIdMiddleware | CorrelationIdMiddleware(app: 'ASGIApp', header_name: str = 'X-Request-ID', update_request_header: bool = True, generator: Callable[[], str] = <function CorrelationIdMiddleware.<lambda> at 0x7f6195f38a60>, validator: Optional[Callable[[str], bool]] = <function is_valid_uuid4 at 0x7f6196234040>, transformer: Optional[Callable[[str], str]] = <function CorrelationIdMiddleware.<lambda> at 0x7f6195f38af0>) | class CorrelationIdMiddleware:
app: 'ASGIApp'
header_name: str = 'X-Request-ID'
update_request_header: bool = True
# ID-generating callable
generator: Callable[[], str] = field(default=lambda: uuid4().hex)
# ID validator
validator: Optional[Callable[[str], bool]] = field(default=is_valid_uuid4)
# ID transformer - can be used to clean/mutate IDs
transformer: Optional[Callable[[str], str]] = field(default=lambda a: a)
async def __call__(self, scope: 'Scope', receive: 'Receive', send: 'Send') -> None:
"""
Load request ID from headers if present. Generate one otherwise.
"""
if scope['type'] not in ('http', 'websocket'):
await self.app(scope, receive, send)
return
# Try to load request ID from the request headers
headers = MutableHeaders(scope=scope)
header_value = headers.get(self.header_name.lower())
validation_failed = False
if not header_value:
# Generate request ID if none was found
id_value = self.generator()
elif self.validator and not self.validator(header_value):
# Also generate a request ID if one was found, but it was deemed invalid
validation_failed = True
id_value = self.generator()
else:
# Otherwise, use the found request ID
id_value = header_value
# Clean/change the ID if needed
if self.transformer:
id_value = self.transformer(id_value)
if validation_failed is True:
logger.warning(FAILED_VALIDATION_MESSAGE, id_value)
# Update the request headers if needed
if id_value != header_value and self.update_request_header is True:
headers[self.header_name] = id_value
correlation_id.set(id_value)
self.sentry_extension(id_value)
async def handle_outgoing_request(message: 'Message') -> None:
if message['type'] == 'http.response.start' and correlation_id.get():
headers = MutableHeaders(scope=message)
headers.append(self.header_name, correlation_id.get())
await send(message)
await self.app(scope, receive, handle_outgoing_request)
return
def __post_init__(self) -> None:
"""
Load extensions on initialization.
If Sentry is installed, propagate correlation IDs to Sentry events.
If Celery is installed, propagate correlation IDs to spawned worker processes.
"""
self.sentry_extension = get_sentry_extension()
try:
import celery # noqa: F401, TC002
from asgi_correlation_id.extensions.celery import load_correlation_ids
load_correlation_ids()
except ImportError: # pragma: no cover
pass
| (app: 'ASGIApp', header_name: str = 'X-Request-ID', update_request_header: bool = True, generator: Callable[[], str] = <function CorrelationIdMiddleware.<lambda> at 0x7f6195f38a60>, validator: Optional[Callable[[str], bool]] = <function is_valid_uuid4 at 0x7f6196234040>, transformer: Optional[Callable[[str], str]] = <function CorrelationIdMiddleware.<lambda> at 0x7f6195f38af0>) -> None |
723,881 | asgi_correlation_id.middleware | __call__ |
Load request ID from headers if present. Generate one otherwise.
| transformer: Optional[Callable[[str], str]] = field(default=lambda a: a)
| (self, scope: 'Scope', receive: 'Receive', send: 'Send') -> None |
723,882 | asgi_correlation_id.middleware | __eq__ | null | import logging
from dataclasses import dataclass, field
from typing import TYPE_CHECKING, Callable, Optional
from uuid import UUID, uuid4
from starlette.datastructures import MutableHeaders
from asgi_correlation_id.context import correlation_id
from asgi_correlation_id.extensions.sentry import get_sentry_extension
if TYPE_CHECKING:
from starlette.types import ASGIApp, Message, Receive, Scope, Send
logger = logging.getLogger('asgi_correlation_id')
def is_valid_uuid4(uuid_: str) -> bool:
"""
Check whether a string is a valid v4 uuid.
"""
try:
return bool(UUID(uuid_, version=4))
except ValueError:
return False
| (self, other) |
723,884 | asgi_correlation_id.middleware | __post_init__ |
Load extensions on initialization.
If Sentry is installed, propagate correlation IDs to Sentry events.
If Celery is installed, propagate correlation IDs to spawned worker processes.
| def __post_init__(self) -> None:
"""
Load extensions on initialization.
If Sentry is installed, propagate correlation IDs to Sentry events.
If Celery is installed, propagate correlation IDs to spawned worker processes.
"""
self.sentry_extension = get_sentry_extension()
try:
import celery # noqa: F401, TC002
from asgi_correlation_id.extensions.celery import load_correlation_ids
load_correlation_ids()
except ImportError: # pragma: no cover
pass
| (self) -> NoneType |
723,886 | asgi_correlation_id.middleware | <lambda> | null | generator: Callable[[], str] = field(default=lambda: uuid4().hex)
| () |
723,887 | asgi_correlation_id.middleware | <lambda> | null | transformer: Optional[Callable[[str], str]] = field(default=lambda a: a)
| (a) |
723,888 | asgi_correlation_id.middleware | is_valid_uuid4 |
Check whether a string is a valid v4 uuid.
| def is_valid_uuid4(uuid_: str) -> bool:
"""
Check whether a string is a valid v4 uuid.
"""
try:
return bool(UUID(uuid_, version=4))
except ValueError:
return False
| (uuid_: str) -> bool |
723,893 | fiscalyear | FiscalDate | A wrapper around the builtin datetime.date class
that provides the following attributes. | class FiscalDate(datetime.date, _FiscalMixin):
"""A wrapper around the builtin datetime.date class
that provides the following attributes."""
pass
| null |
723,894 | fiscalyear | FiscalDateTime | A wrapper around the builtin datetime.datetime class
that provides the following attributes. | class FiscalDateTime(datetime.datetime, _FiscalMixin):
"""A wrapper around the builtin datetime.datetime class
that provides the following attributes."""
pass
| null |
723,895 | fiscalyear | FiscalDay | A class representing a single fiscal day. | class FiscalDay(_Hashable):
"""A class representing a single fiscal day."""
__slots__ = ["_fiscal_year", "_fiscal_day"]
__hash__ = _Hashable.__hash__
_fiscal_year: int
_fiscal_day: int
def __new__(cls, fiscal_year: int, fiscal_day: int) -> "FiscalDay":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_day: The fiscal day
:returns: A newly constructed FiscalDay object
:raises ValueError: If fiscal_year or fiscal_day is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_day = _check_fiscal_day(fiscal_year, fiscal_day)
self = super(FiscalDay, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_day = fiscal_day
return self
@classmethod
def current(cls) -> "FiscalDay":
"""Alternative constructor. Returns the current FiscalDay.
:returns: A newly constructed FiscalDay object
"""
today = FiscalDate.today()
return cls(today.fiscal_year, today.fiscal_day)
def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> fd = FiscalDay(2017, 1)
>>> repr(fd)
'FiscalDay(2017, 1)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_day})"
def __str__(self) -> str:
"""Convert to informal string, for str().
>>> fd = FiscalDay(2017, 1)
>>> str(fd)
'FY2017 FD1'
"""
return f"FY{self._fiscal_year} FD{self._fiscal_day}"
# TODO: Implement __format__ so that you can print
# fiscal year as 17 or 2017 (%y or %Y)
def __contains__(
self, item: Union["FiscalDay", datetime.datetime, datetime.date]
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalDay):
return self == item
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
# Read-only field accessors
@property
def fiscal_year(self) -> int:
""":returns: The fiscal year"""
return self._fiscal_year
@property
def fiscal_quarter(self) -> int:
""":returns: The fiscal quarter"""
return self.start.fiscal_quarter
@property
def fiscal_month(self) -> int:
""":returns: The fiscal month"""
return self.start.fiscal_month
@property
def fiscal_day(self) -> int:
""":returns: The fiscal day"""
return self._fiscal_day
@property
def start(self) -> "FiscalDateTime":
""":returns: Start of the fiscal day"""
fiscal_year = FiscalYear(self._fiscal_year)
days_elapsed = datetime.timedelta(days=self._fiscal_day - 1)
start = fiscal_year.start + days_elapsed
return FiscalDateTime(start.year, start.month, start.day, 0, 0, 0)
@property
def end(self) -> "FiscalDateTime":
""":returns: End of the fiscal day"""
# Find the start of the next fiscal quarter
next_start = self.next_fiscal_day.start
# Substract 1 second
end = next_start - datetime.timedelta(seconds=1)
return FiscalDateTime(
end.year,
end.month,
end.day,
end.hour,
end.minute,
end.second,
end.microsecond,
end.tzinfo,
)
@property
def prev_fiscal_day(self) -> "FiscalDay":
""":returns: The previous fiscal day"""
fiscal_year = self._fiscal_year
fiscal_day = self._fiscal_day - 1
if fiscal_day == 0:
fiscal_year -= 1
try:
fiscal_day = _check_fiscal_day(fiscal_year, 366)
except ValueError:
fiscal_day = _check_fiscal_day(fiscal_year, 365)
return FiscalDay(fiscal_year, fiscal_day)
@property
def next_fiscal_day(self) -> "FiscalDay":
""":returns: The next fiscal day"""
fiscal_year = self._fiscal_year
try:
fiscal_day = _check_fiscal_day(fiscal_year, self._fiscal_day + 1)
except ValueError:
fiscal_year += 1
fiscal_day = 1
return FiscalDay(fiscal_year, fiscal_day)
# Comparisons of FiscalDay objects with other
def __lt__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) < (
other._fiscal_year,
other._fiscal_day,
)
def __le__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) <= (
other._fiscal_year,
other._fiscal_day,
)
def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalDay):
return (self._fiscal_year, self._fiscal_day) == (
other._fiscal_year,
other._fiscal_day,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalDay):
return (self._fiscal_year, self._fiscal_day) != (
other._fiscal_year,
other._fiscal_day,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __gt__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) > (
other._fiscal_year,
other._fiscal_day,
)
def __ge__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) >= (
other._fiscal_year,
other._fiscal_day,
)
| (fiscal_year: int, fiscal_day: int) -> 'FiscalDay' |
723,896 | fiscalyear | __contains__ | Returns True if item in self, else False.
:param item: The item to check
| def __contains__(
self, item: Union["FiscalDay", datetime.datetime, datetime.date]
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalDay):
return self == item
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
| (self, item: Union[fiscalyear.FiscalDay, datetime.datetime, datetime.date]) -> bool |
723,897 | fiscalyear | __eq__ | null | def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalDay):
return (self._fiscal_year, self._fiscal_day) == (
other._fiscal_year,
other._fiscal_day,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,898 | fiscalyear | __ge__ | null | def __ge__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) >= (
other._fiscal_year,
other._fiscal_day,
)
| (self, other: fiscalyear.FiscalDay) -> bool |
723,899 | fiscalyear | __gt__ | null | def __gt__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) > (
other._fiscal_year,
other._fiscal_day,
)
| (self, other: fiscalyear.FiscalDay) -> bool |
723,900 | fiscalyear | __hash__ | Unique hash of an object instance based on __slots__
:returns: a unique hash
| def __hash__(self) -> int:
"""Unique hash of an object instance based on __slots__
:returns: a unique hash
"""
return hash(tuple(map(lambda x: getattr(self, x), self.__slots__)))
| (self) -> int |
723,901 | fiscalyear | __le__ | null | def __le__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) <= (
other._fiscal_year,
other._fiscal_day,
)
| (self, other: fiscalyear.FiscalDay) -> bool |
723,902 | fiscalyear | __lt__ | null | def __lt__(self, other: "FiscalDay") -> bool:
return (self._fiscal_year, self._fiscal_day) < (
other._fiscal_year,
other._fiscal_day,
)
| (self, other: fiscalyear.FiscalDay) -> bool |
723,903 | fiscalyear | __ne__ | null | def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalDay):
return (self._fiscal_year, self._fiscal_day) != (
other._fiscal_year,
other._fiscal_day,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,904 | fiscalyear | __new__ | Constructor.
:param fiscal_year: The fiscal year
:param fiscal_day: The fiscal day
:returns: A newly constructed FiscalDay object
:raises ValueError: If fiscal_year or fiscal_day is out of range
| def __new__(cls, fiscal_year: int, fiscal_day: int) -> "FiscalDay":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_day: The fiscal day
:returns: A newly constructed FiscalDay object
:raises ValueError: If fiscal_year or fiscal_day is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_day = _check_fiscal_day(fiscal_year, fiscal_day)
self = super(FiscalDay, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_day = fiscal_day
return self
| (cls, fiscal_year: int, fiscal_day: int) -> fiscalyear.FiscalDay |
723,905 | fiscalyear | __repr__ | Convert to formal string, for repr().
>>> fd = FiscalDay(2017, 1)
>>> repr(fd)
'FiscalDay(2017, 1)'
| def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> fd = FiscalDay(2017, 1)
>>> repr(fd)
'FiscalDay(2017, 1)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_day})"
| (self) -> str |
723,906 | fiscalyear | __str__ | Convert to informal string, for str().
>>> fd = FiscalDay(2017, 1)
>>> str(fd)
'FY2017 FD1'
| def __str__(self) -> str:
"""Convert to informal string, for str().
>>> fd = FiscalDay(2017, 1)
>>> str(fd)
'FY2017 FD1'
"""
return f"FY{self._fiscal_year} FD{self._fiscal_day}"
| (self) -> str |
723,907 | fiscalyear | FiscalMonth | A class representing a single fiscal month. | class FiscalMonth(_Hashable):
"""A class representing a single fiscal month."""
__slots__ = ["_fiscal_year", "_fiscal_month"]
__hash__ = _Hashable.__hash__
_fiscal_year: int
_fiscal_month: int
def __new__(cls, fiscal_year: int, fiscal_month: int) -> "FiscalMonth":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_month: The fiscal month
:returns: A newly constructed FiscalMonth object
:raises ValueError: If fiscal_year or fiscal_month is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_month = _check_month(fiscal_month)
self = super(FiscalMonth, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_month = fiscal_month
return self
@classmethod
def current(cls) -> "FiscalMonth":
"""Alternative constructor. Returns the current FiscalMonth.
:returns: A newly constructed FiscalMonth object
"""
today = FiscalDate.today()
return cls(today.fiscal_year, today.fiscal_month)
def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> fm = FiscalMonth(2017, 1)
>>> repr(fm)
'FiscalMonth(2017, 1)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_month})"
def __str__(self) -> str:
"""Convert to informal string, for str().
>>> fm = FiscalMonth(2017, 1)
>>> str(fm)
'FY2017 FM1'
"""
return f"FY{self._fiscal_year} FM{self._fiscal_month}"
# TODO: Implement __format__ so that you can print
# fiscal year as 17 or 2017 (%y or %Y)
def __contains__(
self, item: Union["FiscalMonth", "FiscalDay", datetime.datetime, datetime.date]
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalMonth):
return self == item
elif isinstance(item, FiscalDay):
return self.start <= item.start <= item.end <= self.end
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
# Read-only field accessors
@property
def fiscal_year(self) -> int:
""":returns: The fiscal year"""
return self._fiscal_year
@property
def fiscal_month(self) -> int:
""":returns: The fiscal month"""
return self._fiscal_month
@property
def start(self) -> "FiscalDateTime":
""":returns: Start of the fiscal month"""
calendar_month = (START_MONTH + self._fiscal_month - 1) % 12
if calendar_month == 0:
calendar_month = 12
month_is_on_or_after_start_month = calendar_month >= START_MONTH
if START_YEAR == "previous":
if month_is_on_or_after_start_month:
calendar_year = self._fiscal_year - 1
else:
calendar_year = self._fiscal_year
elif START_YEAR == "same":
if month_is_on_or_after_start_month:
calendar_year = self._fiscal_year
else:
calendar_year = self._fiscal_year + 1
return FiscalDateTime(calendar_year, calendar_month, START_DAY)
@property
def end(self) -> "FiscalDateTime":
""":returns: End of the fiscal month"""
# Find the start of the next fiscal quarter
next_start = self.next_fiscal_month.start
# Substract 1 second
end = next_start - datetime.timedelta(seconds=1)
return FiscalDateTime(
end.year,
end.month,
end.day,
end.hour,
end.minute,
end.second,
end.microsecond,
end.tzinfo,
)
@property
def prev_fiscal_month(self) -> "FiscalMonth":
""":returns: The previous fiscal month"""
fiscal_year = self._fiscal_year
fiscal_month = self._fiscal_month - 1
if fiscal_month == 0:
fiscal_year -= 1
fiscal_month = 12
return FiscalMonth(fiscal_year, fiscal_month)
@property
def next_fiscal_month(self) -> "FiscalMonth":
""":returns: The next fiscal month"""
fiscal_year = self._fiscal_year
fiscal_month = self._fiscal_month + 1
if fiscal_month == 13:
fiscal_year += 1
fiscal_month = 1
return FiscalMonth(fiscal_year, fiscal_month)
# Comparisons of FiscalMonth objects with other
def __lt__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) < (
other._fiscal_year,
other._fiscal_month,
)
def __le__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) <= (
other._fiscal_year,
other._fiscal_month,
)
def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalMonth):
return (self._fiscal_year, self._fiscal_month) == (
other._fiscal_year,
other._fiscal_month,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalMonth):
return (self._fiscal_year, self._fiscal_month) != (
other._fiscal_year,
other._fiscal_month,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __gt__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) > (
other._fiscal_year,
other._fiscal_month,
)
def __ge__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) >= (
other._fiscal_year,
other._fiscal_month,
)
| (fiscal_year: int, fiscal_month: int) -> 'FiscalMonth' |
723,908 | fiscalyear | __contains__ | Returns True if item in self, else False.
:param item: The item to check
| def __contains__(
self, item: Union["FiscalMonth", "FiscalDay", datetime.datetime, datetime.date]
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalMonth):
return self == item
elif isinstance(item, FiscalDay):
return self.start <= item.start <= item.end <= self.end
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
| (self, item: Union[fiscalyear.FiscalMonth, fiscalyear.FiscalDay, datetime.datetime, datetime.date]) -> bool |
723,909 | fiscalyear | __eq__ | null | def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalMonth):
return (self._fiscal_year, self._fiscal_month) == (
other._fiscal_year,
other._fiscal_month,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,910 | fiscalyear | __ge__ | null | def __ge__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) >= (
other._fiscal_year,
other._fiscal_month,
)
| (self, other: fiscalyear.FiscalMonth) -> bool |
723,911 | fiscalyear | __gt__ | null | def __gt__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) > (
other._fiscal_year,
other._fiscal_month,
)
| (self, other: fiscalyear.FiscalMonth) -> bool |
723,913 | fiscalyear | __le__ | null | def __le__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) <= (
other._fiscal_year,
other._fiscal_month,
)
| (self, other: fiscalyear.FiscalMonth) -> bool |
723,914 | fiscalyear | __lt__ | null | def __lt__(self, other: "FiscalMonth") -> bool:
return (self._fiscal_year, self._fiscal_month) < (
other._fiscal_year,
other._fiscal_month,
)
| (self, other: fiscalyear.FiscalMonth) -> bool |
723,915 | fiscalyear | __ne__ | null | def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalMonth):
return (self._fiscal_year, self._fiscal_month) != (
other._fiscal_year,
other._fiscal_month,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,916 | fiscalyear | __new__ | Constructor.
:param fiscal_year: The fiscal year
:param fiscal_month: The fiscal month
:returns: A newly constructed FiscalMonth object
:raises ValueError: If fiscal_year or fiscal_month is out of range
| def __new__(cls, fiscal_year: int, fiscal_month: int) -> "FiscalMonth":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_month: The fiscal month
:returns: A newly constructed FiscalMonth object
:raises ValueError: If fiscal_year or fiscal_month is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_month = _check_month(fiscal_month)
self = super(FiscalMonth, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_month = fiscal_month
return self
| (cls, fiscal_year: int, fiscal_month: int) -> fiscalyear.FiscalMonth |
723,917 | fiscalyear | __repr__ | Convert to formal string, for repr().
>>> fm = FiscalMonth(2017, 1)
>>> repr(fm)
'FiscalMonth(2017, 1)'
| def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> fm = FiscalMonth(2017, 1)
>>> repr(fm)
'FiscalMonth(2017, 1)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_month})"
| (self) -> str |
723,918 | fiscalyear | __str__ | Convert to informal string, for str().
>>> fm = FiscalMonth(2017, 1)
>>> str(fm)
'FY2017 FM1'
| def __str__(self) -> str:
"""Convert to informal string, for str().
>>> fm = FiscalMonth(2017, 1)
>>> str(fm)
'FY2017 FM1'
"""
return f"FY{self._fiscal_year} FM{self._fiscal_month}"
| (self) -> str |
723,919 | fiscalyear | FiscalQuarter | A class representing a single fiscal quarter. | class FiscalQuarter(_Hashable):
"""A class representing a single fiscal quarter."""
__slots__ = ["_fiscal_year", "_fiscal_quarter"]
__hash__ = _Hashable.__hash__
_fiscal_year: int
_fiscal_quarter: int
def __new__(cls, fiscal_year: int, fiscal_quarter: int) -> "FiscalQuarter":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_quarter: The fiscal quarter
:returns: A newly constructed FiscalQuarter object
:raises ValueError: If fiscal_year or fiscal_quarter is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_quarter = _check_quarter(fiscal_quarter)
self = super(FiscalQuarter, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_quarter = fiscal_quarter
return self
@classmethod
def current(cls) -> "FiscalQuarter":
"""Alternative constructor. Returns the current FiscalQuarter.
:returns: A newly constructed FiscalQuarter object
"""
today = FiscalDate.today()
return cls(today.fiscal_year, today.fiscal_quarter)
def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> q3 = FiscalQuarter(2017, 3)
>>> repr(q3)
'FiscalQuarter(2017, 3)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_quarter})"
def __str__(self) -> str:
"""Convert to informal string, for str().
>>> q3 = FiscalQuarter(2017, 3)
>>> str(q3)
'FY2017 Q3'
"""
return f"FY{self._fiscal_year} Q{self._fiscal_quarter}"
# TODO: Implement __format__ so that you can print
# fiscal year as 17 or 2017 (%y or %Y)
def __contains__(
self,
item: Union[
"FiscalQuarter",
"FiscalMonth",
"FiscalDay",
datetime.datetime,
datetime.date,
],
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalQuarter):
return self == item
elif isinstance(item, (FiscalMonth, FiscalDay)):
return self.start <= item.start and item.end <= self.end
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
# Read-only field accessors
@property
def fiscal_year(self) -> int:
""":returns: The fiscal year"""
return self._fiscal_year
@property
def fiscal_quarter(self) -> int:
""":returns: The fiscal quarter"""
return self._fiscal_quarter
@property
def prev_fiscal_quarter(self) -> "FiscalQuarter":
""":returns: The previous fiscal quarter"""
fiscal_year = self._fiscal_year
fiscal_quarter = self._fiscal_quarter - 1
if fiscal_quarter == 0:
fiscal_year -= 1
fiscal_quarter = 4
return FiscalQuarter(fiscal_year, fiscal_quarter)
@property
def next_fiscal_quarter(self) -> "FiscalQuarter":
""":returns: The next fiscal quarter"""
fiscal_year = self._fiscal_year
fiscal_quarter = self._fiscal_quarter + 1
if fiscal_quarter == 5:
fiscal_year += 1
fiscal_quarter = 1
return FiscalQuarter(fiscal_year, fiscal_quarter)
@property
def start(self) -> "FiscalDateTime":
""":returns: The start of the fiscal quarter"""
# Find the first month of the fiscal quarter
month = START_MONTH
month += (self._fiscal_quarter - 1) * MONTHS_PER_QUARTER
month %= 12
if month == 0:
month = 12
# Find the calendar year of the start of the fiscal quarter
if START_YEAR == "previous":
year = self._fiscal_year - 1
elif START_YEAR == "same":
year = self._fiscal_year
else:
raise ValueError(
"START_YEAR must be either 'previous' or 'same'", START_YEAR
)
if month < START_MONTH:
year += 1
# Find the last day of the month
# If START_DAY is later, choose last day of month instead
max_day = calendar.monthrange(year, month)[1]
day = min(START_DAY, max_day)
return FiscalDateTime(year, month, day, 0, 0, 0)
@property
def end(self) -> "FiscalDateTime":
""":returns: The end of the fiscal quarter"""
# Find the start of the next fiscal quarter
next_start = self.next_fiscal_quarter.start
# Substract 1 second
end = next_start - datetime.timedelta(seconds=1)
return FiscalDateTime(
end.year,
end.month,
end.day,
end.hour,
end.minute,
end.second,
end.microsecond,
end.tzinfo,
)
# Comparisons of FiscalQuarter objects with other
def __lt__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) < (
other._fiscal_year,
other._fiscal_quarter,
)
def __le__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) <= (
other._fiscal_year,
other._fiscal_quarter,
)
def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalQuarter):
return (self._fiscal_year, self._fiscal_quarter) == (
other._fiscal_year,
other._fiscal_quarter,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalQuarter):
return (self._fiscal_year, self._fiscal_quarter) != (
other._fiscal_year,
other._fiscal_quarter,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __gt__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) > (
other._fiscal_year,
other._fiscal_quarter,
)
def __ge__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) >= (
other._fiscal_year,
other._fiscal_quarter,
)
| (fiscal_year: int, fiscal_quarter: int) -> 'FiscalQuarter' |
723,920 | fiscalyear | __contains__ | Returns True if item in self, else False.
:param item: The item to check
| def __contains__(
self,
item: Union[
"FiscalQuarter",
"FiscalMonth",
"FiscalDay",
datetime.datetime,
datetime.date,
],
) -> bool:
"""Returns True if item in self, else False.
:param item: The item to check
"""
if isinstance(item, FiscalQuarter):
return self == item
elif isinstance(item, (FiscalMonth, FiscalDay)):
return self.start <= item.start and item.end <= self.end
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
elif isinstance(item, datetime.date):
return self.start.date() <= item <= self.end.date()
| (self, item: Union[fiscalyear.FiscalQuarter, fiscalyear.FiscalMonth, fiscalyear.FiscalDay, datetime.datetime, datetime.date]) -> bool |
723,921 | fiscalyear | __eq__ | null | def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalQuarter):
return (self._fiscal_year, self._fiscal_quarter) == (
other._fiscal_year,
other._fiscal_quarter,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,922 | fiscalyear | __ge__ | null | def __ge__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) >= (
other._fiscal_year,
other._fiscal_quarter,
)
| (self, other: fiscalyear.FiscalQuarter) -> bool |
723,923 | fiscalyear | __gt__ | null | def __gt__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) > (
other._fiscal_year,
other._fiscal_quarter,
)
| (self, other: fiscalyear.FiscalQuarter) -> bool |
723,925 | fiscalyear | __le__ | null | def __le__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) <= (
other._fiscal_year,
other._fiscal_quarter,
)
| (self, other: fiscalyear.FiscalQuarter) -> bool |
723,926 | fiscalyear | __lt__ | null | def __lt__(self, other: "FiscalQuarter") -> bool:
return (self._fiscal_year, self._fiscal_quarter) < (
other._fiscal_year,
other._fiscal_quarter,
)
| (self, other: fiscalyear.FiscalQuarter) -> bool |
723,927 | fiscalyear | __ne__ | null | def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalQuarter):
return (self._fiscal_year, self._fiscal_quarter) != (
other._fiscal_year,
other._fiscal_quarter,
)
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,928 | fiscalyear | __new__ | Constructor.
:param fiscal_year: The fiscal year
:param fiscal_quarter: The fiscal quarter
:returns: A newly constructed FiscalQuarter object
:raises ValueError: If fiscal_year or fiscal_quarter is out of range
| def __new__(cls, fiscal_year: int, fiscal_quarter: int) -> "FiscalQuarter":
"""Constructor.
:param fiscal_year: The fiscal year
:param fiscal_quarter: The fiscal quarter
:returns: A newly constructed FiscalQuarter object
:raises ValueError: If fiscal_year or fiscal_quarter is out of range
"""
fiscal_year = _check_year(fiscal_year)
fiscal_quarter = _check_quarter(fiscal_quarter)
self = super(FiscalQuarter, cls).__new__(cls)
self._fiscal_year = fiscal_year
self._fiscal_quarter = fiscal_quarter
return self
| (cls, fiscal_year: int, fiscal_quarter: int) -> fiscalyear.FiscalQuarter |
723,929 | fiscalyear | __repr__ | Convert to formal string, for repr().
>>> q3 = FiscalQuarter(2017, 3)
>>> repr(q3)
'FiscalQuarter(2017, 3)'
| def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> q3 = FiscalQuarter(2017, 3)
>>> repr(q3)
'FiscalQuarter(2017, 3)'
"""
return f"{self.__class__.__name__}({self._fiscal_year}, {self._fiscal_quarter})"
| (self) -> str |
723,930 | fiscalyear | __str__ | Convert to informal string, for str().
>>> q3 = FiscalQuarter(2017, 3)
>>> str(q3)
'FY2017 Q3'
| def __str__(self) -> str:
"""Convert to informal string, for str().
>>> q3 = FiscalQuarter(2017, 3)
>>> str(q3)
'FY2017 Q3'
"""
return f"FY{self._fiscal_year} Q{self._fiscal_quarter}"
| (self) -> str |
723,931 | fiscalyear | FiscalYear | A class representing a single fiscal year. | class FiscalYear(_Hashable):
"""A class representing a single fiscal year."""
__slots__ = ["_fiscal_year"]
__hash__ = _Hashable.__hash__
_fiscal_year: int
def __new__(cls, fiscal_year: int) -> "FiscalYear":
"""Constructor.
:param fiscal_year: The fiscal year
:returns: A newly constructed FiscalYear object
:raises ValueError: If ``fiscal_year`` is out of range
"""
fiscal_year = _check_year(fiscal_year)
self = super(FiscalYear, cls).__new__(cls)
self._fiscal_year = fiscal_year
return self
@classmethod
def current(cls) -> "FiscalYear":
"""Alternative constructor. Returns the current FiscalYear.
:returns: A newly constructed FiscalYear object
"""
today = FiscalDate.today()
return cls(today.fiscal_year)
def __repr__(self) -> str:
"""Convert to formal string, for repr().
>>> fy = FiscalYear(2017)
>>> repr(fy)
'FiscalYear(2017)'
"""
return f"{self.__class__.__name__}({self._fiscal_year})"
def __str__(self) -> str:
"""Convert to informal string, for str().
>>> fy = FiscalYear(2017)
>>> str(fy)
'FY2017'
"""
return f"FY{self._fiscal_year}"
# TODO: Implement __format__ so that you can print
# fiscal year as 17 or 2017 (%y or %Y)
def __contains__(
self,
item: Union[
"FiscalYear",
"FiscalQuarter",
"FiscalMonth",
"FiscalDay",
datetime.datetime,
datetime.date,
],
) -> bool:
""":param item: The item to check
:returns: True if item in self, else False
"""
if isinstance(item, FiscalYear):
return self == item
elif isinstance(item, (FiscalQuarter, FiscalMonth, FiscalDay)):
return self._fiscal_year == item.fiscal_year
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
else:
return self.start.date() <= item <= self.end.date()
# Read-only field accessors
@property
def fiscal_year(self) -> int:
""":returns: The fiscal year"""
return self._fiscal_year
@property
def prev_fiscal_year(self) -> "FiscalYear":
""":returns: The previous fiscal year"""
return FiscalYear(self._fiscal_year - 1)
@property
def next_fiscal_year(self) -> "FiscalYear":
""":returns: The next fiscal year"""
return FiscalYear(self._fiscal_year + 1)
@property
def start(self) -> "FiscalDateTime":
""":returns: Start of the fiscal year"""
return self.q1.start
@property
def end(self) -> "FiscalDateTime":
""":returns: End of the fiscal year"""
return self.q4.end
@property
def q1(self) -> "FiscalQuarter":
""":returns: The first quarter of the fiscal year"""
return FiscalQuarter(self._fiscal_year, 1)
@property
def q2(self) -> "FiscalQuarter":
""":returns: The second quarter of the fiscal year"""
return FiscalQuarter(self._fiscal_year, 2)
@property
def q3(self) -> "FiscalQuarter":
""":returns: The third quarter of the fiscal year"""
return FiscalQuarter(self._fiscal_year, 3)
@property
def q4(self) -> "FiscalQuarter":
""":returns: The fourth quarter of the fiscal year"""
return FiscalQuarter(self._fiscal_year, 4)
@property
def isleap(self) -> bool:
"""returns: True if the fiscal year contains a leap day, else False"""
fiscal_year = FiscalYear(self._fiscal_year)
starts_on_or_before_possible_leap_day = (
fiscal_year.start.month,
fiscal_year.start.day,
) < (3, 1)
if START_YEAR == "previous":
if starts_on_or_before_possible_leap_day:
calendar_year = self._fiscal_year - 1
else:
calendar_year = self._fiscal_year
elif START_YEAR == "same":
if starts_on_or_before_possible_leap_day:
calendar_year = self._fiscal_year
else:
calendar_year = self._fiscal_year + 1
return calendar.isleap(calendar_year)
# Comparisons of FiscalYear objects with other
def __lt__(self, other: "FiscalYear") -> bool:
return self._fiscal_year < other._fiscal_year
def __le__(self, other: "FiscalYear") -> bool:
return self._fiscal_year <= other._fiscal_year
def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalYear):
return self._fiscal_year == other._fiscal_year
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __ne__(self, other: object) -> bool:
if isinstance(other, FiscalYear):
return self._fiscal_year != other._fiscal_year
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
def __gt__(self, other: "FiscalYear") -> bool:
return self._fiscal_year > other._fiscal_year
def __ge__(self, other: "FiscalYear") -> bool:
return self._fiscal_year >= other._fiscal_year
| (fiscal_year: int) -> 'FiscalYear' |
723,932 | fiscalyear | __contains__ | :param item: The item to check
:returns: True if item in self, else False
| def __contains__(
self,
item: Union[
"FiscalYear",
"FiscalQuarter",
"FiscalMonth",
"FiscalDay",
datetime.datetime,
datetime.date,
],
) -> bool:
""":param item: The item to check
:returns: True if item in self, else False
"""
if isinstance(item, FiscalYear):
return self == item
elif isinstance(item, (FiscalQuarter, FiscalMonth, FiscalDay)):
return self._fiscal_year == item.fiscal_year
elif isinstance(item, datetime.datetime):
return self.start <= item <= self.end
else:
return self.start.date() <= item <= self.end.date()
| (self, item: Union[fiscalyear.FiscalYear, fiscalyear.FiscalQuarter, fiscalyear.FiscalMonth, fiscalyear.FiscalDay, datetime.datetime, datetime.date]) -> bool |
723,933 | fiscalyear | __eq__ | null | def __eq__(self, other: object) -> bool:
if isinstance(other, FiscalYear):
return self._fiscal_year == other._fiscal_year
else:
raise TypeError(
f"can't compare '{type(self).__name__}' to '{type(other).__name__}'"
)
| (self, other: object) -> bool |
723,934 | fiscalyear | __ge__ | null | def __ge__(self, other: "FiscalYear") -> bool:
return self._fiscal_year >= other._fiscal_year
| (self, other: fiscalyear.FiscalYear) -> bool |
723,935 | fiscalyear | __gt__ | null | def __gt__(self, other: "FiscalYear") -> bool:
return self._fiscal_year > other._fiscal_year
| (self, other: fiscalyear.FiscalYear) -> bool |
723,937 | fiscalyear | __le__ | null | def __le__(self, other: "FiscalYear") -> bool:
return self._fiscal_year <= other._fiscal_year
| (self, other: fiscalyear.FiscalYear) -> bool |
723,938 | fiscalyear | __lt__ | null | def __lt__(self, other: "FiscalYear") -> bool:
return self._fiscal_year < other._fiscal_year
| (self, other: fiscalyear.FiscalYear) -> bool |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.