forked from orbit-oss/flask
apply pyupgrade
This commit is contained in:
parent
57d628ca74
commit
524fd0bc8c
54 changed files with 169 additions and 230 deletions
|
|
@ -1,22 +1,29 @@
|
|||
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
|
||||
rev: v1.5.0
|
||||
rev: v2.1.0
|
||||
hooks:
|
||||
- id: reorder-python-imports
|
||||
name: Reorder Python imports (src, tests)
|
||||
files: "^(?!examples/)"
|
||||
args: ["--application-directories", ".:src"]
|
||||
args: ["--application-directories", "src"]
|
||||
- repo: https://github.com/python/black
|
||||
rev: 19.3b0
|
||||
rev: 19.10b0
|
||||
hooks:
|
||||
- id: black
|
||||
- repo: https://gitlab.com/pycqa/flake8
|
||||
rev: 3.7.7
|
||||
rev: 3.7.9
|
||||
hooks:
|
||||
- id: flake8
|
||||
additional_dependencies: [flake8-bugbear]
|
||||
additional_dependencies:
|
||||
- flake8-bugbear
|
||||
- flake8-implicit-str-concat
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v2.2.3
|
||||
rev: v2.5.0
|
||||
hooks:
|
||||
- id: check-byte-order-marker
|
||||
- id: trailing-whitespace
|
||||
|
|
|
|||
10
docs/conf.py
10
docs/conf.py
|
|
@ -52,14 +52,12 @@ singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}
|
|||
html_static_path = ["_static"]
|
||||
html_favicon = "_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
|
||||
|
||||
# LaTeX ----------------------------------------------------------------
|
||||
|
||||
latex_documents = [
|
||||
(master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")
|
||||
]
|
||||
latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]
|
||||
|
||||
# Local Extensions -----------------------------------------------------
|
||||
|
||||
|
|
@ -76,9 +74,9 @@ def github_link(name, rawtext, text, lineno, inliner, options=None, content=None
|
|||
words = None
|
||||
|
||||
if packaging.version.parse(release).is_devrelease:
|
||||
url = "{0}master/{1}".format(base_url, text)
|
||||
url = f"{base_url}master/{text}"
|
||||
else:
|
||||
url = "{0}{1}/{2}".format(base_url, release, text)
|
||||
url = f"{base_url}{release}/{text}"
|
||||
|
||||
if words is None:
|
||||
words = url
|
||||
|
|
|
|||
|
|
@ -2,4 +2,4 @@ from flask import Flask
|
|||
|
||||
app = Flask(__name__)
|
||||
|
||||
from js_example import views
|
||||
from js_example import views # noqa: F401
|
||||
|
|
|
|||
|
|
@ -8,7 +8,7 @@ from js_example import app
|
|||
@app.route("/", defaults={"js": "plain"})
|
||||
@app.route("/<any(plain, jquery, fetch):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"])
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import io
|
||||
|
||||
from setuptools import find_packages
|
||||
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()
|
||||
|
||||
setup(
|
||||
|
|
|
|||
|
|
@ -64,7 +64,7 @@ def register():
|
|||
db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()
|
||||
is not None
|
||||
):
|
||||
error = "User {0} is already registered.".format(username)
|
||||
error = f"User {username} is already registered."
|
||||
|
||||
if error is None:
|
||||
# the name is available, store it in the database and go to
|
||||
|
|
|
|||
|
|
@ -49,7 +49,7 @@ def get_post(id, check_author=True):
|
|||
)
|
||||
|
||||
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"]:
|
||||
abort(403)
|
||||
|
|
|
|||
|
|
@ -1,9 +1,7 @@
|
|||
import io
|
||||
|
||||
from setuptools import find_packages
|
||||
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()
|
||||
|
||||
setup(
|
||||
|
|
|
|||
|
|
@ -44,7 +44,7 @@ def runner(app):
|
|||
return app.test_cli_runner()
|
||||
|
||||
|
||||
class AuthActions(object):
|
||||
class AuthActions:
|
||||
def __init__(self, client):
|
||||
self._client = client
|
||||
|
||||
|
|
|
|||
|
|
@ -17,7 +17,7 @@ def test_get_close_db(app):
|
|||
|
||||
|
||||
def test_init_db_command(runner, monkeypatch):
|
||||
class Recorder(object):
|
||||
class Recorder:
|
||||
called = False
|
||||
|
||||
def fake_init_db():
|
||||
|
|
|
|||
|
|
@ -20,7 +20,8 @@ source =
|
|||
# F = flake8 pyflakes
|
||||
# W = pycodestyle warnings
|
||||
# B9 = bugbear opinions
|
||||
select = B, E, F, W, B9
|
||||
# ISC = implicit-str-concat
|
||||
select = B, E, F, W, B9, ISC
|
||||
ignore =
|
||||
# slice notation whitespace, invalid
|
||||
E203
|
||||
|
|
@ -35,6 +36,5 @@ ignore =
|
|||
# up to 88 allowed by bugbear B950
|
||||
max-line-length = 80
|
||||
per-file-ignores =
|
||||
# __init__ modules export names
|
||||
**/__init__.py: F401
|
||||
src/flask/_compat.py: E731, B301, F401
|
||||
# __init__ module exports names
|
||||
src/flask/__init__.py: F401
|
||||
|
|
|
|||
5
setup.py
5
setup.py
|
|
@ -1,13 +1,12 @@
|
|||
import io
|
||||
import re
|
||||
|
||||
from setuptools import find_packages
|
||||
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()
|
||||
|
||||
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)
|
||||
|
||||
setup(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask
|
||||
~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.__main__
|
||||
~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -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}>"
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
)
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -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())
|
||||
|
|
|
|||
|
|
@ -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))
|
||||
|
|
|
|||
|
|
@ -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,
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.globals
|
||||
~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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("\\/", "/")
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
flask.templating
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
|
|
|||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.conftest
|
||||
~~~~~~~~~~~~~~
|
||||
|
|
@ -112,7 +111,7 @@ def limit_loader(request, monkeypatch):
|
|||
if not request.param:
|
||||
return
|
||||
|
||||
class LimitedLoader(object):
|
||||
class LimitedLoader:
|
||||
def __init__(self, loader):
|
||||
self.loader = loader
|
||||
|
||||
|
|
@ -172,7 +171,7 @@ def install_egg(modules_tmpdir, monkeypatch):
|
|||
textwrap.dedent(
|
||||
"""
|
||||
from setuptools import setup
|
||||
setup(name='{0}',
|
||||
setup(name='{}',
|
||||
version='1.0',
|
||||
packages=['site_egg'],
|
||||
zip_safe=True)
|
||||
|
|
@ -187,7 +186,7 @@ def install_egg(modules_tmpdir, monkeypatch):
|
|||
subprocess.check_call(
|
||||
[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))
|
||||
return egg_path
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.appctx
|
||||
~~~~~~~~~~~~
|
||||
|
|
@ -163,7 +162,7 @@ def test_app_ctx_globals_methods(app, app_ctx):
|
|||
|
||||
|
||||
def test_custom_app_ctx_globals_class(app):
|
||||
class CustomRequestGlobals(object):
|
||||
class CustomRequestGlobals:
|
||||
def __init__(self):
|
||||
self.spam = "eggs"
|
||||
|
||||
|
|
@ -190,7 +189,7 @@ def test_context_refcounts(app, client):
|
|||
pass
|
||||
env = flask._request_ctx_stack.top.request.environ
|
||||
assert env["werkzeug.request"] is not None
|
||||
return u""
|
||||
return ""
|
||||
|
||||
res = client.get("/")
|
||||
assert res.status_code == 200
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
from __future__ import absolute_import
|
||||
from __future__ import print_function
|
||||
|
||||
from flask import Flask
|
||||
|
||||
testapp = Flask("testapp")
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
from __future__ import absolute_import
|
||||
from __future__ import print_function
|
||||
|
||||
from flask import Flask
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
from __future__ import absolute_import
|
||||
from __future__ import print_function
|
||||
|
||||
from flask import Flask
|
||||
|
||||
raise ImportError()
|
||||
|
|
|
|||
|
|
@ -1,6 +1,3 @@
|
|||
from __future__ import absolute_import
|
||||
from __future__ import print_function
|
||||
|
||||
from flask import Flask
|
||||
|
||||
app1 = Flask("app1")
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
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):
|
||||
class PrefixPathMiddleware(object):
|
||||
class PrefixPathMiddleware:
|
||||
def __init__(self, app, prefix):
|
||||
self.app = app
|
||||
self.prefix = prefix
|
||||
|
|
@ -583,18 +582,18 @@ def test_extended_flashing(app):
|
|||
|
||||
@app.route("/")
|
||||
def index():
|
||||
flask.flash(u"Hello World")
|
||||
flask.flash(u"Hello World", "error")
|
||||
flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")
|
||||
flask.flash("Hello World")
|
||||
flask.flash("Hello World", "error")
|
||||
flask.flash(flask.Markup("<em>Testing</em>"), "warning")
|
||||
return ""
|
||||
|
||||
@app.route("/test/")
|
||||
def test():
|
||||
messages = flask.get_flashed_messages()
|
||||
assert list(messages) == [
|
||||
u"Hello World",
|
||||
u"Hello World",
|
||||
flask.Markup(u"<em>Testing</em>"),
|
||||
"Hello World",
|
||||
"Hello World",
|
||||
flask.Markup("<em>Testing</em>"),
|
||||
]
|
||||
return ""
|
||||
|
||||
|
|
@ -603,9 +602,9 @@ def test_extended_flashing(app):
|
|||
messages = flask.get_flashed_messages(with_categories=True)
|
||||
assert len(messages) == 3
|
||||
assert list(messages) == [
|
||||
("message", u"Hello World"),
|
||||
("error", u"Hello World"),
|
||||
("warning", flask.Markup(u"<em>Testing</em>")),
|
||||
("message", "Hello World"),
|
||||
("error", "Hello World"),
|
||||
("warning", flask.Markup("<em>Testing</em>")),
|
||||
]
|
||||
return ""
|
||||
|
||||
|
|
@ -614,7 +613,7 @@ def test_extended_flashing(app):
|
|||
messages = flask.get_flashed_messages(
|
||||
category_filter=["message"], with_categories=True
|
||||
)
|
||||
assert list(messages) == [("message", u"Hello World")]
|
||||
assert list(messages) == [("message", "Hello World")]
|
||||
return ""
|
||||
|
||||
@app.route("/test_filters/")
|
||||
|
|
@ -623,8 +622,8 @@ def test_extended_flashing(app):
|
|||
category_filter=["message", "warning"], with_categories=True
|
||||
)
|
||||
assert list(messages) == [
|
||||
("message", u"Hello World"),
|
||||
("warning", flask.Markup(u"<em>Testing</em>")),
|
||||
("message", "Hello World"),
|
||||
("warning", flask.Markup("<em>Testing</em>")),
|
||||
]
|
||||
return ""
|
||||
|
||||
|
|
@ -632,8 +631,8 @@ def test_extended_flashing(app):
|
|||
def test_filters2():
|
||||
messages = flask.get_flashed_messages(category_filter=["message", "warning"])
|
||||
assert len(messages) == 2
|
||||
assert messages[0] == u"Hello World"
|
||||
assert messages[1] == flask.Markup(u"<em>Testing</em>")
|
||||
assert messages[0] == "Hello World"
|
||||
assert messages[1] == flask.Markup("<em>Testing</em>")
|
||||
return ""
|
||||
|
||||
# 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):
|
||||
@app.route("/text")
|
||||
def from_text():
|
||||
return u"Hällo Wörld"
|
||||
return "Hällo Wörld"
|
||||
|
||||
@app.route("/bytes")
|
||||
def from_bytes():
|
||||
return u"Hällo Wörld".encode("utf-8")
|
||||
return "Hällo Wörld".encode()
|
||||
|
||||
@app.route("/full_tuple")
|
||||
def from_full_tuple():
|
||||
|
|
@ -1143,8 +1142,8 @@ def test_response_types(app, client):
|
|||
def from_dict():
|
||||
return {"foo": "bar"}, 201
|
||||
|
||||
assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")
|
||||
assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")
|
||||
assert client.get("/text").data == "Hällo Wörld".encode()
|
||||
assert client.get("/bytes").data == "Hällo Wörld".encode()
|
||||
|
||||
rv = client.get("/full_tuple")
|
||||
assert rv.data == b"Meh"
|
||||
|
|
@ -1611,11 +1610,11 @@ def test_inject_blueprint_url_defaults(app):
|
|||
|
||||
|
||||
def test_nonascii_pathinfo(app, client):
|
||||
@app.route(u"/киртест")
|
||||
@app.route("/киртест")
|
||||
def index():
|
||||
return "Hello World!"
|
||||
|
||||
rv = client.get(u"/киртест")
|
||||
rv = client.get("/киртест")
|
||||
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):
|
||||
class View(object):
|
||||
class View:
|
||||
def __init__(self, app):
|
||||
app.add_url_rule("/", "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
|
||||
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)
|
||||
hostname, port = "localhost", 8000
|
||||
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(
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.blueprints
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_cli
|
||||
~~~~~~~~~~~~~~
|
||||
|
|
@ -8,8 +7,6 @@
|
|||
"""
|
||||
# This file was part of Flask-CLI and was modified under the terms of
|
||||
# its Revised BSD License. Copyright © 2015 CERN.
|
||||
from __future__ import absolute_import
|
||||
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
|
|
@ -261,7 +258,7 @@ def test_get_version(test_apps, capsys):
|
|||
from werkzeug import __version__ as werkzeug_version
|
||||
from platform import python_version
|
||||
|
||||
class MockCtx(object):
|
||||
class MockCtx:
|
||||
resilient_parsing = False
|
||||
color = None
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_config
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
|
@ -65,7 +64,7 @@ def test_config_from_mapping():
|
|||
|
||||
|
||||
def test_config_from_class():
|
||||
class Base(object):
|
||||
class Base:
|
||||
TEST_KEY = "foo"
|
||||
|
||||
class Test(Base):
|
||||
|
|
@ -186,8 +185,8 @@ def test_from_pyfile_weird_encoding(tmpdir, encoding):
|
|||
f = tmpdir.join("my_config.py")
|
||||
f.write_binary(
|
||||
textwrap.dedent(
|
||||
u"""
|
||||
# -*- coding: {0} -*-
|
||||
"""
|
||||
# -*- coding: {} -*-
|
||||
TEST_VALUE = "föö"
|
||||
""".format(
|
||||
encoding
|
||||
|
|
@ -197,4 +196,4 @@ def test_from_pyfile_weird_encoding(tmpdir, encoding):
|
|||
app = flask.Flask(__name__)
|
||||
app.config.from_pyfile(str(f))
|
||||
value = app.config["TEST_VALUE"]
|
||||
assert value == u"föö"
|
||||
assert value == "föö"
|
||||
|
|
|
|||
|
|
@ -10,7 +10,7 @@ def test_custom_converters(app, client):
|
|||
return value.split(",")
|
||||
|
||||
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)
|
||||
|
||||
app.url_map.converters["list"] = ListConverter
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.helpers
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
|
@ -38,7 +37,7 @@ def has_encoding(name):
|
|||
return False
|
||||
|
||||
|
||||
class FakePath(object):
|
||||
class FakePath:
|
||||
"""Fake object to represent a ``PathLike object``.
|
||||
|
||||
This represents a ``pathlib.Path`` object in python 3.
|
||||
|
|
@ -73,9 +72,9 @@ class FixedOffset(datetime.tzinfo):
|
|||
return datetime.timedelta()
|
||||
|
||||
|
||||
class TestJSON(object):
|
||||
class TestJSON:
|
||||
@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(
|
||||
"encoding",
|
||||
|
|
@ -126,12 +125,12 @@ class TestJSON(object):
|
|||
assert rv.data == b"foo"
|
||||
|
||||
@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):
|
||||
|
||||
app.config["JSON_AS_ASCII"] = test_value
|
||||
rv = flask.json.dumps(u"\N{SNOWMAN}")
|
||||
rv = flask.json.dumps("\N{SNOWMAN}")
|
||||
assert rv == expected
|
||||
|
||||
def test_json_dump_to_file(self, app, app_ctx):
|
||||
|
|
@ -217,7 +216,7 @@ class TestJSON(object):
|
|||
)
|
||||
|
||||
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))
|
||||
rv = client.get(url)
|
||||
assert rv.mimetype == "application/json"
|
||||
|
|
@ -262,7 +261,7 @@ class TestJSON(object):
|
|||
def test_template_escaping(self, app, req_ctx):
|
||||
render = flask.render_template_string
|
||||
rv = flask.json.htmlsafe_dumps("</script>")
|
||||
assert rv == u'"\\u003c/script\\u003e"'
|
||||
assert rv == '"\\u003c/script\\u003e"'
|
||||
assert type(rv) is str
|
||||
rv = render('{{ "</script>"|tojson }}')
|
||||
assert rv == '"\\u003c/script\\u003e"'
|
||||
|
|
@ -280,7 +279,7 @@ class TestJSON(object):
|
|||
assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'
|
||||
|
||||
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):
|
||||
self.val = val
|
||||
|
||||
|
|
@ -315,7 +314,7 @@ class TestJSON(object):
|
|||
assert rv.data == b'"<42>"'
|
||||
|
||||
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):
|
||||
self.val = val
|
||||
|
||||
|
|
@ -368,9 +367,9 @@ class TestJSON(object):
|
|||
def index():
|
||||
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.data == u"정상처리".encode("utf-8")
|
||||
assert rv.data == "정상처리".encode()
|
||||
|
||||
def test_json_key_sorting(self, app, client):
|
||||
app.debug = True
|
||||
|
|
@ -443,7 +442,7 @@ class TestJSON(object):
|
|||
assert lines == sorted_by_str
|
||||
|
||||
|
||||
class PyBytesIO(object):
|
||||
class PyBytesIO:
|
||||
def __init__(self, *args, **kwargs):
|
||||
self._io = io.BytesIO(*args, **kwargs)
|
||||
|
||||
|
|
@ -451,7 +450,7 @@ class PyBytesIO(object):
|
|||
return getattr(self._io, name)
|
||||
|
||||
|
||||
class TestSendfile(object):
|
||||
class TestSendfile:
|
||||
def test_send_file_regular(self, app, req_ctx):
|
||||
rv = flask.send_file("static/index.html")
|
||||
assert rv.direct_passthrough
|
||||
|
|
@ -516,7 +515,7 @@ class TestSendfile(object):
|
|||
@pytest.mark.parametrize(
|
||||
"opener",
|
||||
[
|
||||
lambda app: io.StringIO(u"Test"),
|
||||
lambda app: io.StringIO("Test"),
|
||||
lambda app: open(os.path.join(app.static_folder, "index.html")),
|
||||
],
|
||||
)
|
||||
|
|
@ -673,13 +672,13 @@ class TestSendfile(object):
|
|||
(
|
||||
("index.html", "index.html", False),
|
||||
(
|
||||
u"Ñandú/pingüino.txt",
|
||||
"Ñandú/pingüino.txt",
|
||||
'"Nandu/pinguino.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
|
||||
(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):
|
||||
|
|
@ -775,7 +774,7 @@ class TestSendfile(object):
|
|||
flask.send_from_directory("static", "bad\x00")
|
||||
|
||||
|
||||
class TestUrlFor(object):
|
||||
class TestUrlFor:
|
||||
def test_url_for_with_anchor(self, app, req_ctx):
|
||||
@app.route("/")
|
||||
def index():
|
||||
|
|
@ -834,7 +833,7 @@ class TestUrlFor(object):
|
|||
assert flask.url_for("myview", _method="POST") == "/myview/create"
|
||||
|
||||
|
||||
class TestNoImports(object):
|
||||
class TestNoImports:
|
||||
"""Test Flasks are created without import.
|
||||
|
||||
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.")
|
||||
|
||||
|
||||
class TestStreaming(object):
|
||||
class TestStreaming:
|
||||
def test_streaming_with_context(self, app, client):
|
||||
@app.route("/")
|
||||
def index():
|
||||
|
|
@ -884,7 +883,7 @@ class TestStreaming(object):
|
|||
def test_streaming_with_context_and_custom_close(self, app, client):
|
||||
called = []
|
||||
|
||||
class Wrapper(object):
|
||||
class Wrapper:
|
||||
def __init__(self, gen):
|
||||
self._gen = gen
|
||||
|
||||
|
|
@ -927,7 +926,7 @@ class TestStreaming(object):
|
|||
assert rv.data == b"flask"
|
||||
|
||||
|
||||
class TestSafeJoin(object):
|
||||
class TestSafeJoin:
|
||||
def test_safe_join(self):
|
||||
# Valid combinations of *args and expected joined paths.
|
||||
passing = (
|
||||
|
|
@ -968,7 +967,7 @@ class TestSafeJoin(object):
|
|||
print(flask.safe_join(*args))
|
||||
|
||||
|
||||
class TestHelpers(object):
|
||||
class TestHelpers:
|
||||
@pytest.mark.parametrize(
|
||||
"debug, expected_flag, expected_default_flag",
|
||||
[
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_instance
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_json_tag
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
|
@ -48,7 +47,7 @@ def test_duplicate_tag():
|
|||
|
||||
|
||||
def test_custom_tag():
|
||||
class Foo(object): # noqa: B903, for Python2 compatibility
|
||||
class Foo: # noqa: B903, for Python2 compatibility
|
||||
def __init__(self, data):
|
||||
self.data = data
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_logging
|
||||
~~~~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.regression
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
|
@ -20,7 +19,7 @@ import flask
|
|||
_gc_lock = threading.Lock()
|
||||
|
||||
|
||||
class assert_no_leak(object):
|
||||
class assert_no_leak:
|
||||
def __enter__(self):
|
||||
gc.disable()
|
||||
_gc_lock.acquire()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.reqctx
|
||||
~~~~~~~~~~~~
|
||||
|
|
@ -150,7 +149,7 @@ def test_manual_context_binding(app):
|
|||
|
||||
|
||||
@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")
|
||||
class TestGreenletContextCopying(object):
|
||||
class TestGreenletContextCopying:
|
||||
def test_greenlet_context_copying(self, app, client):
|
||||
greenlets = []
|
||||
|
||||
|
|
@ -239,7 +238,7 @@ def test_session_dynamic_cookie_name():
|
|||
if flask.request.url.endswith("dynamic_cookie"):
|
||||
return "dynamic_cookie_name"
|
||||
else:
|
||||
return super(PathAwareSessionInterface, self).get_cookie_name(app)
|
||||
return super().get_cookie_name(app)
|
||||
|
||||
class CustomFlask(flask.Flask):
|
||||
session_interface = PathAwareSessionInterface()
|
||||
|
|
@ -291,7 +290,7 @@ def test_bad_environ_raises_bad_request():
|
|||
environ = builder.get_environ()
|
||||
|
||||
# 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):
|
||||
response = app.full_dispatch_request()
|
||||
|
|
@ -311,7 +310,7 @@ def test_environ_for_valid_idna_completes():
|
|||
environ = builder.get_environ()
|
||||
|
||||
# these characters are all IDNA-compatible
|
||||
environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"
|
||||
environ["HTTP_HOST"] = "ąśźäüжŠßя.com"
|
||||
|
||||
with app.request_context(environ):
|
||||
response = app.full_dispatch_request()
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.signals
|
||||
~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.subclassing
|
||||
~~~~~~~~~~~~~~~~~
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.templating
|
||||
~~~~~~~~~~~~~~~~
|
||||
|
|
@ -417,14 +416,14 @@ def test_template_loader_debugging(test_apps, monkeypatch):
|
|||
text = str(record.msg)
|
||||
assert '1: trying loader of application "blueprintapp"' in text
|
||||
assert (
|
||||
'2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"
|
||||
'2: trying loader of blueprint "admin" (blueprintapp.apps.admin)'
|
||||
) in text
|
||||
assert (
|
||||
'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"
|
||||
'trying loader of blueprint "frontend" (blueprintapp.apps.frontend)'
|
||||
) in text
|
||||
assert "Error: the template could not be found" in text
|
||||
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
|
||||
assert "See https://flask.palletsprojects.com/blueprints/#templates" in text
|
||||
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.testing
|
||||
~~~~~~~~~~~~~
|
||||
|
|
@ -122,8 +121,8 @@ def test_path_is_url(app):
|
|||
def test_environbuilder_json_dumps(app):
|
||||
"""EnvironBuilder.json_dumps() takes settings from the app."""
|
||||
app.config["JSON_AS_ASCII"] = False
|
||||
eb = EnvironBuilder(app, json=u"\u20ac")
|
||||
assert eb.input_stream.read().decode("utf8") == u'"\u20ac"'
|
||||
eb = EnvironBuilder(app, json="\u20ac")
|
||||
assert eb.input_stream.read().decode("utf8") == '"\u20ac"'
|
||||
|
||||
|
||||
def test_blueprint_with_subdomain():
|
||||
|
|
@ -324,7 +323,7 @@ def test_client_json_no_app_context(app, client):
|
|||
def hello():
|
||||
return "Hello, {}!".format(flask.request.json["name"])
|
||||
|
||||
class Namespace(object):
|
||||
class Namespace:
|
||||
count = 0
|
||||
|
||||
def add(self, app):
|
||||
|
|
@ -402,7 +401,7 @@ def test_cli_invoke(app):
|
|||
|
||||
|
||||
def test_cli_custom_obj(app):
|
||||
class NS(object):
|
||||
class NS:
|
||||
called = False
|
||||
|
||||
def create_app():
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.test_user_error_handler
|
||||
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
|
||||
|
|
@ -208,7 +207,7 @@ def test_default_error_handler():
|
|||
assert c.get("/slash", follow_redirects=True).data == b"slash"
|
||||
|
||||
|
||||
class TestGenericHandlers(object):
|
||||
class TestGenericHandlers:
|
||||
"""Test how very generic handlers are dispatched to."""
|
||||
|
||||
class Custom(Exception):
|
||||
|
|
|
|||
|
|
@ -1,4 +1,3 @@
|
|||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
tests.views
|
||||
~~~~~~~~~~~
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue