Merge branch 'main' of https://github.com/fochoao/flask into main

This commit is contained in:
Fernando Ochoa O 2021-06-24 15:14:07 -05:00
commit 75ba58a293
20 changed files with 71 additions and 97 deletions

View file

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

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask._compat flask._compat
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -83,7 +82,7 @@ def with_metaclass(meta, *bases):
BROKEN_PYPY_CTXMGR_EXIT = False BROKEN_PYPY_CTXMGR_EXIT = False
if hasattr(sys, "pypy_version_info"): if hasattr(sys, "pypy_version_info"):
class _Mgr(object): class _Mgr:
def __enter__(self): def __enter__(self):
return self return self
@ -115,7 +114,7 @@ except ImportError:
return path.__fspath__() if hasattr(path, "__fspath__") else path return path.__fspath__() if hasattr(path, "__fspath__") else path
class _DeprecatedBool(object): class _DeprecatedBool:
def __init__(self, name, version, value): def __init__(self, name, version, value):
self.message = "'{}' is deprecated and will be removed in version {}.".format( self.message = "'{}' is deprecated and will be removed in version {}.".format(
name, version name, version

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask.app flask.app
~~~~~~~~~ ~~~~~~~~~
@ -1181,7 +1180,7 @@ class Flask(_PackageBoundObject):
endpoint=None, endpoint=None,
view_func=None, view_func=None,
provide_automatic_options=None, provide_automatic_options=None,
**options **options,
): ):
"""Connects a URL rule. Works exactly like the :meth:`route` """Connects a URL rule. Works exactly like the :meth:`route`
decorator. If a view_func is provided it will be registered with the decorator. If a view_func is provided it will be registered with the
@ -1250,7 +1249,7 @@ class Flask(_PackageBoundObject):
"Allowed methods have to be iterables of strings, " "Allowed methods have to be iterables of strings, "
'for example: @app.route(..., methods=["POST"])' '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 # Methods that should always be added
required_methods = set(getattr(view_func, "required_methods", ())) required_methods = set(getattr(view_func, "required_methods", ()))
@ -1412,7 +1411,7 @@ class Flask(_PackageBoundObject):
""" """
if isinstance(code_or_exception, HTTPException): # old broken behavior if isinstance(code_or_exception, HTTPException): # old broken behavior
raise ValueError( 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" " Handlers can only be registered for exception classes or"
" HTTP error codes.".format(code_or_exception) " HTTP error codes.".format(code_or_exception)
) )
@ -1421,7 +1420,7 @@ class Flask(_PackageBoundObject):
exc_class, code = self._get_exc_class_and_code(code_or_exception) exc_class, code = self._get_exc_class_and_code(code_or_exception)
except KeyError: except KeyError:
raise 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) " HTTPException with that code instead.".format(code_or_exception)
) )
@ -1889,7 +1888,7 @@ class Flask(_PackageBoundObject):
.. versionadded:: 0.8 .. versionadded:: 0.8
""" """
self.logger.error( 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): def raise_routing_exception(self, request):
@ -2197,8 +2196,7 @@ class Flask(_PackageBoundObject):
func(endpoint, values) func(endpoint, values)
def handle_url_build_error(self, error, endpoint, values): def handle_url_build_error(self, error, endpoint, values):
"""Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`. """Handle :class:`~werkzeug.routing.BuildError` on :meth:`url_for`."""
"""
exc_type, exc_value, tb = sys.exc_info() exc_type, exc_value, tb = sys.exc_info()
for handler in self.url_build_error_handlers: for handler in self.url_build_error_handlers:
try: try:
@ -2464,4 +2462,4 @@ class Flask(_PackageBoundObject):
return self.wsgi_app(environ, start_response) return self.wsgi_app(environ, start_response)
def __repr__(self): 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 flask.blueprints
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
@ -18,7 +17,7 @@ from .helpers import _PackageBoundObject
_sentinel = object() _sentinel = object()
class BlueprintSetupState(object): class BlueprintSetupState:
"""Temporary holder object for registering a blueprint with the """Temporary holder object for registering a blueprint with the
application. An instance of this class is created by the application. An instance of this class is created by the
:meth:`~flask.Blueprint.make_setup_state` method and later passed :meth:`~flask.Blueprint.make_setup_state` method and later passed
@ -80,10 +79,10 @@ class BlueprintSetupState(object):
defaults = dict(defaults, **options.pop("defaults")) defaults = dict(defaults, **options.pop("defaults"))
self.app.add_url_rule( self.app.add_url_rule(
rule, rule,
"%s.%s" % (self.blueprint.name, endpoint), f"{self.blueprint.name}.{endpoint}",
view_func, view_func,
defaults=defaults, defaults=defaults,
**options **options,
) )
@ -521,16 +520,14 @@ class Blueprint(_PackageBoundObject):
return f return f
def app_url_value_preprocessor(self, f): def app_url_value_preprocessor(self, f):
"""Same as :meth:`url_value_preprocessor` but application wide. """Same as :meth:`url_value_preprocessor` but application wide."""
"""
self.record_once( self.record_once(
lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f) lambda s: s.app.url_value_preprocessors.setdefault(None, []).append(f)
) )
return f return f
def app_url_defaults(self, f): def app_url_defaults(self, f):
"""Same as :meth:`url_defaults` but application wide. """Same as :meth:`url_defaults` but application wide."""
"""
self.record_once( self.record_once(
lambda s: s.app.url_default_functions.setdefault(None, []).append(f) lambda s: s.app.url_default_functions.setdefault(None, []).append(f)
) )

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask.config flask.config
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -19,7 +18,7 @@ from ._compat import iteritems
from ._compat import string_types from ._compat import string_types
class ConfigAttribute(object): class ConfigAttribute:
"""Makes an attribute forward to the config""" """Makes an attribute forward to the config"""
def __init__(self, name, get_converter=None): def __init__(self, name, get_converter=None):
@ -130,7 +129,7 @@ class Config(dict):
try: try:
with open(filename, mode="rb") as config_file: with open(filename, mode="rb") as config_file:
exec(compile(config_file.read(), filename, "exec"), d.__dict__) 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): if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):
return False return False
e.strerror = "Unable to load configuration file (%s)" % e.strerror e.strerror = "Unable to load configuration file (%s)" % e.strerror
@ -194,7 +193,7 @@ class Config(dict):
try: try:
with open(filename) as json_file: with open(filename) as json_file:
obj = json.loads(json_file.read()) obj = json.loads(json_file.read())
except IOError as e: except OSError as e:
if silent and e.errno in (errno.ENOENT, errno.EISDIR): if silent and e.errno in (errno.ENOENT, errno.EISDIR):
return False return False
e.strerror = "Unable to load configuration file (%s)" % e.strerror e.strerror = "Unable to load configuration file (%s)" % e.strerror
@ -266,4 +265,4 @@ class Config(dict):
return rv return rv
def __repr__(self): def __repr__(self):
return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self)) return f"<{self.__class__.__name__} {dict.__repr__(self)}>"

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask.ctx flask.ctx
~~~~~~~~~ ~~~~~~~~~
@ -25,7 +24,7 @@ from .signals import appcontext_pushed
_sentinel = object() _sentinel = object()
class _AppCtxGlobals(object): class _AppCtxGlobals:
"""A plain object. Used as a namespace for storing data during an """A plain object. Used as a namespace for storing data during an
application context. application context.
@ -202,7 +201,7 @@ def has_app_context():
return _app_ctx_stack.top is not None return _app_ctx_stack.top is not None
class AppContext(object): class AppContext:
"""The application context binds an application object implicitly """The application context binds an application object implicitly
to the current thread or greenlet, similar to how the to the current thread or greenlet, similar to how the
:class:`RequestContext` binds request information. The application :class:`RequestContext` binds request information. The application
@ -238,7 +237,7 @@ class AppContext(object):
self.app.do_teardown_appcontext(exc) self.app.do_teardown_appcontext(exc)
finally: finally:
rv = _app_ctx_stack.pop() 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) appcontext_popped.send(self.app)
def __enter__(self): def __enter__(self):
@ -252,7 +251,7 @@ class AppContext(object):
reraise(exc_type, exc_value, tb) reraise(exc_type, exc_value, tb)
class RequestContext(object): class RequestContext:
"""The request context contains all request relevant information. It is """The request context contains all request relevant information. It is
created at the beginning of the request and pushed to the 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 `_request_ctx_stack` and removed at the end of it. It will create the
@ -437,7 +436,9 @@ class RequestContext(object):
if app_ctx is not None: if app_ctx is not None:
app_ctx.pop(exc) app_ctx.pop(exc)
assert rv is self, "Popped wrong request context. (%r instead of %r)" % ( assert (
rv is self
), "Popped wrong request context. ({!r} instead of {!r})".format(
rv, rv,
self, self,
) )
@ -467,7 +468,7 @@ class RequestContext(object):
reraise(exc_type, exc_value, tb) reraise(exc_type, exc_value, tb)
def __repr__(self): def __repr__(self):
return "<%s '%s' [%s] of %s>" % ( return "<{} '{}' [{}] of {}>".format(
self.__class__.__name__, self.__class__.__name__,
self.request.url, self.request.url,
self.request.method, self.request.method,

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
Tagged JSON Tagged JSON
~~~~~~~~~~~ ~~~~~~~~~~~
@ -56,7 +55,7 @@ from ..json import dumps
from ..json import loads from ..json import loads
class JSONTag(object): class JSONTag:
"""Base class for defining type tags for :class:`TaggedJSONSerializer`.""" """Base class for defining type tags for :class:`TaggedJSONSerializer`."""
__slots__ = ("serializer",) __slots__ = ("serializer",)
@ -124,7 +123,7 @@ class PassDict(JSONTag):
def to_json(self, value): def to_json(self, value):
# JSON objects may only have string keys, so don't bother tagging the # JSON objects may only have string keys, so don't bother tagging the
# key here. # key here.
return dict((k, self.serializer.tag(v)) for k, v in iteritems(value)) return {k: self.serializer.tag(v) for k, v in iteritems(value)}
tag = to_json tag = to_json
@ -215,7 +214,7 @@ class TagDateTime(JSONTag):
return parse_date(value) return parse_date(value)
class TaggedJSONSerializer(object): class TaggedJSONSerializer:
"""Serializer that uses a tag system to compactly represent objects that """Serializer that uses a tag system to compactly represent objects that
are not JSON types. Passed as the intermediate serializer to are not JSON types. Passed as the intermediate serializer to
:class:`itsdangerous.Serializer`. :class:`itsdangerous.Serializer`.
@ -271,7 +270,7 @@ class TaggedJSONSerializer(object):
if key is not None: if key is not None:
if not force and key in self.tags: 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 self.tags[key] = tag

View file

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

View file

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

View file

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

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask.testing flask.testing
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -52,7 +51,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
subdomain=None, subdomain=None,
url_scheme=None, url_scheme=None,
*args, *args,
**kwargs **kwargs,
): ):
assert not (base_url or subdomain or url_scheme) or ( assert not (base_url or subdomain or url_scheme) or (
base_url is not None base_url is not None
@ -65,7 +64,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
app_root = app.config["APPLICATION_ROOT"] app_root = app.config["APPLICATION_ROOT"]
if subdomain: if subdomain:
http_host = "{0}.{1}".format(subdomain, http_host) http_host = f"{subdomain}.{http_host}"
if url_scheme is None: if url_scheme is None:
url_scheme = app.config["PREFERRED_URL_SCHEME"] url_scheme = app.config["PREFERRED_URL_SCHEME"]
@ -83,7 +82,7 @@ class EnvironBuilder(werkzeug.test.EnvironBuilder):
path += sep + url.query path += sep + url.query
self.app = app 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): def json_dumps(self, obj, **kwargs):
"""Serialize ``obj`` to a JSON-formatted string. """Serialize ``obj`` to a JSON-formatted string.
@ -130,7 +129,7 @@ class FlaskClient(Client):
preserve_context = False preserve_context = False
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
super(FlaskClient, self).__init__(*args, **kwargs) super().__init__(*args, **kwargs)
self.environ_base = { self.environ_base = {
"REMOTE_ADDR": "127.0.0.1", "REMOTE_ADDR": "127.0.0.1",
"HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__, "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,
@ -257,7 +256,7 @@ class FlaskCliRunner(CliRunner):
def __init__(self, app, **kwargs): def __init__(self, app, **kwargs):
self.app = app self.app = app
super(FlaskCliRunner, self).__init__(**kwargs) super().__init__(**kwargs)
def invoke(self, cli=None, args=None, **kwargs): def invoke(self, cli=None, args=None, **kwargs):
"""Invokes a CLI command in an isolated environment. See """Invokes a CLI command in an isolated environment. See
@ -280,4 +279,4 @@ class FlaskCliRunner(CliRunner):
if "obj" not in kwargs: if "obj" not in kwargs:
kwargs["obj"] = ScriptInfo(create_app=lambda: self.app) 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 flask.views
~~~~~~~~~~~ ~~~~~~~~~~~
@ -17,7 +16,7 @@ http_method_funcs = frozenset(
) )
class View(object): class View:
"""Alternative way to use view functions. A subclass has to implement """Alternative way to use view functions. A subclass has to implement
:meth:`dispatch_request` which is called with the view arguments from :meth:`dispatch_request` which is called with the view arguments from
the URL routing system. If :attr:`methods` is provided the methods the URL routing system. If :attr:`methods` is provided the methods
@ -114,7 +113,7 @@ class MethodViewType(type):
""" """
def __init__(cls, name, bases, d): def __init__(cls, name, bases, d):
super(MethodViewType, cls).__init__(name, bases, d) super().__init__(name, bases, d)
if "methods" not in d: if "methods" not in d:
methods = set() methods = set()

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
flask.wrappers flask.wrappers
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
@ -22,7 +21,7 @@ class JSONMixin(_JSONMixin):
def on_json_loading_failed(self, e): def on_json_loading_failed(self, e):
if current_app and current_app.debug: 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() raise BadRequest()
@ -134,4 +133,4 @@ class Response(ResponseBase, JSONMixin):
return current_app.config["MAX_COOKIE_SIZE"] return current_app.config["MAX_COOKIE_SIZE"]
# return Werkzeug's default when not in an app context # return Werkzeug's default when not in an app context
return super(Response, self).max_cookie_size return super().max_cookie_size