apply pyupgrade

This commit is contained in:
David Lord 2020-04-04 09:43:06 -07:00
parent 57d628ca74
commit 524fd0bc8c
No known key found for this signature in database
GPG key ID: 7A1C87E3F5BC42A8
54 changed files with 169 additions and 230 deletions

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask
~~~~~

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.__main__
~~~~~~~~~~~~~~

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.app
~~~~~~~~~
@ -1111,7 +1110,7 @@ class Flask(_PackageBoundObject):
endpoint=None,
view_func=None,
provide_automatic_options=None,
**options
**options,
):
"""Connects a URL rule. Works exactly like the :meth:`route`
decorator. If a view_func is provided it will be registered with the
@ -1180,7 +1179,7 @@ class Flask(_PackageBoundObject):
"Allowed methods must be a list of strings, for"
' example: @app.route(..., methods=["POST"])'
)
methods = set(item.upper() for item in methods)
methods = {item.upper() for item in methods}
# Methods that should always be added
required_methods = set(getattr(view_func, "required_methods", ()))
@ -1342,7 +1341,7 @@ class Flask(_PackageBoundObject):
"""
if isinstance(code_or_exception, HTTPException): # old broken behavior
raise ValueError(
"Tried to register a handler for an exception instance {0!r}."
"Tried to register a handler for an exception instance {!r}."
" Handlers can only be registered for exception classes or"
" HTTP error codes.".format(code_or_exception)
)
@ -1351,7 +1350,7 @@ class Flask(_PackageBoundObject):
exc_class, code = self._get_exc_class_and_code(code_or_exception)
except KeyError:
raise KeyError(
"'{0}' is not a recognized HTTP error code. Use a subclass of"
"'{}' is not a recognized HTTP error code. Use a subclass of"
" HTTPException with that code instead.".format(code_or_exception)
)
@ -1811,7 +1810,7 @@ class Flask(_PackageBoundObject):
.. versionadded:: 0.8
"""
self.logger.error(
"Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info
f"Exception on {request.path} [{request.method}]", exc_info=exc_info
)
def raise_routing_exception(self, request):
@ -2376,4 +2375,4 @@ class Flask(_PackageBoundObject):
return self.wsgi_app(environ, start_response)
def __repr__(self):
return "<%s %r>" % (self.__class__.__name__, self.name)
return f"<{self.__class__.__name__} {self.name!r}>"

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.blueprints
~~~~~~~~~~~~~~~~
@ -18,7 +17,7 @@ from .helpers import _PackageBoundObject
_sentinel = object()
class BlueprintSetupState(object):
class BlueprintSetupState:
"""Temporary holder object for registering a blueprint with the
application. An instance of this class is created by the
:meth:`~flask.Blueprint.make_setup_state` method and later passed
@ -80,10 +79,10 @@ class BlueprintSetupState(object):
defaults = dict(defaults, **options.pop("defaults"))
self.app.add_url_rule(
rule,
"%s.%s" % (self.blueprint.name, endpoint),
f"{self.blueprint.name}.{endpoint}",
view_func,
defaults=defaults,
**options
**options,
)

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.cli
~~~~~~~~~
@ -8,8 +7,6 @@
:copyright: 2010 Pallets
:license: BSD-3-Clause
"""
from __future__ import print_function
import ast
import inspect
import os
@ -167,7 +164,7 @@ def find_app_by_string(script_info, module, app_name):
if inspect.isfunction(attr):
if args:
try:
args = ast.literal_eval("({args},)".format(args=args))
args = ast.literal_eval(f"({args},)")
except (ValueError, SyntaxError) as e:
raise NoAppException(
"Could not parse the arguments in "
@ -243,7 +240,7 @@ def locate_app(script_info, module_name, app_name, raise_if_not_found=True):
"\n\n{tb}".format(name=module_name, tb=traceback.format_exc())
)
elif raise_if_not_found:
raise NoAppException('Could not import "{name}".'.format(name=module_name))
raise NoAppException(f'Could not import "{module_name}".')
else:
return
@ -285,7 +282,7 @@ version_option = click.Option(
)
class DispatchingApp(object):
class DispatchingApp:
"""Special application that dispatches to a Flask application which
is imported by name in a background thread. If an error happens
it is recorded and shown as part of the WSGI handling which in case
@ -344,7 +341,7 @@ class DispatchingApp(object):
return rv(environ, start_response)
class ScriptInfo(object):
class ScriptInfo:
"""Helper object to deal with Flask applications. This is usually not
necessary to interface with as it's used internally in the dispatching
to click. In future versions of Flask this object will most likely play
@ -491,7 +488,7 @@ class FlaskGroup(AppGroup):
add_version_option=True,
load_dotenv=True,
set_debug_flag=True,
**extra
**extra,
):
params = list(extra.pop("params", None) or ())
@ -583,7 +580,7 @@ class FlaskGroup(AppGroup):
kwargs["obj"] = obj
kwargs.setdefault("auto_envvar_prefix", "FLASK")
return super(FlaskGroup, self).main(*args, **kwargs)
return super().main(*args, **kwargs)
def _path_is_ancestor(path, other):
@ -662,14 +659,14 @@ def show_server_banner(env, debug, app_import_path, eager_loading):
return
if app_import_path is not None:
message = ' * Serving Flask app "{0}"'.format(app_import_path)
message = f' * Serving Flask app "{app_import_path}"'
if not eager_loading:
message += " (lazy loading)"
click.echo(message)
click.echo(" * Environment: {0}".format(env))
click.echo(f" * Environment: {env}")
if env == "production":
click.secho(
@ -680,7 +677,7 @@ def show_server_banner(env, debug, app_import_path, eager_loading):
click.secho(" Use a production WSGI server instead.", dim=True)
if debug is not None:
click.echo(" * Debug mode: {0}".format("on" if debug else "off"))
click.echo(" * Debug mode: {}".format("on" if debug else "off"))
class CertParamType(click.ParamType):
@ -766,7 +763,7 @@ class SeparatedPathType(click.Path):
def convert(self, value, param, ctx):
items = self.split_envvar_value(value)
super_convert = super(SeparatedPathType, self).convert
super_convert = super().convert
return [super_convert(item, param, ctx) for item in items]
@ -866,12 +863,8 @@ def shell_command():
from .globals import _app_ctx_stack
app = _app_ctx_stack.top.app
banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (
sys.version,
sys.platform,
app.import_name,
app.env,
app.instance_path,
banner = "Python {} on {}\nApp: {} [{}]\nInstance: {}".format(
sys.version, sys.platform, app.import_name, app.env, app.instance_path,
)
ctx = {}
@ -879,7 +872,7 @@ def shell_command():
# is using it.
startup = os.environ.get("PYTHONSTARTUP")
if startup and os.path.isfile(startup):
with open(startup, "r") as f:
with open(startup) as f:
eval(compile(f.read(), startup, "exec"), ctx)
ctx.update(app.make_shell_context())

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.config
~~~~~~~~~~~~
@ -15,7 +14,7 @@ import types
from werkzeug.utils import import_string
class ConfigAttribute(object):
class ConfigAttribute:
"""Makes an attribute forward to the config"""
def __init__(self, name, get_converter=None):
@ -126,7 +125,7 @@ class Config(dict):
try:
with open(filename, mode="rb") as config_file:
exec(compile(config_file.read(), filename, "exec"), d.__dict__)
except IOError as e:
except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
return False
e.strerror = "Unable to load configuration file (%s)" % e.strerror
@ -197,7 +196,7 @@ class Config(dict):
try:
with open(filename) as f:
obj = load(f)
except IOError as e:
except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False
@ -271,4 +270,4 @@ class Config(dict):
return rv
def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))
return "<{} {}>".format(self.__class__.__name__, dict.__repr__(self))

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.ctx
~~~~~~~~~
@ -23,7 +22,7 @@ from .signals import appcontext_pushed
_sentinel = object()
class _AppCtxGlobals(object):
class _AppCtxGlobals:
"""A plain object. Used as a namespace for storing data during an
application context.
@ -200,7 +199,7 @@ def has_app_context():
return _app_ctx_stack.top is not None
class AppContext(object):
class AppContext:
"""The application context binds an application object implicitly
to the current thread or greenlet, similar to how the
:class:`RequestContext` binds request information. The application
@ -234,7 +233,7 @@ class AppContext(object):
self.app.do_teardown_appcontext(exc)
finally:
rv = _app_ctx_stack.pop()
assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)
assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"
appcontext_popped.send(self.app)
def __enter__(self):
@ -245,7 +244,7 @@ class AppContext(object):
self.pop(exc_value)
class RequestContext(object):
class RequestContext:
"""The request context contains all request relevant information. It is
created at the beginning of the request and pushed to the
`_request_ctx_stack` and removed at the end of it. It will create the
@ -420,10 +419,9 @@ class RequestContext(object):
if app_ctx is not None:
app_ctx.pop(exc)
assert rv is self, "Popped wrong request context. (%r instead of %r)" % (
rv,
self,
)
assert (
rv is self
), f"Popped wrong request context. ({rv!r} instead of {self!r})"
def auto_pop(self, exc):
if self.request.environ.get("flask._preserve_context") or (
@ -447,7 +445,7 @@ class RequestContext(object):
self.auto_pop(exc_value)
def __repr__(self):
return "<%s '%s' [%s] of %s>" % (
return "<{} '{}' [{}] of {}>".format(
self.__class__.__name__,
self.request.url,
self.request.method,

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.debughelpers
~~~~~~~~~~~~~~~~~~
@ -102,7 +101,7 @@ def attach_enctype_error_multidict(request):
def _dump_loader_info(loader):
yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)
yield "class: {}.{}".format(type(loader).__module__, type(loader).__name__)
for key, value in sorted(loader.__dict__.items()):
if key.startswith("_"):
continue
@ -115,7 +114,7 @@ def _dump_loader_info(loader):
continue
elif not isinstance(value, (str, int, float, bool)):
continue
yield "%s: %r" % (key, value)
yield f"{key}: {value!r}"
def explain_template_loading_attempts(app, template, attempts):
@ -131,7 +130,7 @@ def explain_template_loading_attempts(app, template, attempts):
if isinstance(srcobj, Flask):
src_info = 'application "%s"' % srcobj.import_name
elif isinstance(srcobj, Blueprint):
src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)
src_info = f'blueprint "{srcobj.name}" ({srcobj.import_name})'
else:
src_info = repr(srcobj)

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.globals
~~~~~~~~~~~~~

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.helpers
~~~~~~~~~~~~~
@ -155,8 +154,7 @@ def stream_with_context(generator_or_function):
# don't need that because they are closed on their destruction
# automatically.
try:
for item in gen:
yield item
yield from gen
finally:
if hasattr(gen, "close"):
gen.close()
@ -933,7 +931,7 @@ def find_package(import_name):
return None, package_path
class locked_cached_property(object):
class locked_cached_property:
"""A decorator that converts a function into a lazy property. The
function wrapped is called the first time to retrieve the result
and then that calculated result is used the next time you access
@ -959,7 +957,7 @@ class locked_cached_property(object):
return value
class _PackageBoundObject(object):
class _PackageBoundObject:
#: The name of the package or module that this app belongs to. Do not
#: change this once it is set by the constructor.
import_name = None
@ -1137,7 +1135,7 @@ def is_ip(value):
for family in (socket.AF_INET, socket.AF_INET6):
try:
socket.inet_pton(family, value)
except socket.error:
except OSError:
pass
else:
return True

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.json
~~~~~~~~~~
@ -286,10 +285,10 @@ def htmlsafe_dumps(obj, **kwargs):
"""
rv = (
dumps(obj, **kwargs)
.replace(u"<", u"\\u003c")
.replace(u">", u"\\u003e")
.replace(u"&", u"\\u0026")
.replace(u"'", u"\\u0027")
.replace("<", "\\u003c")
.replace(">", "\\u003e")
.replace("&", "\\u0026")
.replace("'", "\\u0027")
)
if not _slash_escape:
rv = rv.replace("\\/", "/")

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
Tagged JSON
~~~~~~~~~~~
@ -54,7 +53,7 @@ from ..json import dumps
from ..json import loads
class JSONTag(object):
class JSONTag:
"""Base class for defining type tags for :class:`TaggedJSONSerializer`."""
__slots__ = ("serializer",)
@ -122,7 +121,7 @@ class PassDict(JSONTag):
def to_json(self, value):
# JSON objects may only have string keys, so don't bother tagging the
# key here.
return dict((k, self.serializer.tag(v)) for k, v in value.items())
return {k: self.serializer.tag(v) for k, v in value.items()}
tag = to_json
@ -213,7 +212,7 @@ class TagDateTime(JSONTag):
return parse_date(value)
class TaggedJSONSerializer(object):
class TaggedJSONSerializer:
"""Serializer that uses a tag system to compactly represent objects that
are not JSON types. Passed as the intermediate serializer to
:class:`itsdangerous.Serializer`.
@ -269,7 +268,7 @@ class TaggedJSONSerializer(object):
if key is not None:
if not force and key in self.tags:
raise KeyError("Tag '{0}' is already registered.".format(key))
raise KeyError(f"Tag '{key}' is already registered.")
self.tags[key] = tag

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.logging
~~~~~~~~~~~~~
@ -6,8 +5,6 @@ flask.logging
:copyright: 2010 Pallets
:license: BSD-3-Clause
"""
from __future__ import absolute_import
import logging
import sys

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.sessions
~~~~~~~~~~~~~~
@ -77,19 +76,19 @@ class SecureCookieSession(CallbackDict, SessionMixin):
self.modified = True
self.accessed = True
super(SecureCookieSession, self).__init__(initial, on_update)
super().__init__(initial, on_update)
def __getitem__(self, key):
self.accessed = True
return super(SecureCookieSession, self).__getitem__(key)
return super().__getitem__(key)
def get(self, key, default=None):
self.accessed = True
return super(SecureCookieSession, self).get(key, default)
return super().get(key, default)
def setdefault(self, key, default=None):
self.accessed = True
return super(SecureCookieSession, self).setdefault(key, default)
return super().setdefault(key, default)
class NullSession(SecureCookieSession):
@ -109,7 +108,7 @@ class NullSession(SecureCookieSession):
del _fail
class SessionInterface(object):
class SessionInterface:
"""The basic interface you have to implement in order to replace the
default session interface which uses werkzeug's securecookie
implementation. The only methods you have to implement are

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.signals
~~~~~~~~~~~~~
@ -16,11 +15,11 @@ try:
except ImportError:
signals_available = False
class Namespace(object):
class Namespace:
def signal(self, name, doc=None):
return _FakeSignal(name, doc)
class _FakeSignal(object):
class _FakeSignal:
"""If blinker is unavailable, create a fake class with the same
interface that allows sending of signals but will fail with an
error on anything else. Instead of doing anything on send, it

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.templating
~~~~~~~~~~~~~~~~

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.testing
~~~~~~~~~~~~~
@ -51,7 +50,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
subdomain=None,
url_scheme=None,
*args,
**kwargs
**kwargs,
):
assert not (base_url or subdomain or url_scheme) or (
base_url is not None
@ -64,7 +63,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
app_root = app.config["APPLICATION_ROOT"]
if subdomain:
http_host = "{0}.{1}".format(subdomain, http_host)
http_host = f"{subdomain}.{http_host}"
if url_scheme is None:
url_scheme = app.config["PREFERRED_URL_SCHEME"]
@ -82,7 +81,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
path += sep + url.query
self.app = app
super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)
super().__init__(path, base_url, *args, **kwargs)
def json_dumps(self, obj, **kwargs):
"""Serialize ``obj`` to a JSON-formatted string.
@ -112,7 +111,7 @@ class FlaskClient(Client):
preserve_context = False
def __init__(self, *args, **kwargs):
super(FlaskClient, self).__init__(*args, **kwargs)
super().__init__(*args, **kwargs)
self.environ_base = {
"REMOTE_ADDR": "127.0.0.1",
"HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,
@ -239,7 +238,7 @@ class FlaskCliRunner(CliRunner):
def __init__(self, app, **kwargs):
self.app = app
super(FlaskCliRunner, self).__init__(**kwargs)
super().__init__(**kwargs)
def invoke(self, cli=None, args=None, **kwargs):
"""Invokes a CLI command in an isolated environment. See
@ -262,4 +261,4 @@ class FlaskCliRunner(CliRunner):
if "obj" not in kwargs:
kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)
return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)
return super().invoke(cli, args, **kwargs)

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.views
~~~~~~~~~~~
@ -16,7 +15,7 @@ http_method_funcs = frozenset(
)
class View(object):
class View:
"""Alternative way to use view functions. A subclass has to implement
:meth:`dispatch_request` which is called with the view arguments from
the URL routing system. If :attr:`methods` is provided the methods
@ -113,7 +112,7 @@ class MethodViewType(type):
"""
def __init__(cls, name, bases, d):
super(MethodViewType, cls).__init__(name, bases, d)
super().__init__(name, bases, d)
if "methods" not in d:
methods = set()

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""
flask.wrappers
~~~~~~~~~~~~~~
@ -22,7 +21,7 @@ class JSONMixin(_JSONMixin):
def on_json_loading_failed(self, e):
if current_app and current_app.debug:
raise BadRequest("Failed to decode JSON object: {0}".format(e))
raise BadRequest(f"Failed to decode JSON object: {e}")
raise BadRequest()
@ -134,4 +133,4 @@ class Response(ResponseBase, JSONMixin):
return current_app.config["MAX_COOKIE_SIZE"]
# return Werkzeug's default when not in an app context
return super(Response, self).max_cookie_size
return super().max_cookie_size