Skip to content

Commit

Permalink
Merge pull request #401 from joke2k/fix/codestyle
Browse files Browse the repository at this point in the history
Fix code style
  • Loading branch information
sergeyklay committed Jun 19, 2022
2 parents 495be60 + 20ba2d1 commit 6fc36d8
Show file tree
Hide file tree
Showing 7 changed files with 60 additions and 35 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.rst
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,10 @@ Deprecated
- Support of Python < 3.6 is deprecated and will be removed
in next major version.

Changed
+++++++
- Use UTF-8 as a encoding when open ``.env`` file.

Removed
+++++++
- Removed deprecated ``Env.unicode()``.
Expand Down Expand Up @@ -74,7 +78,7 @@ Fixed
---------------------------
Added
+++++
- Log invalid lines when parse .env file
- Log invalid lines when parse ``.env`` file
`#283 <https://github.com/joke2k/django-environ/pull/283>`_.
- Added docker-style file variable support
`#189 <https://github.com/joke2k/django-environ/issues/189>`_.
Expand Down
2 changes: 2 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,6 +126,8 @@ def find_version(meta_file):
# In nitpick mode (-n), still ignore any of the following "broken" references
# to non-types.
nitpick_ignore = [
('py:func', 'str.rfind'),
('py:func', 'str.find'),
]

#
Expand Down
1 change: 1 addition & 0 deletions environ/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,5 +42,6 @@
__url__ = 'https://django-environ.readthedocs.org'
"""The URL of the package."""

# pylint: disable=line-too-long
__description__ = 'A package that allows you to utilize 12factor inspired environment variables to configure your Django application.' # noqa: E501
"""The description of the package."""
2 changes: 1 addition & 1 deletion environ/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
DJANGO_VERSION = None

class ImproperlyConfigured(Exception):
pass
"""Django is somehow improperly configured"""


def choose_rediscache_driver():
Expand Down
64 changes: 33 additions & 31 deletions environ/environ.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,7 @@ def _cast_urlstr(v):


class NoValue:
"""Represent of no value object."""

def __repr__(self):
return '<{}>'.format(self.__class__.__name__)
Expand Down Expand Up @@ -203,8 +204,6 @@ def __call__(self, var, cast=None, default=NOTSET, parse_default=False):
def __contains__(self, var):
return var in self.ENVIRON

# Shortcuts

def str(self, var, default=NOTSET, multiline=False):
"""
:rtype: str
Expand Down Expand Up @@ -357,9 +356,9 @@ def get_value(self, var, cast=None, default=NOTSET, parse_default=False):
:rtype: typing.IO[typing.Any]
"""

logger.debug("get '{}' casted as '{}' with default '{}'".format(
var, cast, default
))
logger.debug(
"get '%s' casted as '%s' with default '%s'",
var, cast, default)

var_name = "{}{}".format(self.prefix, var)
if var_name in self.scheme:
Expand Down Expand Up @@ -415,8 +414,6 @@ def get_value(self, var, cast=None, default=NOTSET, parse_default=False):

return value

# Class and static methods

@classmethod
def parse_value(cls, value, cast):
"""Parse and cast provided value
Expand All @@ -428,7 +425,7 @@ def parse_value(cls, value, cast):
"""
if cast is None:
return value
elif cast is bool:
if cast is bool:
try:
value = int(value) != 0
except ValueError:
Expand All @@ -441,7 +438,7 @@ def parse_value(cls, value, cast):
elif isinstance(cast, dict):
key_cast = cast.get('key', str)
value_cast = cast.get('value', str)
value_cast_by_key = cast.get('cast', dict())
value_cast_by_key = cast.get('cast', {})
value = dict(map(
lambda kv: (
key_cast(kv[0]),
Expand All @@ -458,6 +455,7 @@ def parse_value(cls, value, cast):
value = [x for x in value.split(',') if x]
elif cast is tuple:
val = value.strip('(').strip(')').split(',')
# pylint: disable=consider-using-generator
value = tuple([x for x in val if x])
elif cast is float:
# clean string
Expand Down Expand Up @@ -574,7 +572,7 @@ def db_url_config(cls, url, engine=None):
if url.scheme == 'oracle':
# Django oracle/base.py strips port and fails on non-string value
if not config['PORT']:
del (config['PORT'])
del config['PORT']
else:
config['PORT'] = str(config['PORT'])

Expand Down Expand Up @@ -615,8 +613,7 @@ def cache_url_config(cls, url, backend=None):
if not isinstance(url, cls.URL_CLASS):
if not url:
return {}
else:
url = urlparse(url)
url = urlparse(url)

if url.scheme not in cls.CACHE_SCHEMES:
raise ImproperlyConfigured(
Expand Down Expand Up @@ -760,24 +757,24 @@ def search_url_config(cls, url, engine=None):
params = {} # type: dict
if url.query:
params = parse_qs(url.query)
if 'EXCLUDED_INDEXES' in params.keys():
if 'EXCLUDED_INDEXES' in params:
config['EXCLUDED_INDEXES'] \
= params['EXCLUDED_INDEXES'][0].split(',')
if 'INCLUDE_SPELLING' in params.keys():
if 'INCLUDE_SPELLING' in params:
config['INCLUDE_SPELLING'] = cls.parse_value(
params['INCLUDE_SPELLING'][0],
bool
)
if 'BATCH_SIZE' in params.keys():
if 'BATCH_SIZE' in params:
config['BATCH_SIZE'] = cls.parse_value(
params['BATCH_SIZE'][0],
int
)

if url.scheme == 'simple':
return config
elif url.scheme in ['solr'] + cls.ELASTICSEARCH_FAMILY:
if 'KWARGS' in params.keys():
if url.scheme in ['solr'] + cls.ELASTICSEARCH_FAMILY:
if 'KWARGS' in params:
config['KWARGS'] = params['KWARGS'][0]

# remove trailing slash
Expand All @@ -788,7 +785,7 @@ def search_url_config(cls, url, engine=None):
config['URL'] = urlunparse(
('http',) + url[1:2] + (path,) + ('', '', '')
)
if 'TIMEOUT' in params.keys():
if 'TIMEOUT' in params:
config['TIMEOUT'] = cls.parse_value(params['TIMEOUT'][0], int)
return config

Expand All @@ -805,23 +802,23 @@ def search_url_config(cls, url, engine=None):
config['URL'] = urlunparse(
('http',) + url[1:2] + (path,) + ('', '', '')
)
if 'TIMEOUT' in params.keys():
if 'TIMEOUT' in params:
config['TIMEOUT'] = cls.parse_value(params['TIMEOUT'][0], int)
config['INDEX_NAME'] = index
return config

config['PATH'] = '/' + path

if url.scheme == 'whoosh':
if 'STORAGE' in params.keys():
if 'STORAGE' in params:
config['STORAGE'] = params['STORAGE'][0]
if 'POST_LIMIT' in params.keys():
if 'POST_LIMIT' in params:
config['POST_LIMIT'] = cls.parse_value(
params['POST_LIMIT'][0],
int
)
elif url.scheme == 'xapian':
if 'FLAGS' in params.keys():
if 'FLAGS' in params:
config['FLAGS'] = params['FLAGS'][0]

if engine:
Expand Down Expand Up @@ -855,6 +852,7 @@ def read_env(cls, env_file=None, overwrite=False, **overrides):
existing environment variable, the value will be overridden.
"""
if env_file is None:
# pylint: disable=protected-access
frame = sys._getframe()
env_file = os.path.join(
os.path.dirname(frame.f_back.f_code.co_filename),
Expand All @@ -863,24 +861,24 @@ def read_env(cls, env_file=None, overwrite=False, **overrides):
if not os.path.exists(env_file):
logger.info(
"%s doesn't exist - if you're not configuring your "
"environment separately, create one." % env_file)
"environment separately, create one.", env_file)
return

try:
if isinstance(env_file, Openable):
# Python 3.5 support (wrap path with str).
with open(str(env_file)) as f:
with open(str(env_file), encoding='utf-8') as f:
content = f.read()
else:
with env_file as f:
content = f.read()
except OSError:
logger.info(
"%s not found - if you're not configuring your "
"environment separately, check this." % env_file)
"environment separately, check this.", env_file)
return

logger.debug('Read environment variables from: {}'.format(env_file))
logger.debug('Read environment variables from: %s', env_file)

def _keep_escaped_format_characters(match):
"""Keep escaped newline/tabs in quoted strings"""
Expand Down Expand Up @@ -960,13 +958,15 @@ def file(self, name, *args, **kwargs):
:param \**kwargs: ``**kwargs`` passed to :py:func:`open`
:rtype: typing.IO[typing.Any]
"""
# pylint: disable=unspecified-encoding
return open(self(name), *args, **kwargs)

@property
def root(self):
"""Current directory for this Path"""
return self.__root__

# pylint: disable=keyword-arg-before-vararg
def __init__(self, start='', *paths, **kwargs):

super().__init__()
Expand Down Expand Up @@ -1000,9 +1000,9 @@ def __add__(self, other):
def __sub__(self, other):
if isinstance(other, int):
return self.path('../' * other)
elif isinstance(other, str):
if self.__root__.endswith(other):
return Path(self.__root__.rstrip(other))
if isinstance(other, str) and self.__root__.endswith(other):
return Path(self.__root__.rstrip(other))

raise TypeError(
"unsupported operand type(s) for -: '{self}' and '{other}' "
"unless value of {self} ends with value of {other}".format(
Expand Down Expand Up @@ -1035,10 +1035,12 @@ def __fspath__(self):
return self.__str__()

def rfind(self, *args, **kwargs):
return self.__str__().rfind(*args, **kwargs)
"""Proxy method to :py:func:`str.rfind`"""
return str(self).rfind(*args, **kwargs)

def find(self, *args, **kwargs):
return self.__str__().find(*args, **kwargs)
"""Proxy method to :py:func:`str.find`"""
return str(self).find(*args, **kwargs)

@staticmethod
def _absolute_join(base, *paths, **kwargs):
Expand Down
2 changes: 1 addition & 1 deletion environ/fileaware_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def __getitem__(self, key):
return self.files_cache[key]
key_file = self.env.get(key + "_FILE")
if key_file:
with open(key_file) as f:
with open(key_file, encoding='utf-8') as f:
value = f.read()
if self.cache:
self.files_cache[key] = value
Expand Down
18 changes: 17 additions & 1 deletion tox.ini
Original file line number Diff line number Diff line change
Expand Up @@ -67,10 +67,26 @@ deps =
flake8
flake8-blind-except
flake8-import-order
pylint
commands_pre =
python -m pip install --upgrade pip
python -m pip install .
commands = flake8 environ setup.py
commands =
flake8 environ setup.py
# Format ("f") strings have not been introduced before Python 3.6,
# thus disable "consider-using-f-string" at this moment.
pylint \
--logging-format-style=old \
--good-names-rgxs=m[0-9],f,v \
--disable=too-few-public-methods \
--disable=import-error \
--disable=unused-import \
--disable=consider-using-f-string \
--disable=too-many-locals \
--disable=too-many-branches \
--disable=too-many-public-methods \
--disable=too-many-lines \
environ

[testenv:linkcheck]
description = Check external links in the package documentation
Expand Down

0 comments on commit 6fc36d8

Please sign in to comment.