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,22 +1,29 @@
repos: repos:
- repo: https://github.com/asottile/pyupgrade
rev: v2.1.0
hooks:
- id: pyupgrade
args: ["--py36-plus"]
- repo: https://github.com/asottile/reorder_python_imports - repo: https://github.com/asottile/reorder_python_imports
rev: v1.5.0 rev: v2.1.0
hooks: hooks:
- id: reorder-python-imports - id: reorder-python-imports
name: Reorder Python imports (src, tests) name: Reorder Python imports (src, tests)
files: "^(?!examples/)" files: "^(?!examples/)"
args: ["--application-directories", ".:src"] args: ["--application-directories", "src"]
- repo: https://github.com/python/black - repo: https://github.com/python/black
rev: 19.3b0 rev: 19.10b0
hooks: hooks:
- id: black - id: black
- repo: https://gitlab.com/pycqa/flake8 - repo: https://gitlab.com/pycqa/flake8
rev: 3.7.7 rev: 3.7.9
hooks: hooks:
- id: flake8 - id: flake8
additional_dependencies: [flake8-bugbear] additional_dependencies:
- flake8-bugbear
- flake8-implicit-str-concat
- repo: https://github.com/pre-commit/pre-commit-hooks - repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.2.3 rev: v2.5.0
hooks: hooks:
- id: check-byte-order-marker - id: check-byte-order-marker
- id: trailing-whitespace - id: trailing-whitespace

View file

@ -52,14 +52,12 @@ singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}
html_static_path = ["_static"] html_static_path = ["_static"]
html_favicon = "_static/flask-icon.png" html_favicon = "_static/flask-icon.png"
html_logo = "_static/flask-icon.png" html_logo = "_static/flask-icon.png"
html_title = "Flask Documentation ({})".format(version) html_title = f"Flask Documentation ({version})"
html_show_sourcelink = False html_show_sourcelink = False
# LaTeX ---------------------------------------------------------------- # LaTeX ----------------------------------------------------------------
latex_documents = [ latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]
(master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")
]
# Local Extensions ----------------------------------------------------- # Local Extensions -----------------------------------------------------
@ -76,9 +74,9 @@ def github_link(name, rawtext, text, lineno, inliner, options=None, content=None
words = None words = None
if packaging.version.parse(release).is_devrelease: if packaging.version.parse(release).is_devrelease:
url = "{0}master/{1}".format(base_url, text) url = f"{base_url}master/{text}"
else: else:
url = "{0}{1}/{2}".format(base_url, release, text) url = f"{base_url}{release}/{text}"
if words is None: if words is None:
words = url words = url

View file

@ -2,4 +2,4 @@ from flask import Flask
app = Flask(__name__) app = Flask(__name__)
from js_example import views from js_example import views # noqa: F401

View file

@ -8,7 +8,7 @@ from js_example import app
@app.route("/", defaults={"js": "plain"}) @app.route("/", defaults={"js": "plain"})
@app.route("/<any(plain, jquery, fetch):js>") @app.route("/<any(plain, jquery, fetch):js>")
def index(js): def index(js):
return render_template("{0}.html".format(js), js=js) return render_template(f"{js}.html", js=js)
@app.route("/add", methods=["POST"]) @app.route("/add", methods=["POST"])

View file

@ -1,9 +1,7 @@
import io
from setuptools import find_packages from setuptools import find_packages
from setuptools import setup from setuptools import setup
with io.open("README.rst", "rt", encoding="utf8") as f: with open("README.rst", encoding="utf8") as f:
readme = f.read() readme = f.read()
setup( setup(

View file

@ -64,7 +64,7 @@ def register():
db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone() db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()
is not None is not None
): ):
error = "User {0} is already registered.".format(username) error = f"User {username} is already registered."
if error is None: if error is None:
# the name is available, store it in the database and go to # the name is available, store it in the database and go to

View file

@ -49,7 +49,7 @@ def get_post(id, check_author=True):
) )
if post is None: if post is None:
abort(404, "Post id {0} doesn't exist.".format(id)) abort(404, f"Post id {id} doesn't exist.")
if check_author and post["author_id"] != g.user["id"]: if check_author and post["author_id"] != g.user["id"]:
abort(403) abort(403)

View file

@ -1,9 +1,7 @@
import io
from setuptools import find_packages from setuptools import find_packages
from setuptools import setup from setuptools import setup
with io.open("README.rst", "rt", encoding="utf8") as f: with open("README.rst", encoding="utf8") as f:
readme = f.read() readme = f.read()
setup( setup(

View file

@ -44,7 +44,7 @@ def runner(app):
return app.test_cli_runner() return app.test_cli_runner()
class AuthActions(object): class AuthActions:
def __init__(self, client): def __init__(self, client):
self._client = client self._client = client

View file

@ -17,7 +17,7 @@ def test_get_close_db(app):
def test_init_db_command(runner, monkeypatch): def test_init_db_command(runner, monkeypatch):
class Recorder(object): class Recorder:
called = False called = False
def fake_init_db(): def fake_init_db():

View file

@ -20,7 +20,8 @@ source =
# F = flake8 pyflakes # F = flake8 pyflakes
# W = pycodestyle warnings # W = pycodestyle warnings
# B9 = bugbear opinions # B9 = bugbear opinions
select = B, E, F, W, B9 # ISC = implicit-str-concat
select = B, E, F, W, B9, ISC
ignore = ignore =
# slice notation whitespace, invalid # slice notation whitespace, invalid
E203 E203
@ -35,6 +36,5 @@ ignore =
# up to 88 allowed by bugbear B950 # up to 88 allowed by bugbear B950
max-line-length = 80 max-line-length = 80
per-file-ignores = per-file-ignores =
# __init__ modules export names # __init__ module exports names
**/__init__.py: F401 src/flask/__init__.py: F401
src/flask/_compat.py: E731, B301, F401

View file

@ -1,13 +1,12 @@
import io
import re import re
from setuptools import find_packages from setuptools import find_packages
from setuptools import setup from setuptools import setup
with io.open("README.rst", "rt", encoding="utf8") as f: with open("README.rst", encoding="utf8") as f:
readme = f.read() readme = f.read()
with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f: with open("src/flask/__init__.py", encoding="utf8") as f:
version = re.search(r'__version__ = "(.*?)"', f.read()).group(1) version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)
setup( setup(

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.app flask.app
~~~~~~~~~ ~~~~~~~~~
@ -1111,7 +1110,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
@ -1180,7 +1179,7 @@ class Flask(_PackageBoundObject):
"Allowed methods must be a list of strings, for" "Allowed methods must be a list of strings, for"
' example: @app.route(..., methods=["POST"])' ' 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", ()))
@ -1342,7 +1341,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)
) )
@ -1351,7 +1350,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)
) )
@ -1811,7 +1810,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):
@ -2376,4 +2375,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,
) )

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
@ -167,7 +164,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 "
@ -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()) "\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
@ -285,7 +282,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):
@ -766,7 +763,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]
@ -866,12 +863,8 @@ 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, app.import_name, app.env, app.instance_path,
sys.platform,
app.import_name,
app.env,
app.instance_path,
) )
ctx = {} ctx = {}
@ -879,7 +872,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
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -15,7 +14,7 @@ import types
from werkzeug.utils import import_string from werkzeug.utils import import_string
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):
@ -126,7 +125,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
@ -197,7 +196,7 @@ class Config(dict):
try: try:
with open(filename) as f: with open(filename) as f:
obj = load(f) obj = load(f)
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
@ -271,4 +270,4 @@ class Config(dict):
return rv return rv
def __repr__(self): 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 flask.ctx
~~~~~~~~~ ~~~~~~~~~
@ -23,7 +22,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.
@ -200,7 +199,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
@ -234,7 +233,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):
@ -245,7 +244,7 @@ class AppContext(object):
self.pop(exc_value) self.pop(exc_value)
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
@ -420,10 +419,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, rv is self
self, ), f"Popped wrong request context. ({rv!r} instead of {self!r})"
)
def auto_pop(self, exc): def auto_pop(self, exc):
if self.request.environ.get("flask._preserve_context") or ( if self.request.environ.get("flask._preserve_context") or (
@ -447,7 +445,7 @@ class RequestContext(object):
self.auto_pop(exc_value) self.auto_pop(exc_value)
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
~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~
@ -102,7 +101,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 "class: {}.{}".format(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
@ -115,7 +114,7 @@ def _dump_loader_info(loader):
continue continue
elif not isinstance(value, (str, int, float, bool)): elif not isinstance(value, (str, 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):
@ -131,7 +130,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
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -155,8 +154,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
@ -1137,7 +1135,7 @@ def is_ip(value):
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
~~~~~~~~~~ ~~~~~~~~~~
@ -286,10 +285,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
~~~~~~~~~~~ ~~~~~~~~~~~
@ -54,7 +53,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",)
@ -122,7 +121,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 value.items()) return {k: self.serializer.tag(v) for k, v in value.items()}
tag = to_json tag = to_json
@ -213,7 +212,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`.
@ -269,7 +268,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

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
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -51,7 +50,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
@ -64,7 +63,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"]
@ -82,7 +81,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.
@ -112,7 +111,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__,
@ -239,7 +238,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
@ -262,4 +261,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
~~~~~~~~~~~ ~~~~~~~~~~~
@ -16,7 +15,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
@ -113,7 +112,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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.conftest tests.conftest
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
@ -112,7 +111,7 @@ def limit_loader(request, monkeypatch):
if not request.param: if not request.param:
return return
class LimitedLoader(object): class LimitedLoader:
def __init__(self, loader): def __init__(self, loader):
self.loader = loader self.loader = loader
@ -172,7 +171,7 @@ def install_egg(modules_tmpdir, monkeypatch):
textwrap.dedent( textwrap.dedent(
""" """
from setuptools import setup from setuptools import setup
setup(name='{0}', setup(name='{}',
version='1.0', version='1.0',
packages=['site_egg'], packages=['site_egg'],
zip_safe=True) zip_safe=True)
@ -187,7 +186,7 @@ def install_egg(modules_tmpdir, monkeypatch):
subprocess.check_call( subprocess.check_call(
[sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir) [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)
) )
egg_path, = modules_tmpdir.join("dist/").listdir() (egg_path,) = modules_tmpdir.join("dist/").listdir()
monkeypatch.syspath_prepend(str(egg_path)) monkeypatch.syspath_prepend(str(egg_path))
return egg_path return egg_path

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.appctx tests.appctx
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -163,7 +162,7 @@ def test_app_ctx_globals_methods(app, app_ctx):
def test_custom_app_ctx_globals_class(app): def test_custom_app_ctx_globals_class(app):
class CustomRequestGlobals(object): class CustomRequestGlobals:
def __init__(self): def __init__(self):
self.spam = "eggs" self.spam = "eggs"
@ -190,7 +189,7 @@ def test_context_refcounts(app, client):
pass pass
env = flask._request_ctx_stack.top.request.environ env = flask._request_ctx_stack.top.request.environ
assert env["werkzeug.request"] is not None assert env["werkzeug.request"] is not None
return u"" return ""
res = client.get("/") res = client.get("/")
assert res.status_code == 200 assert res.status_code == 200

View file

@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import print_function
from flask import Flask from flask import Flask
testapp = Flask("testapp") testapp = Flask("testapp")

View file

@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import print_function
from flask import Flask from flask import Flask

View file

@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import print_function
from flask import Flask from flask import Flask
raise ImportError() raise ImportError()

View file

@ -1,6 +1,3 @@
from __future__ import absolute_import
from __future__ import print_function
from flask import Flask from flask import Flask
app1 = Flask("app1") app1 = Flask("app1")

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.basic tests.basic
~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~
@ -278,7 +277,7 @@ def test_session_using_server_name_port_and_path(app, client):
def test_session_using_application_root(app, client): def test_session_using_application_root(app, client):
class PrefixPathMiddleware(object): class PrefixPathMiddleware:
def __init__(self, app, prefix): def __init__(self, app, prefix):
self.app = app self.app = app
self.prefix = prefix self.prefix = prefix
@ -583,18 +582,18 @@ def test_extended_flashing(app):
@app.route("/") @app.route("/")
def index(): def index():
flask.flash(u"Hello World") flask.flash("Hello World")
flask.flash(u"Hello World", "error") flask.flash("Hello World", "error")
flask.flash(flask.Markup(u"<em>Testing</em>"), "warning") flask.flash(flask.Markup("<em>Testing</em>"), "warning")
return "" return ""
@app.route("/test/") @app.route("/test/")
def test(): def test():
messages = flask.get_flashed_messages() messages = flask.get_flashed_messages()
assert list(messages) == [ assert list(messages) == [
u"Hello World", "Hello World",
u"Hello World", "Hello World",
flask.Markup(u"<em>Testing</em>"), flask.Markup("<em>Testing</em>"),
] ]
return "" return ""
@ -603,9 +602,9 @@ def test_extended_flashing(app):
messages = flask.get_flashed_messages(with_categories=True) messages = flask.get_flashed_messages(with_categories=True)
assert len(messages) == 3 assert len(messages) == 3
assert list(messages) == [ assert list(messages) == [
("message", u"Hello World"), ("message", "Hello World"),
("error", u"Hello World"), ("error", "Hello World"),
("warning", flask.Markup(u"<em>Testing</em>")), ("warning", flask.Markup("<em>Testing</em>")),
] ]
return "" return ""
@ -614,7 +613,7 @@ def test_extended_flashing(app):
messages = flask.get_flashed_messages( messages = flask.get_flashed_messages(
category_filter=["message"], with_categories=True category_filter=["message"], with_categories=True
) )
assert list(messages) == [("message", u"Hello World")] assert list(messages) == [("message", "Hello World")]
return "" return ""
@app.route("/test_filters/") @app.route("/test_filters/")
@ -623,8 +622,8 @@ def test_extended_flashing(app):
category_filter=["message", "warning"], with_categories=True category_filter=["message", "warning"], with_categories=True
) )
assert list(messages) == [ assert list(messages) == [
("message", u"Hello World"), ("message", "Hello World"),
("warning", flask.Markup(u"<em>Testing</em>")), ("warning", flask.Markup("<em>Testing</em>")),
] ]
return "" return ""
@ -632,8 +631,8 @@ def test_extended_flashing(app):
def test_filters2(): def test_filters2():
messages = flask.get_flashed_messages(category_filter=["message", "warning"]) messages = flask.get_flashed_messages(category_filter=["message", "warning"])
assert len(messages) == 2 assert len(messages) == 2
assert messages[0] == u"Hello World" assert messages[0] == "Hello World"
assert messages[1] == flask.Markup(u"<em>Testing</em>") assert messages[1] == flask.Markup("<em>Testing</em>")
return "" return ""
# Create new test client on each test to clean flashed messages. # Create new test client on each test to clean flashed messages.
@ -1102,11 +1101,11 @@ def test_enctype_debug_helper(app, client):
def test_response_types(app, client): def test_response_types(app, client):
@app.route("/text") @app.route("/text")
def from_text(): def from_text():
return u"Hällo Wörld" return "Hällo Wörld"
@app.route("/bytes") @app.route("/bytes")
def from_bytes(): def from_bytes():
return u"Hällo Wörld".encode("utf-8") return "Hällo Wörld".encode()
@app.route("/full_tuple") @app.route("/full_tuple")
def from_full_tuple(): def from_full_tuple():
@ -1143,8 +1142,8 @@ def test_response_types(app, client):
def from_dict(): def from_dict():
return {"foo": "bar"}, 201 return {"foo": "bar"}, 201
assert client.get("/text").data == u"Hällo Wörld".encode("utf-8") assert client.get("/text").data == "Hällo Wörld".encode()
assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8") assert client.get("/bytes").data == "Hällo Wörld".encode()
rv = client.get("/full_tuple") rv = client.get("/full_tuple")
assert rv.data == b"Meh" assert rv.data == b"Meh"
@ -1611,11 +1610,11 @@ def test_inject_blueprint_url_defaults(app):
def test_nonascii_pathinfo(app, client): def test_nonascii_pathinfo(app, client):
@app.route(u"/киртест") @app.route("/киртест")
def index(): def index():
return "Hello World!" return "Hello World!"
rv = client.get(u"/киртест") rv = client.get("/киртест")
assert rv.data == b"Hello World!" assert rv.data == b"Hello World!"
@ -1875,7 +1874,7 @@ def test_multi_route_rules(app, client):
def test_multi_route_class_views(app, client): def test_multi_route_class_views(app, client):
class View(object): class View:
def __init__(self, app): def __init__(self, app):
app.add_url_rule("/", "index", self.index) app.add_url_rule("/", "index", self.index)
app.add_url_rule("/<test>/", "index", self.index) app.add_url_rule("/<test>/", "index", self.index)
@ -1907,12 +1906,12 @@ def test_run_server_port(monkeypatch, app):
# Mocks werkzeug.serving.run_simple method # Mocks werkzeug.serving.run_simple method
def run_simple_mock(hostname, port, application, *args, **kwargs): def run_simple_mock(hostname, port, application, *args, **kwargs):
rv["result"] = "running on %s:%s ..." % (hostname, port) rv["result"] = f"running on {hostname}:{port} ..."
monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock) monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)
hostname, port = "localhost", 8000 hostname, port = "localhost", 8000
app.run(hostname, port, debug=True) app.run(hostname, port, debug=True)
assert rv["result"] == "running on %s:%s ..." % (hostname, port) assert rv["result"] == f"running on {hostname}:{port} ..."
@pytest.mark.parametrize( @pytest.mark.parametrize(

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.test_cli tests.test_cli
~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~
@ -8,8 +7,6 @@
""" """
# This file was part of Flask-CLI and was modified under the terms of # This file was part of Flask-CLI and was modified under the terms of
# its Revised BSD License. Copyright © 2015 CERN. # its Revised BSD License. Copyright © 2015 CERN.
from __future__ import absolute_import
import os import os
import ssl import ssl
import sys import sys
@ -261,7 +258,7 @@ def test_get_version(test_apps, capsys):
from werkzeug import __version__ as werkzeug_version from werkzeug import __version__ as werkzeug_version
from platform import python_version from platform import python_version
class MockCtx(object): class MockCtx:
resilient_parsing = False resilient_parsing = False
color = None color = None

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.test_config tests.test_config
~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~
@ -65,7 +64,7 @@ def test_config_from_mapping():
def test_config_from_class(): def test_config_from_class():
class Base(object): class Base:
TEST_KEY = "foo" TEST_KEY = "foo"
class Test(Base): class Test(Base):
@ -186,8 +185,8 @@ def test_from_pyfile_weird_encoding(tmpdir, encoding):
f = tmpdir.join("my_config.py") f = tmpdir.join("my_config.py")
f.write_binary( f.write_binary(
textwrap.dedent( textwrap.dedent(
u""" """
# -*- coding: {0} -*- # -*- coding: {} -*-
TEST_VALUE = "föö" TEST_VALUE = "föö"
""".format( """.format(
encoding encoding
@ -197,4 +196,4 @@ def test_from_pyfile_weird_encoding(tmpdir, encoding):
app = flask.Flask(__name__) app = flask.Flask(__name__)
app.config.from_pyfile(str(f)) app.config.from_pyfile(str(f))
value = app.config["TEST_VALUE"] value = app.config["TEST_VALUE"]
assert value == u"föö" assert value == "föö"

View file

@ -10,7 +10,7 @@ def test_custom_converters(app, client):
return value.split(",") return value.split(",")
def to_url(self, value): def to_url(self, value):
base_to_url = super(ListConverter, self).to_url base_to_url = super().to_url
return ",".join(base_to_url(x) for x in value) return ",".join(base_to_url(x) for x in value)
app.url_map.converters["list"] = ListConverter app.url_map.converters["list"] = ListConverter

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.helpers tests.helpers
~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~
@ -38,7 +37,7 @@ def has_encoding(name):
return False return False
class FakePath(object): class FakePath:
"""Fake object to represent a ``PathLike object``. """Fake object to represent a ``PathLike object``.
This represents a ``pathlib.Path`` object in python 3. This represents a ``pathlib.Path`` object in python 3.
@ -73,9 +72,9 @@ class FixedOffset(datetime.tzinfo):
return datetime.timedelta() return datetime.timedelta()
class TestJSON(object): class TestJSON:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"}) "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": "🐍"})
) )
@pytest.mark.parametrize( @pytest.mark.parametrize(
"encoding", "encoding",
@ -126,12 +125,12 @@ class TestJSON(object):
assert rv.data == b"foo" assert rv.data == b"foo"
@pytest.mark.parametrize( @pytest.mark.parametrize(
"test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')] "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')]
) )
def test_json_as_unicode(self, test_value, expected, app, app_ctx): def test_json_as_unicode(self, test_value, expected, app, app_ctx):
app.config["JSON_AS_ASCII"] = test_value app.config["JSON_AS_ASCII"] = test_value
rv = flask.json.dumps(u"\N{SNOWMAN}") rv = flask.json.dumps("\N{SNOWMAN}")
assert rv == expected assert rv == expected
def test_json_dump_to_file(self, app, app_ctx): def test_json_dump_to_file(self, app, app_ctx):
@ -217,7 +216,7 @@ class TestJSON(object):
) )
for i, d in enumerate(test_dates): for i, d in enumerate(test_dates):
url = "/datetest{0}".format(i) url = f"/datetest{i}"
app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val)) app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))
rv = client.get(url) rv = client.get(url)
assert rv.mimetype == "application/json" assert rv.mimetype == "application/json"
@ -262,7 +261,7 @@ class TestJSON(object):
def test_template_escaping(self, app, req_ctx): def test_template_escaping(self, app, req_ctx):
render = flask.render_template_string render = flask.render_template_string
rv = flask.json.htmlsafe_dumps("</script>") rv = flask.json.htmlsafe_dumps("</script>")
assert rv == u'"\\u003c/script\\u003e"' assert rv == '"\\u003c/script\\u003e"'
assert type(rv) is str assert type(rv) is str
rv = render('{{ "</script>"|tojson }}') rv = render('{{ "</script>"|tojson }}')
assert rv == '"\\u003c/script\\u003e"' assert rv == '"\\u003c/script\\u003e"'
@ -280,7 +279,7 @@ class TestJSON(object):
assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>' assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'
def test_json_customization(self, app, client): def test_json_customization(self, app, client):
class X(object): # noqa: B903, for Python2 compatibility class X: # noqa: B903, for Python2 compatibility
def __init__(self, val): def __init__(self, val):
self.val = val self.val = val
@ -315,7 +314,7 @@ class TestJSON(object):
assert rv.data == b'"<42>"' assert rv.data == b'"<42>"'
def test_blueprint_json_customization(self, app, client): def test_blueprint_json_customization(self, app, client):
class X(object): # noqa: B903, for Python2 compatibility class X: # noqa: B903, for Python2 compatibility
def __init__(self, val): def __init__(self, val):
self.val = val self.val = val
@ -368,9 +367,9 @@ class TestJSON(object):
def index(): def index():
return flask.request.args["foo"] return flask.request.args["foo"]
rv = client.get(u"/?foo=정상처리".encode("euc-kr")) rv = client.get("/?foo=정상처리".encode("euc-kr"))
assert rv.status_code == 200 assert rv.status_code == 200
assert rv.data == u"정상처리".encode("utf-8") assert rv.data == "정상처리".encode()
def test_json_key_sorting(self, app, client): def test_json_key_sorting(self, app, client):
app.debug = True app.debug = True
@ -443,7 +442,7 @@ class TestJSON(object):
assert lines == sorted_by_str assert lines == sorted_by_str
class PyBytesIO(object): class PyBytesIO:
def __init__(self, *args, **kwargs): def __init__(self, *args, **kwargs):
self._io = io.BytesIO(*args, **kwargs) self._io = io.BytesIO(*args, **kwargs)
@ -451,7 +450,7 @@ class PyBytesIO(object):
return getattr(self._io, name) return getattr(self._io, name)
class TestSendfile(object): class TestSendfile:
def test_send_file_regular(self, app, req_ctx): def test_send_file_regular(self, app, req_ctx):
rv = flask.send_file("static/index.html") rv = flask.send_file("static/index.html")
assert rv.direct_passthrough assert rv.direct_passthrough
@ -516,7 +515,7 @@ class TestSendfile(object):
@pytest.mark.parametrize( @pytest.mark.parametrize(
"opener", "opener",
[ [
lambda app: io.StringIO(u"Test"), lambda app: io.StringIO("Test"),
lambda app: open(os.path.join(app.static_folder, "index.html")), lambda app: open(os.path.join(app.static_folder, "index.html")),
], ],
) )
@ -673,13 +672,13 @@ class TestSendfile(object):
( (
("index.html", "index.html", False), ("index.html", "index.html", False),
( (
u"Ñandúpingüino.txt", "Ñandúpingüino.txt",
'"Nandu/pinguino.txt"', '"Nandu/pinguino.txt"',
"%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt", "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",
), ),
(u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"), ("Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),
# ":/" are not safe in filename* value # ":/" are not safe in filename* value
(u"те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"), ("те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),
), ),
) )
def test_attachment_filename_encoding(self, filename, ascii, utf8): def test_attachment_filename_encoding(self, filename, ascii, utf8):
@ -775,7 +774,7 @@ class TestSendfile(object):
flask.send_from_directory("static", "bad\x00") flask.send_from_directory("static", "bad\x00")
class TestUrlFor(object): class TestUrlFor:
def test_url_for_with_anchor(self, app, req_ctx): def test_url_for_with_anchor(self, app, req_ctx):
@app.route("/") @app.route("/")
def index(): def index():
@ -834,7 +833,7 @@ class TestUrlFor(object):
assert flask.url_for("myview", _method="POST") == "/myview/create" assert flask.url_for("myview", _method="POST") == "/myview/create"
class TestNoImports(object): class TestNoImports:
"""Test Flasks are created without import. """Test Flasks are created without import.
Avoiding ``__import__`` helps create Flask instances where there are errors Avoiding ``__import__`` helps create Flask instances where there are errors
@ -853,7 +852,7 @@ class TestNoImports(object):
AssertionError("Flask(import_name) is importing import_name.") AssertionError("Flask(import_name) is importing import_name.")
class TestStreaming(object): class TestStreaming:
def test_streaming_with_context(self, app, client): def test_streaming_with_context(self, app, client):
@app.route("/") @app.route("/")
def index(): def index():
@ -884,7 +883,7 @@ class TestStreaming(object):
def test_streaming_with_context_and_custom_close(self, app, client): def test_streaming_with_context_and_custom_close(self, app, client):
called = [] called = []
class Wrapper(object): class Wrapper:
def __init__(self, gen): def __init__(self, gen):
self._gen = gen self._gen = gen
@ -927,7 +926,7 @@ class TestStreaming(object):
assert rv.data == b"flask" assert rv.data == b"flask"
class TestSafeJoin(object): class TestSafeJoin:
def test_safe_join(self): def test_safe_join(self):
# Valid combinations of *args and expected joined paths. # Valid combinations of *args and expected joined paths.
passing = ( passing = (
@ -968,7 +967,7 @@ class TestSafeJoin(object):
print(flask.safe_join(*args)) print(flask.safe_join(*args))
class TestHelpers(object): class TestHelpers:
@pytest.mark.parametrize( @pytest.mark.parametrize(
"debug, expected_flag, expected_default_flag", "debug, expected_flag, expected_default_flag",
[ [

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.test_json_tag tests.test_json_tag
~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~
@ -48,7 +47,7 @@ def test_duplicate_tag():
def test_custom_tag(): def test_custom_tag():
class Foo(object): # noqa: B903, for Python2 compatibility class Foo: # noqa: B903, for Python2 compatibility
def __init__(self, data): def __init__(self, data):
self.data = data self.data = data

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.regression tests.regression
~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -20,7 +19,7 @@ import flask
_gc_lock = threading.Lock() _gc_lock = threading.Lock()
class assert_no_leak(object): class assert_no_leak:
def __enter__(self): def __enter__(self):
gc.disable() gc.disable()
_gc_lock.acquire() _gc_lock.acquire()

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.reqctx tests.reqctx
~~~~~~~~~~~~ ~~~~~~~~~~~~
@ -150,7 +149,7 @@ def test_manual_context_binding(app):
@pytest.mark.skipif(greenlet is None, reason="greenlet not installed") @pytest.mark.skipif(greenlet is None, reason="greenlet not installed")
class TestGreenletContextCopying(object): class TestGreenletContextCopying:
def test_greenlet_context_copying(self, app, client): def test_greenlet_context_copying(self, app, client):
greenlets = [] greenlets = []
@ -239,7 +238,7 @@ def test_session_dynamic_cookie_name():
if flask.request.url.endswith("dynamic_cookie"): if flask.request.url.endswith("dynamic_cookie"):
return "dynamic_cookie_name" return "dynamic_cookie_name"
else: else:
return super(PathAwareSessionInterface, self).get_cookie_name(app) return super().get_cookie_name(app)
class CustomFlask(flask.Flask): class CustomFlask(flask.Flask):
session_interface = PathAwareSessionInterface() session_interface = PathAwareSessionInterface()
@ -291,7 +290,7 @@ def test_bad_environ_raises_bad_request():
environ = builder.get_environ() environ = builder.get_environ()
# use a non-printable character in the Host - this is key to this test # use a non-printable character in the Host - this is key to this test
environ["HTTP_HOST"] = u"\x8a" environ["HTTP_HOST"] = "\x8a"
with app.request_context(environ): with app.request_context(environ):
response = app.full_dispatch_request() response = app.full_dispatch_request()
@ -311,7 +310,7 @@ def test_environ_for_valid_idna_completes():
environ = builder.get_environ() environ = builder.get_environ()
# these characters are all IDNA-compatible # these characters are all IDNA-compatible
environ["HTTP_HOST"] = u"ąśźäüжŠßя.com" environ["HTTP_HOST"] = "ąśźäüжŠßя.com"
with app.request_context(environ): with app.request_context(environ):
response = app.full_dispatch_request() response = app.full_dispatch_request()

View file

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

View file

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

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.templating tests.templating
~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~
@ -417,14 +416,14 @@ def test_template_loader_debugging(test_apps, monkeypatch):
text = str(record.msg) text = str(record.msg)
assert '1: trying loader of application "blueprintapp"' in text assert '1: trying loader of application "blueprintapp"' in text
assert ( assert (
'2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)" '2: trying loader of blueprint "admin" (blueprintapp.apps.admin)'
) in text ) in text
assert ( assert (
'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)" 'trying loader of blueprint "frontend" (blueprintapp.apps.frontend)'
) in text ) in text
assert "Error: the template could not be found" in text assert "Error: the template could not be found" in text
assert ( assert (
"looked up from an endpoint that belongs to " 'the blueprint "frontend"' 'looked up from an endpoint that belongs to the blueprint "frontend"'
) in text ) in text
assert "See https://flask.palletsprojects.com/blueprints/#templates" in text assert "See https://flask.palletsprojects.com/blueprints/#templates" in text

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.testing tests.testing
~~~~~~~~~~~~~ ~~~~~~~~~~~~~
@ -122,8 +121,8 @@ def test_path_is_url(app):
def test_environbuilder_json_dumps(app): def test_environbuilder_json_dumps(app):
"""EnvironBuilder.json_dumps() takes settings from the app.""" """EnvironBuilder.json_dumps() takes settings from the app."""
app.config["JSON_AS_ASCII"] = False app.config["JSON_AS_ASCII"] = False
eb = EnvironBuilder(app, json=u"\u20ac") eb = EnvironBuilder(app, json="\u20ac")
assert eb.input_stream.read().decode("utf8") == u'"\u20ac"' assert eb.input_stream.read().decode("utf8") == '"\u20ac"'
def test_blueprint_with_subdomain(): def test_blueprint_with_subdomain():
@ -324,7 +323,7 @@ def test_client_json_no_app_context(app, client):
def hello(): def hello():
return "Hello, {}!".format(flask.request.json["name"]) return "Hello, {}!".format(flask.request.json["name"])
class Namespace(object): class Namespace:
count = 0 count = 0
def add(self, app): def add(self, app):
@ -402,7 +401,7 @@ def test_cli_invoke(app):
def test_cli_custom_obj(app): def test_cli_custom_obj(app):
class NS(object): class NS:
called = False called = False
def create_app(): def create_app():

View file

@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
""" """
tests.test_user_error_handler tests.test_user_error_handler
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
@ -208,7 +207,7 @@ def test_default_error_handler():
assert c.get("/slash", follow_redirects=True).data == b"slash" assert c.get("/slash", follow_redirects=True).data == b"slash"
class TestGenericHandlers(object): class TestGenericHandlers:
"""Test how very generic handlers are dispatched to.""" """Test how very generic handlers are dispatched to."""
class Custom(Exception): class Custom(Exception):

View file

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