apply pyupgrade
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parent 57d628c · Browse files · 54 files·+169 added−230 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
54 files+169 added−230 removed
- tests:+74 added−106 removed
- other:+95 added−124 removed
Provenance
- Commit
524fd0b- Tree
62fe16e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
57d628c
54 files changed+169 added−230 removed
modified:docs/conf.py+4 added-6 removed
50 unmodified lines51 singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}52 html_static_path = ["_static"]53 html_favicon = "_static/flask-icon.png"54 html_logo = "_static/flask-icon.png"55-html_title = "Flask Documentation ({})".format(version)55+html_title = f"Flask Documentation ({version})"56 html_show_sourcelink = False57 58 # LaTeX ----------------------------------------------------------------59 60-latex_documents = [61- (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")62-]60+latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]61 62 # Local Extensions -----------------------------------------------------63 64 8 unmodified lines73 else:74 words = None75 76 if packaging.version.parse(release).is_devrelease:79- url = "{0}master/{1}".format(base_url, text)77+ url = f"{base_url}master/{text}"78 else:81- url = "{0}{1}/{2}".format(base_url, release, text)79+ url = f"{base_url}{release}/{text}"80 81 if words is None:82 words = url83 11 unmodified linesmodified:examples/javascript/js_example/__init__.py+1 added-1 removed
1 from flask import Flask2 3 app = Flask(__name__)4 5-from js_example import views5+from js_example import views # noqa: F401modified:examples/javascript/js_example/views.py+1 added-1 removed
6 unmodified lines7 8 @app.route("/", defaults={"js": "plain"})9 @app.route("/<any(plain, jquery, fetch):js>")10 def index(js):11- return render_template("{0}.html".format(js), js=js)11+ return render_template(f"{js}.html", js=js)12 13 14 @app.route("/add", methods=["POST"])15 def add():3 unmodified linesmodified:examples/javascript/setup.py+1 added-3 removed
1-import io2-1 from setuptools import find_packages2 from setuptools import setup3 6-with io.open("README.rst", "rt", encoding="utf8") as f:4+with open("README.rst", encoding="utf8") as f:5 readme = f.read()6 7 setup(8 name="js_example",13 unmodified linesmodified:examples/tutorial/flaskr/auth.py+1 added-1 removed
62 unmodified lines63 elif (64 db.execute("SELECT id FROM user WHERE username = ?", (username,)).fetchone()65 is not None66 ):67- error = "User {0} is already registered.".format(username)67+ error = f"User {username} is already registered."68 69 if error is None:70 # the name is available, store it in the database and go to71 # the login page45 unmodified linesmodified:examples/tutorial/flaskr/blog.py+1 added-1 removed
47 unmodified lines48 .fetchone()49 )50 51 if post is None:52- abort(404, "Post id {0} doesn't exist.".format(id))52+ abort(404, f"Post id {id} doesn't exist.")53 54 if check_author and post["author_id"] != g.user["id"]:55 abort(403)56 69 unmodified linesmodified:examples/tutorial/tests/conftest.py+1 added-1 removed
42 unmodified lines43 """A test runner for the app's Click commands."""44 return app.test_cli_runner()45 46 47-class AuthActions(object):47+class AuthActions:48 def __init__(self, client):49 self._client = client50 51 def login(self, username="test", password="test"):11 unmodified linesmodified:examples/tutorial/tests/test_db.py+1 added-1 removed
15 unmodified lines16 assert "closed" in str(e.value)17 18 19 def test_init_db_command(runner, monkeypatch):20- class Recorder(object):20+ class Recorder:21 called = False22 23 def fake_init_db():24 Recorder.called = True5 unmodified linesmodified:examples/tutorial/setup.py+1 added-3 removed
1-import io2-1 from setuptools import find_packages2 from setuptools import setup3 6-with io.open("README.rst", "rt", encoding="utf8") as f:4+with open("README.rst", encoding="utf8") as f:5 readme = f.read()6 7 setup(8 name="flaskr",13 unmodified linesmodified:src/flask/json/__init__.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 flask.json3 ~~~~~~~~~~4 279 unmodified lines284 filter. Alternatively use ``|tojson|forceescape``.285 """286 rv = (287 dumps(obj, **kwargs)289- .replace(u"<", u"\\u003c")290- .replace(u">", u"\\u003e")291- .replace(u"&", u"\\u0026")292- .replace(u"'", u"\\u0027")288+ .replace("<", "\\u003c")289+ .replace(">", "\\u003e")290+ .replace("&", "\\u0026")291+ .replace("'", "\\u0027")292 )293 if not _slash_escape:294 rv = rv.replace("\\/", "/")295 return rv78 unmodified linesmodified:src/flask/json/tag.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 Tagged JSON3 ~~~~~~~~~~~4 47 unmodified lines52 from ..json import dumps53 from ..json import loads54 55 57-class JSONTag(object):56+class JSONTag:57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""58 59 __slots__ = ("serializer",)60 59 unmodified lines120 121 def to_json(self, value):122 # JSON objects may only have string keys, so don't bother tagging the123 # key here.125- return dict((k, self.serializer.tag(v)) for k, v in value.items())124+ return {k: self.serializer.tag(v) for k, v in value.items()}125 126 tag = to_json127 128 82 unmodified lines211 def to_python(self, value):212 return parse_date(value)213 214 216-class TaggedJSONSerializer(object):215+class TaggedJSONSerializer:216 """Serializer that uses a tag system to compactly represent objects that217 are not JSON types. Passed as the intermediate serializer to218 :class:`itsdangerous.Serializer`.219 47 unmodified lines267 key = tag.key268 269 if key is not None:270 if not force and key in self.tags:272- raise KeyError("Tag '{0}' is already registered.".format(key))271+ raise KeyError(f"Tag '{key}' is already registered.")272 273 self.tags[key] = tag274 275 if index is None:31 unmodified linesmodified:src/flask/__init__.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask3 ~~~~~4 54 unmodified linesmodified:src/flask/__main__.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.__main__3 ~~~~~~~~~~~~~~4 10 unmodified linesmodified:src/flask/app.py+6 added-7 removed
1-# -*- coding: utf-8 -*-1 """2 flask.app3 ~~~~~~~~~4 1104 unmodified lines1109 rule,1110 endpoint=None,1111 view_func=None,1112 provide_automatic_options=None,1114- **options1113+ **options,1114 ):1115 """Connects a URL rule. Works exactly like the :meth:`route`1116 decorator. If a view_func is provided it will be registered with the1117 endpoint.60 unmodified lines1178 raise TypeError(1179 "Allowed methods must be a list of strings, for"1180 ' example: @app.route(..., methods=["POST"])'1181 )1183- methods = set(item.upper() for item in methods)1182+ methods = {item.upper() for item in methods}1183 1184 # Methods that should always be added1185 required_methods = set(getattr(view_func, "required_methods", ()))1186 153 unmodified lines1340 :type f: callable1341 """1342 if isinstance(code_or_exception, HTTPException): # old broken behavior1343 raise ValueError(1345- "Tried to register a handler for an exception instance {0!r}."1344+ "Tried to register a handler for an exception instance {!r}."1345 " Handlers can only be registered for exception classes or"1346 " HTTP error codes.".format(code_or_exception)1347 )1348 1349 try:1350 exc_class, code = self._get_exc_class_and_code(code_or_exception)1351 except KeyError:1352 raise KeyError(1354- "'{0}' is not a recognized HTTP error code. Use a subclass of"1353+ "'{}' is not a recognized HTTP error code. Use a subclass of"1354 " HTTPException with that code instead.".format(code_or_exception)1355 )1356 1357 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})451 unmodified lines1809 1810 .. versionadded:: 0.81811 """1812 self.logger.error(1814- "Exception on %s [%s]" % (request.path, request.method), exc_info=exc_info1813+ f"Exception on {request.path} [{request.method}]", exc_info=exc_info1814 )1815 1816 def raise_routing_exception(self, request):1817 """Exceptions that are recording during routing are reraised with556 unmodified lines2374 wrapped to applying middleware."""2375 return self.wsgi_app(environ, start_response)2376 2377 def __repr__(self):2379- return "<%s %r>" % (self.__class__.__name__, self.name)2378+ return f"<{self.__class__.__name__} {self.name!r}>"modified:src/flask/blueprints.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 flask.blueprints3 ~~~~~~~~~~~~~~~~4 11 unmodified lines16 # a singleton sentinel value for parameter defaults17 _sentinel = object()18 19 21-class BlueprintSetupState(object):20+class BlueprintSetupState:21 """Temporary holder object for registering a blueprint with the22 application. An instance of this class is created by the23 :meth:`~flask.Blueprint.make_setup_state` method and later passed24 to all register callback functions.53 unmodified lines78 if "defaults" in options:79 defaults = dict(defaults, **options.pop("defaults"))80 self.app.add_url_rule(81 rule,83- "%s.%s" % (self.blueprint.name, endpoint),82+ f"{self.blueprint.name}.{endpoint}",83 view_func,84 defaults=defaults,86- **options85+ **options,86 )87 88 89 class Blueprint(_PackageBoundObject):479 unmodified linesmodified:src/flask/cli.py+13 added-20 removed
1-# -*- coding: utf-8 -*-1 """2 flask.cli3 ~~~~~~~~~4 1 unmodified line6 7 :copyright: 2010 Pallets8 :license: BSD-3-Clause9 """11-from __future__ import print_function12-10 import ast11 import inspect12 import os13 import platform149 unmodified lines163 164 if inspect.isfunction(attr):165 if args:166 try:170- args = ast.literal_eval("({args},)".format(args=args))167+ args = ast.literal_eval(f"({args},)")168 except (ValueError, SyntaxError) as e:169 raise NoAppException(170 "Could not parse the arguments in "171 '"{app_name}".'.format(e=e, app_name=app_name)67 unmodified lines239 'While importing "{name}", an ImportError was raised:'240 "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())241 )242 elif raise_if_not_found:246- raise NoAppException('Could not import "{name}".'.format(name=module_name))243+ raise NoAppException(f'Could not import "{module_name}".')244 else:245 return246 247 module = sys.modules[module_name]33 unmodified lines281 is_eager=True,282 )283 284 288-class DispatchingApp(object):285+class DispatchingApp:286 """Special application that dispatches to a Flask application which287 is imported by name in a background thread. If an error happens288 it is recorded and shown as part of the WSGI handling which in case289 of the Werkzeug debugger means that it shows up in the browser.50 unmodified lines340 rv = self._load_unlocked()341 return rv(environ, start_response)342 343 347-class ScriptInfo(object):344+class ScriptInfo:345 """Helper object to deal with Flask applications. This is usually not346 necessary to interface with as it's used internally in the dispatching347 to click. In future versions of Flask this object will most likely play348 a bigger role. Typically it's created automatically by the138 unmodified lines487 create_app=None,488 add_version_option=True,489 load_dotenv=True,490 set_debug_flag=True,494- **extra491+ **extra,492 ):493 params = list(extra.pop("params", None) or ())494 495 if add_version_option:83 unmodified lines579 )580 581 kwargs["obj"] = obj582 kwargs.setdefault("auto_envvar_prefix", "FLASK")586- return super(FlaskGroup, self).main(*args, **kwargs)583+ return super().main(*args, **kwargs)584 585 586 def _path_is_ancestor(path, other):587 """Take ``other`` and remove the length of ``path`` from it. Then join it70 unmodified lines658 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":659 return660 661 if app_import_path is not None:665- message = ' * Serving Flask app "{0}"'.format(app_import_path)662+ message = f' * Serving Flask app "{app_import_path}"'663 664 if not eager_loading:665 message += " (lazy loading)"666 667 click.echo(message)668 672- click.echo(" * Environment: {0}".format(env))669+ click.echo(f" * Environment: {env}")670 671 if env == "production":672 click.secho(673 " WARNING: This is a development server. "2 unmodified lines676 )677 click.secho(" Use a production WSGI server instead.", dim=True)678 679 if debug is not None:683- click.echo(" * Debug mode: {0}".format("on" if debug else "off"))680+ click.echo(" * Debug mode: {}".format("on" if debug else "off"))681 682 683 class CertParamType(click.ParamType):684 """Click option type for the ``--cert`` option. Allows either an77 unmodified lines762 """763 764 def convert(self, value, param, ctx):765 items = self.split_envvar_value(value)769- super_convert = super(SeparatedPathType, self).convert766+ super_convert = super().convert767 return [super_convert(item, param, ctx) for item in items]768 769 770 @click.command("run", short_help="Run a development server.")91 unmodified lines862 import code863 from .globals import _app_ctx_stack864 865 app = _app_ctx_stack.top.app869- banner = "Python %s on %s\nApp: %s [%s]\nInstance: %s" % (870- sys.version,871- sys.platform,872- app.import_name,873- app.env,874- app.instance_path,866+ banner = "Python {} on {}\nApp: {} [{}]\nInstance: {}".format(867+ sys.version, sys.platform, app.import_name, app.env, app.instance_path,868 )869 ctx = {}870 871 # Support the regular Python interpreter startup script if someone872 # is using it.873 startup = os.environ.get("PYTHONSTARTUP")874 if startup and os.path.isfile(startup):882- with open(startup, "r") as f:875+ with open(startup) as f:876 eval(compile(f.read(), startup, "exec"), ctx)877 878 ctx.update(app.make_shell_context())879 76 unmodified linesmodified:src/flask/config.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 flask.config3 ~~~~~~~~~~~~4 8 unmodified lines13 14 from werkzeug.utils import import_string15 16 18-class ConfigAttribute(object):17+class ConfigAttribute:18 """Makes an attribute forward to the config"""19 20 def __init__(self, name, get_converter=None):21 self.__name__ = name102 unmodified lines124 d.__file__ = filename125 try:126 with open(filename, mode="rb") as config_file:127 exec(compile(config_file.read(), filename, "exec"), d.__dict__)129- except IOError as e:128+ except OSError as e:129 if silent and e.errno in (errno.ENOENT, errno.EISDIR, errno.ENOTDIR):130 return False131 e.strerror = "Unable to load configuration file (%s)" % e.strerror132 raise62 unmodified lines195 196 try:197 with open(filename) as f:198 obj = load(f)200- except IOError as e:199+ except OSError as e:200 if silent and e.errno in (errno.ENOENT, errno.EISDIR):201 return False202 203 e.strerror = "Unable to load configuration file (%s)" % e.strerror65 unmodified lines269 rv[key] = v270 return rv271 272 def __repr__(self):274- return "<%s %s>" % (self.__class__.__name__, dict.__repr__(self))273+ return "<{} {}>".format(self.__class__.__name__, dict.__repr__(self))modified:src/flask/ctx.py+8 added-10 removed
1-# -*- coding: utf-8 -*-1 """2 flask.ctx3 ~~~~~~~~~4 16 unmodified lines21 # a singleton sentinel value for parameter defaults22 _sentinel = object()23 24 26-class _AppCtxGlobals(object):25+class _AppCtxGlobals:26 """A plain object. Used as a namespace for storing data during an27 application context.28 29 Creating an app context automatically creates this object, which is168 unmodified lines198 """199 return _app_ctx_stack.top is not None200 201 203-class AppContext(object):202+class AppContext:203 """The application context binds an application object implicitly204 to the current thread or greenlet, similar to how the205 :class:`RequestContext` binds request information. The application206 context is also implicitly created if a request context is created25 unmodified lines232 exc = sys.exc_info()[1]233 self.app.do_teardown_appcontext(exc)234 finally:235 rv = _app_ctx_stack.pop()237- assert rv is self, "Popped wrong app context. (%r instead of %r)" % (rv, self)236+ assert rv is self, f"Popped wrong app context. ({rv!r} instead of {self!r})"237 appcontext_popped.send(self.app)238 239 def __enter__(self):240 self.push()2 unmodified lines243 def __exit__(self, exc_type, exc_value, tb):244 self.pop(exc_value)245 246 248-class RequestContext(object):247+class RequestContext:248 """The request context contains all request relevant information. It is249 created at the beginning of the request and pushed to the250 `_request_ctx_stack` and removed at the end of it. It will create the251 URL adapter and request object for the WSGI environment provided.166 unmodified lines418 # Get rid of the app as well if necessary.419 if app_ctx is not None:420 app_ctx.pop(exc)421 423- assert rv is self, "Popped wrong request context. (%r instead of %r)" % (424- rv,425- self,426- )422+ assert (423+ rv is self424+ ), f"Popped wrong request context. ({rv!r} instead of {self!r})"425 426 def auto_pop(self, exc):427 if self.request.environ.get("flask._preserve_context") or (428 exc is not None and self.app.preserve_context_on_exception15 unmodified lines444 # See flask.testing for how this works.445 self.auto_pop(exc_value)446 447 def __repr__(self):450- return "<%s '%s' [%s] of %s>" % (448+ return "<{} '{}' [{}] of {}>".format(449 self.__class__.__name__,450 self.request.url,451 self.request.method,452 self.app.name,1 unmodified linemodified:src/flask/debughelpers.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 flask.debughelpers3 ~~~~~~~~~~~~~~~~~~4 95 unmodified lines100 request.files.__class__ = newcls101 102 103 def _dump_loader_info(loader):105- yield "class: %s.%s" % (type(loader).__module__, type(loader).__name__)104+ yield "class: {}.{}".format(type(loader).__module__, type(loader).__name__)105 for key, value in sorted(loader.__dict__.items()):106 if key.startswith("_"):107 continue108 if isinstance(value, (tuple, list)):4 unmodified lines113 yield " - %s" % item114 continue115 elif not isinstance(value, (str, int, float, bool)):116 continue118- yield "%s: %r" % (key, value)117+ yield f"{key}: {value!r}"118 119 120 def explain_template_loading_attempts(app, template, attempts):121 """This should help developers understand what failed"""7 unmodified lines129 for idx, (loader, srcobj, triple) in enumerate(attempts):130 if isinstance(srcobj, Flask):131 src_info = 'application "%s"' % srcobj.import_name132 elif isinstance(srcobj, Blueprint):134- src_info = 'blueprint "%s" (%s)' % (srcobj.name, srcobj.import_name)133+ src_info = f'blueprint "{srcobj.name}" ({srcobj.import_name})'134 else:135 src_info = repr(srcobj)136 137 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))42 unmodified linesmodified:src/flask/globals.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.globals3 ~~~~~~~~~~~~~4 57 unmodified linesmodified:src/flask/helpers.py+4 added-6 removed
1-# -*- coding: utf-8 -*-1 """2 flask.helpers3 ~~~~~~~~~~~~~4 148 unmodified lines153 # iterator in we're still running the cleanup logic. Generators154 # don't need that because they are closed on their destruction155 # automatically.156 try:158- for item in gen:159- yield item157+ yield from gen158 finally:159 if hasattr(gen, "close"):160 gen.close()161 768 unmodified lines930 return base_dir, package_path931 return None, package_path932 933 936-class locked_cached_property(object):934+class locked_cached_property:935 """A decorator that converts a function into a lazy property. The936 function wrapped is called the first time to retrieve the result937 and then that calculated result is used the next time you access938 the value. Works like the one in Werkzeug but has a lock for17 unmodified lines956 obj.__dict__[self.__name__] = value957 return value958 959 962-class _PackageBoundObject(object):960+class _PackageBoundObject:961 #: The name of the package or module that this app belongs to. Do not962 #: change this once it is set by the constructor.963 import_name = None964 169 unmodified lines1134 """1135 for family in (socket.AF_INET, socket.AF_INET6):1136 try:1137 socket.inet_pton(family, value)1140- except socket.error:1138+ except OSError:1139 pass1140 else:1141 return True1142 1 unmodified linemodified:src/flask/logging.py-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.logging3 ~~~~~~~~~~~~~4 5 :copyright: 2010 Pallets6 :license: BSD-3-Clause7 """9-from __future__ import absolute_import10-8 import logging9 import sys10 11 from werkzeug.local import LocalProxy66 unmodified linesmodified:src/flask/sessions.py+5 added-6 removed
1-# -*- coding: utf-8 -*-1 """2 flask.sessions3 ~~~~~~~~~~~~~~4 70 unmodified lines75 def on_update(self):76 self.modified = True77 self.accessed = True78 80- super(SecureCookieSession, self).__init__(initial, on_update)79+ super().__init__(initial, on_update)80 81 def __getitem__(self, key):82 self.accessed = True84- return super(SecureCookieSession, self).__getitem__(key)83+ return super().__getitem__(key)84 85 def get(self, key, default=None):86 self.accessed = True88- return super(SecureCookieSession, self).get(key, default)87+ return super().get(key, default)88 89 def setdefault(self, key, default=None):90 self.accessed = True92- return super(SecureCookieSession, self).setdefault(key, default)91+ return super().setdefault(key, default)92 93 94 class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not11 unmodified lines107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109 110 112-class SessionInterface(object):111+class SessionInterface:112 """The basic interface you have to implement in order to replace the113 default session interface which uses werkzeug's securecookie114 implementation. The only methods you have to implement are115 :meth:`open_session` and :meth:`save_session`, the others have278 unmodified linesmodified:src/flask/signals.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.signals3 ~~~~~~~~~~~~~4 9 unmodified lines14 signals_available = True15 except ImportError:16 signals_available = False17 19- class Namespace(object):18+ class Namespace:19 def signal(self, name, doc=None):20 return _FakeSignal(name, doc)21 23- class _FakeSignal(object):22+ class _FakeSignal:23 """If blinker is unavailable, create a fake class with the same24 interface that allows sending of signals but will fail with an25 error on anything else. Instead of doing anything on send, it26 will just ignore the arguments and do nothing instead.38 unmodified linesmodified:src/flask/templating.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 flask.templating3 ~~~~~~~~~~~~~~~~4 150 unmodified linesmodified:src/flask/testing.py+6 added-7 removed
1-# -*- coding: utf-8 -*-1 """2 flask.testing3 ~~~~~~~~~~~~~4 44 unmodified lines49 base_url=None,50 subdomain=None,51 url_scheme=None,52 *args,54- **kwargs53+ **kwargs,54 ):55 assert not (base_url or subdomain or url_scheme) or (56 base_url is not None57 ) != bool(4 unmodified lines62 http_host = app.config.get("SERVER_NAME") or "localhost"63 app_root = app.config["APPLICATION_ROOT"]64 65 if subdomain:67- http_host = "{0}.{1}".format(subdomain, http_host)66+ http_host = f"{subdomain}.{http_host}"67 68 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]70 9 unmodified lines80 sep = b"?" if isinstance(url.query, bytes) else "?"81 path += sep + url.query82 83 self.app = app85- super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)84+ super().__init__(path, base_url, *args, **kwargs)85 86 def json_dumps(self, obj, **kwargs):87 """Serialize ``obj`` to a JSON-formatted string.88 21 unmodified lines110 111 preserve_context = False112 113 def __init__(self, *args, **kwargs):115- super(FlaskClient, self).__init__(*args, **kwargs)114+ super().__init__(*args, **kwargs)115 self.environ_base = {116 "REMOTE_ADDR": "127.0.0.1",117 "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,118 }118 unmodified lines237 """238 239 def __init__(self, app, **kwargs):240 self.app = app242- super(FlaskCliRunner, self).__init__(**kwargs)241+ super().__init__(**kwargs)242 243 def invoke(self, cli=None, args=None, **kwargs):244 """Invokes a CLI command in an isolated environment. See245 :meth:`CliRunner.invoke <click.testing.CliRunner.invoke>` for14 unmodified lines260 261 if "obj" not in kwargs:262 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)263 265- return super(FlaskCliRunner, self).invoke(cli, args, **kwargs)264+ return super().invoke(cli, args, **kwargs)modified:src/flask/views.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.views3 ~~~~~~~~~~~4 9 unmodified lines14 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]15 )16 17 19-class View(object):18+class View:19 """Alternative way to use view functions. A subclass has to implement20 :meth:`dispatch_request` which is called with the view arguments from21 the URL routing system. If :attr:`methods` is provided the methods22 do not have to be passed to the :meth:`~flask.Flask.add_url_rule`88 unmodified lines111 defines.112 """113 114 def __init__(cls, name, bases, d):116- super(MethodViewType, cls).__init__(name, bases, d)115+ super().__init__(name, bases, d)116 117 if "methods" not in d:118 methods = set()119 42 unmodified linesmodified:src/flask/wrappers.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 flask.wrappers3 ~~~~~~~~~~~~~~4 15 unmodified lines20 json_module = json21 22 def on_json_loading_failed(self, e):23 if current_app and current_app.debug:25- raise BadRequest("Failed to decode JSON object: {0}".format(e))24+ raise BadRequest(f"Failed to decode JSON object: {e}")25 26 raise BadRequest()27 28 103 unmodified lines132 if current_app:133 return current_app.config["MAX_COOKIE_SIZE"]134 135 # return Werkzeug's default when not in an app context137- return super(Response, self).max_cookie_size136+ return super().max_cookie_sizemodified:tests/test_apps/cliapp/app.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 testapp = Flask("testapp")modified:tests/test_apps/cliapp/factory.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 4 def create_app():13 unmodified linesmodified:tests/test_apps/cliapp/importerrorapp.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 raise ImportError()4 1 unmodified linemodified:tests/test_apps/cliapp/multiapp.py-3 removed
1-from __future__ import absolute_import2-from __future__ import print_function3-1 from flask import Flask2 3 app1 = Flask("app1")4 app2 = Flask("app2")modified:tests/conftest.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 tests.conftest3 ~~~~~~~~~~~~~~4 105 unmodified lines110 """111 if not request.param:112 return113 115- class LimitedLoader(object):114+ class LimitedLoader:115 def __init__(self, loader):116 self.loader = loader117 118 def __getattr__(self, name):51 unmodified lines170 egg_setup.write(171 textwrap.dedent(172 """173 from setuptools import setup175- setup(name='{0}',174+ setup(name='{}',175 version='1.0',176 packages=['site_egg'],177 zip_safe=True)178 """.format(6 unmodified lines185 186 subprocess.check_call(187 [sys.executable, "setup.py", "bdist_egg"], cwd=str(modules_tmpdir)188 )190- egg_path, = modules_tmpdir.join("dist/").listdir()189+ (egg_path,) = modules_tmpdir.join("dist/").listdir()190 monkeypatch.syspath_prepend(str(egg_path))191 return egg_path192 193 return inner8 unmodified linesmodified:tests/test_appctx.py+2 added-3 removed
1-# -*- coding: utf-8 -*-1 """2 tests.appctx3 ~~~~~~~~~~~~4 156 unmodified lines161 assert repr(flask.g) == "<flask.g of 'flask_test'>"162 163 164 def test_custom_app_ctx_globals_class(app):166- class CustomRequestGlobals(object):165+ class CustomRequestGlobals:166 def __init__(self):167 self.spam = "eggs"168 169 app.app_ctx_globals_class = CustomRequestGlobals18 unmodified lines188 with flask._request_ctx_stack.top:189 pass190 env = flask._request_ctx_stack.top.request.environ191 assert env["werkzeug.request"] is not None193- return u""192+ return ""193 194 res = client.get("/")195 assert res.status_code == 200196 assert res.data == b""23 unmodified linesmodified:tests/test_basic.py+24 added-25 removed
1-# -*- coding: utf-8 -*-1 """2 tests.basic3 ~~~~~~~~~~~~~~~~~~~~~4 271 unmodified lines276 assert "httponly" in rv.headers["set-cookie"].lower()277 278 279 def test_session_using_application_root(app, client):281- class PrefixPathMiddleware(object):280+ class PrefixPathMiddleware:281 def __init__(self, app, prefix):282 self.app = app283 self.prefix = prefix284 296 unmodified lines581 # instead of propagating exceptions.582 583 @app.route("/")584 def index():586- flask.flash(u"Hello World")587- flask.flash(u"Hello World", "error")588- flask.flash(flask.Markup(u"<em>Testing</em>"), "warning")585+ flask.flash("Hello World")586+ flask.flash("Hello World", "error")587+ flask.flash(flask.Markup("<em>Testing</em>"), "warning")588 return ""589 590 @app.route("/test/")591 def test():592 messages = flask.get_flashed_messages()593 assert list(messages) == [595- u"Hello World",596- u"Hello World",597- flask.Markup(u"<em>Testing</em>"),594+ "Hello World",595+ "Hello World",596+ flask.Markup("<em>Testing</em>"),597 ]598 return ""599 600 @app.route("/test_with_categories/")601 def test_with_categories():602 messages = flask.get_flashed_messages(with_categories=True)603 assert len(messages) == 3604 assert list(messages) == [606- ("message", u"Hello World"),607- ("error", u"Hello World"),608- ("warning", flask.Markup(u"<em>Testing</em>")),605+ ("message", "Hello World"),606+ ("error", "Hello World"),607+ ("warning", flask.Markup("<em>Testing</em>")),608 ]609 return ""610 611 @app.route("/test_filter/")612 def test_filter():613 messages = flask.get_flashed_messages(614 category_filter=["message"], with_categories=True615 )617- assert list(messages) == [("message", u"Hello World")]616+ assert list(messages) == [("message", "Hello World")]617 return ""618 619 @app.route("/test_filters/")620 def test_filters():621 messages = flask.get_flashed_messages(622 category_filter=["message", "warning"], with_categories=True623 )624 assert list(messages) == [626- ("message", u"Hello World"),627- ("warning", flask.Markup(u"<em>Testing</em>")),625+ ("message", "Hello World"),626+ ("warning", flask.Markup("<em>Testing</em>")),627 ]628 return ""629 630 @app.route("/test_filters_without_returning_categories/")631 def test_filters2():632 messages = flask.get_flashed_messages(category_filter=["message", "warning"])633 assert len(messages) == 2635- assert messages[0] == u"Hello World"636- assert messages[1] == flask.Markup(u"<em>Testing</em>")634+ assert messages[0] == "Hello World"635+ assert messages[1] == flask.Markup("<em>Testing</em>")636 return ""637 638 # Create new test client on each test to clean flashed messages.639 460 unmodified lines1100 1101 def test_response_types(app, client):1102 @app.route("/text")1103 def from_text():1105- return u"Hällo Wörld"1104+ return "Hällo Wörld"1105 1106 @app.route("/bytes")1107 def from_bytes():1109- return u"Hällo Wörld".encode("utf-8")1108+ return "Hällo Wörld".encode()1109 1110 @app.route("/full_tuple")1111 def from_full_tuple():1112 return (28 unmodified lines1141 @app.route("/dict")1142 def from_dict():1143 return {"foo": "bar"}, 2011144 1146- assert client.get("/text").data == u"Hällo Wörld".encode("utf-8")1147- assert client.get("/bytes").data == u"Hällo Wörld".encode("utf-8")1145+ assert client.get("/text").data == "Hällo Wörld".encode()1146+ assert client.get("/bytes").data == "Hällo Wörld".encode()1147 1148 rv = client.get("/full_tuple")1149 assert rv.data == b"Meh"1150 assert rv.headers["X-Foo"] == "Testing"458 unmodified lines1609 assert url == expected1610 1611 1612 def test_nonascii_pathinfo(app, client):1614- @app.route(u"/киртест")1613+ @app.route("/киртест")1614 def index():1615 return "Hello World!"1616 1618- rv = client.get(u"/киртест")1617+ rv = client.get("/киртест")1618 assert rv.data == b"Hello World!"1619 1620 1621 def test_debug_mode_complains_after_first_request(app, client):251 unmodified lines1873 assert rv.data == b"b"1874 1875 1876 def test_multi_route_class_views(app, client):1878- class View(object):1877+ class View:1878 def __init__(self, app):1879 app.add_url_rule("/", "index", self.index)1880 app.add_url_rule("/<test>/", "index", self.index)1881 23 unmodified lines1905 rv = {}1906 1907 # Mocks werkzeug.serving.run_simple method1908 def run_simple_mock(hostname, port, application, *args, **kwargs):1910- rv["result"] = "running on %s:%s ..." % (hostname, port)1909+ rv["result"] = f"running on {hostname}:{port} ..."1910 1911 monkeypatch.setattr(werkzeug.serving, "run_simple", run_simple_mock)1912 hostname, port = "localhost", 80001913 app.run(hostname, port, debug=True)1915- assert rv["result"] == "running on %s:%s ..." % (hostname, port)1914+ assert rv["result"] == f"running on {hostname}:{port} ..."1915 1916 1917 @pytest.mark.parametrize(1918 "host,port,server_name,expect_host,expect_port",50 unmodified linesmodified:tests/test_blueprints.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.blueprints3 ~~~~~~~~~~~~~~~~4 857 unmodified linesmodified:tests/test_cli.py+1 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_cli3 ~~~~~~~~~~~~~~4 1 unmodified line6 :license: BSD-3-Clause7 """8 # This file was part of Flask-CLI and was modified under the terms of9 # its Revised BSD License. Copyright © 2015 CERN.11-from __future__ import absolute_import12-10 import os11 import ssl12 import sys13 import types243 unmodified lines257 from flask import __version__ as flask_version258 from werkzeug import __version__ as werkzeug_version259 from platform import python_version260 264- class MockCtx(object):261+ class MockCtx:262 resilient_parsing = False263 color = None264 265 def exit(self):394 unmodified linesmodified:tests/test_config.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_config3 ~~~~~~~~~~~~~~~~~4 58 unmodified lines63 app.config.from_mapping({}, {})64 65 66 def test_config_from_class():68- class Base(object):67+ class Base:68 TEST_KEY = "foo"69 70 class Test(Base):71 SECRET_KEY = "config"112 unmodified lines184 def test_from_pyfile_weird_encoding(tmpdir, encoding):185 f = tmpdir.join("my_config.py")186 f.write_binary(187 textwrap.dedent(189- u"""190- # -*- coding: {0} -*-188+ """189+ # -*- coding: {} -*-190 TEST_VALUE = "föö"191 """.format(192 encoding193 )1 unmodified line195 )196 app = flask.Flask(__name__)197 app.config.from_pyfile(str(f))198 value = app.config["TEST_VALUE"]200- assert value == u"föö"199+ assert value == "föö"modified:tests/test_converters.py+1 added-1 removed
8 unmodified lines9 def to_python(self, value):10 return value.split(",")11 12 def to_url(self, value):13- base_to_url = super(ListConverter, self).to_url13+ base_to_url = super().to_url14 return ",".join(base_to_url(x) for x in value)15 16 app.url_map.converters["list"] = ListConverter17 23 unmodified linesmodified:tests/test_helpers.py+23 added-24 removed
1-# -*- coding: utf-8 -*-1 """2 tests.helpers3 ~~~~~~~~~~~~~~~~~~~~~~~4 31 unmodified lines36 except LookupError:37 return False38 39 41-class FakePath(object):40+class FakePath:41 """Fake object to represent a ``PathLike object``.42 43 This represents a ``pathlib.Path`` object in python 3.44 See: https://www.python.org/dev/peps/pep-0519/26 unmodified lines71 def dst(self, dt):72 return datetime.timedelta()73 74 76-class TestJSON(object):75+class TestJSON:76 @pytest.mark.parametrize(78- "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": u"🐍"})77+ "value", (1, "t", True, False, None, [], [1, 2, 3], {}, {"foo": "🐍"})78 )79 @pytest.mark.parametrize(80 "encoding",81 (42 unmodified lines124 rv = client.post("/json", data='"foo"', content_type="application/x+json")125 assert rv.data == b"foo"126 127 @pytest.mark.parametrize(129- "test_value,expected", [(True, '"\\u2603"'), (False, u'"\u2603"')]128+ "test_value,expected", [(True, '"\\u2603"'), (False, '"\u2603"')]129 )130 def test_json_as_unicode(self, test_value, expected, app, app_ctx):131 132 app.config["JSON_AS_ASCII"] = test_value134- rv = flask.json.dumps(u"\N{SNOWMAN}")133+ rv = flask.json.dumps("\N{SNOWMAN}")134 assert rv == expected135 136 def test_json_dump_to_file(self, app, app_ctx):137 test_data = {"name": "Flask"}77 unmodified lines215 datetime.date(1975, 1, 5),216 )217 218 for i, d in enumerate(test_dates):220- url = "/datetest{0}".format(i)219+ url = f"/datetest{i}"220 app.add_url_rule(url, str(i), lambda val=d: flask.jsonify(x=val))221 rv = client.get(url)222 assert rv.mimetype == "application/json"223 assert flask.json.loads(rv.data)["x"] == http_date(d.timetuple())36 unmodified lines260 261 def test_template_escaping(self, app, req_ctx):262 render = flask.render_template_string263 rv = flask.json.htmlsafe_dumps("</script>")265- assert rv == u'"\\u003c/script\\u003e"'264+ assert rv == '"\\u003c/script\\u003e"'265 assert type(rv) is str266 rv = render('{{ "</script>"|tojson }}')267 assert rv == '"\\u003c/script\\u003e"'268 rv = render('{{ "<\0/script>"|tojson }}')9 unmodified lines278 )279 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'280 281 def test_json_customization(self, app, client):283- class X(object): # noqa: B903, for Python2 compatibility282+ class X: # noqa: B903, for Python2 compatibility283 def __init__(self, val):284 self.val = val285 286 class MyEncoder(flask.json.JSONEncoder):26 unmodified lines313 )314 assert rv.data == b'"<42>"'315 316 def test_blueprint_json_customization(self, app, client):318- class X(object): # noqa: B903, for Python2 compatibility317+ class X: # noqa: B903, for Python2 compatibility318 def __init__(self, val):319 self.val = val320 321 class MyEncoder(flask.json.JSONEncoder):44 unmodified lines366 @app.route("/")367 def index():368 return flask.request.args["foo"]369 371- rv = client.get(u"/?foo=정상처리".encode("euc-kr"))370+ rv = client.get("/?foo=정상처리".encode("euc-kr"))371 assert rv.status_code == 200373- assert rv.data == u"정상처리".encode("utf-8")372+ assert rv.data == "정상처리".encode()373 374 def test_json_key_sorting(self, app, client):375 app.debug = True376 64 unmodified lines441 except AssertionError:442 assert lines == sorted_by_str443 444 446-class PyBytesIO(object):445+class PyBytesIO:446 def __init__(self, *args, **kwargs):447 self._io = io.BytesIO(*args, **kwargs)448 449 def __getattr__(self, name):450 return getattr(self._io, name)451 452 454-class TestSendfile(object):453+class TestSendfile:454 def test_send_file_regular(self, app, req_ctx):455 rv = flask.send_file("static/index.html")456 assert rv.direct_passthrough457 assert rv.mimetype == "text/html"56 unmodified lines514 515 @pytest.mark.parametrize(516 "opener",517 [519- lambda app: io.StringIO(u"Test"),518+ lambda app: io.StringIO("Test"),519 lambda app: open(os.path.join(app.static_folder, "index.html")),520 ],521 )522 @pytest.mark.usefixtures("req_ctx")148 unmodified lines671 ("filename", "ascii", "utf8"),672 (673 ("index.html", "index.html", False),674 (676- u"Ñandú/pingüino.txt",675+ "Ñandú/pingüino.txt",676 '"Nandu/pinguino.txt"',677 "%C3%91and%C3%BA%EF%BC%8Fping%C3%BCino.txt",678 ),680- (u"Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),679+ ("Vögel.txt", "Vogel.txt", "V%C3%B6gel.txt"),680 # ":/" are not safe in filename* value682- (u"те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),681+ ("те:/ст", '":/"', "%D1%82%D0%B5%3A%2F%D1%81%D1%82"),682 ),683 )684 def test_attachment_filename_encoding(self, filename, ascii, utf8):685 rv = flask.send_file(87 unmodified lines773 with pytest.raises(exception):774 flask.send_from_directory("static", "bad\x00")775 776 778-class TestUrlFor(object):777+class TestUrlFor:778 def test_url_for_with_anchor(self, app, req_ctx):779 @app.route("/")780 def index():781 return "42"50 unmodified lines832 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"833 assert flask.url_for("myview", _method="POST") == "/myview/create"834 835 837-class TestNoImports(object):836+class TestNoImports:837 """Test Flasks are created without import.838 839 Avoiding ``__import__`` helps create Flask instances where there are errors840 at import time. Those runtime errors will be apparent to the user soon10 unmodified lines851 except NotImplementedError:852 AssertionError("Flask(import_name) is importing import_name.")853 854 856-class TestStreaming(object):855+class TestStreaming:856 def test_streaming_with_context(self, app, client):857 @app.route("/")858 def index():859 def generate():22 unmodified lines882 883 def test_streaming_with_context_and_custom_close(self, app, client):884 called = []885 887- class Wrapper(object):886+ class Wrapper:887 def __init__(self, gen):888 self._gen = gen889 890 def __iter__(self):34 unmodified lines925 rv = client.get("/")926 assert rv.data == b"flask"927 928 930-class TestSafeJoin(object):929+class TestSafeJoin:930 def test_safe_join(self):931 # Valid combinations of *args and expected joined paths.932 passing = (933 (("a/b/c",), "a/b/c"),32 unmodified lines966 with pytest.raises(NotFound):967 print(flask.safe_join(*args))968 969 971-class TestHelpers(object):970+class TestHelpers:971 @pytest.mark.parametrize(972 "debug, expected_flag, expected_default_flag",973 [974 ("", False, False),55 unmodified linesmodified:tests/test_instance_config.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_instance3 ~~~~~~~~~~~~~~~~~~~4 124 unmodified linesmodified:tests/test_json_tag.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_json_tag3 ~~~~~~~~~~~~~~~~~~~4 41 unmodified lines46 assert isinstance(s.order[0], TagDict)47 48 49 def test_custom_tag():51- class Foo(object): # noqa: B903, for Python2 compatibility50+ class Foo: # noqa: B903, for Python2 compatibility51 def __init__(self, data):52 self.data = data53 54 class TagFoo(JSONTag):38 unmodified linesmodified:tests/test_logging.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_logging3 ~~~~~~~~~~~~~~~~~~~4 101 unmodified linesmodified:tests/test_regression.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 """2 tests.regression3 ~~~~~~~~~~~~~~~~~~~~~~~~~~4 13 unmodified lines18 19 _gc_lock = threading.Lock()20 21 23-class assert_no_leak(object):22+class assert_no_leak:23 def __enter__(self):24 gc.disable()25 _gc_lock.acquire()26 loc = flask._request_ctx_stack._local69 unmodified linesmodified:tests/test_reqctx.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 tests.reqctx3 ~~~~~~~~~~~~4 143 unmodified lines148 index()149 150 151 @pytest.mark.skipif(greenlet is None, reason="greenlet not installed")153-class TestGreenletContextCopying(object):152+class TestGreenletContextCopying:153 def test_greenlet_context_copying(self, app, client):154 greenlets = []155 156 @app.route("/")80 unmodified lines237 def get_cookie_name(self, app):238 if flask.request.url.endswith("dynamic_cookie"):239 return "dynamic_cookie_name"240 else:242- return super(PathAwareSessionInterface, self).get_cookie_name(app)241+ return super().get_cookie_name(app)242 243 class CustomFlask(flask.Flask):244 session_interface = PathAwareSessionInterface()245 43 unmodified lines289 builder = EnvironBuilder(app)290 environ = builder.get_environ()291 292 # use a non-printable character in the Host - this is key to this test294- environ["HTTP_HOST"] = u"\x8a"293+ environ["HTTP_HOST"] = "\x8a"294 295 with app.request_context(environ):296 response = app.full_dispatch_request()297 assert response.status_code == 40011 unmodified lines309 builder = EnvironBuilder(app)310 environ = builder.get_environ()311 312 # these characters are all IDNA-compatible314- environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"313+ environ["HTTP_HOST"] = "ąśźäüжŠßя.com"314 315 with app.request_context(environ):316 response = app.full_dispatch_request()317 12 unmodified linesmodified:tests/test_signals.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.signals3 ~~~~~~~~~~~~~~~~~~~~~~~4 201 unmodified linesmodified:tests/test_subclassing.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.subclassing3 ~~~~~~~~~~~~~~~~~4 27 unmodified linesmodified:tests/test_templating.py+3 added-4 removed
1-# -*- coding: utf-8 -*-1 """2 tests.templating3 ~~~~~~~~~~~~~~~~4 410 unmodified lines415 called.append(True)416 text = str(record.msg)417 assert '1: trying loader of application "blueprintapp"' in text418 assert (420- '2: trying loader of blueprint "admin" ' "(blueprintapp.apps.admin)"419+ '2: trying loader of blueprint "admin" (blueprintapp.apps.admin)'420 ) in text421 assert (423- 'trying loader of blueprint "frontend" ' "(blueprintapp.apps.frontend)"422+ 'trying loader of blueprint "frontend" (blueprintapp.apps.frontend)'423 ) in text424 assert "Error: the template could not be found" in text425 assert (427- "looked up from an endpoint that belongs to " 'the blueprint "frontend"'426+ 'looked up from an endpoint that belongs to the blueprint "frontend"'427 ) in text428 assert "See https://flask.palletsprojects.com/blueprints/#templates" in text429 430 with app.test_client() as c:22 unmodified linesmodified:tests/test_testing.py+4 added-5 removed
1-# -*- coding: utf-8 -*-1 """2 tests.testing3 ~~~~~~~~~~~~~4 115 unmodified lines120 121 def test_environbuilder_json_dumps(app):122 """EnvironBuilder.json_dumps() takes settings from the app."""123 app.config["JSON_AS_ASCII"] = False125- eb = EnvironBuilder(app, json=u"\u20ac")126- assert eb.input_stream.read().decode("utf8") == u'"\u20ac"'124+ eb = EnvironBuilder(app, json="\u20ac")125+ assert eb.input_stream.read().decode("utf8") == '"\u20ac"'126 127 128 def test_blueprint_with_subdomain():129 app = flask.Flask(__name__, subdomain_matching=True)192 unmodified lines322 @app.route("/hello", methods=["POST"])323 def hello():324 return "Hello, {}!".format(flask.request.json["name"])325 327- class Namespace(object):326+ class Namespace:327 count = 0328 329 def add(self, app):330 self.count += 169 unmodified lines400 assert "Hello" in result.output401 402 403 def test_cli_custom_obj(app):405- class NS(object):404+ class NS:405 called = False406 407 def create_app():408 NS.called = True25 unmodified linesmodified:tests/test_user_error_handler.py+1 added-2 removed
1-# -*- coding: utf-8 -*-1 """2 tests.test_user_error_handler3 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4 201 unmodified lines206 # Don't handle RequestRedirect raised when adding slash.207 assert c.get("/slash", follow_redirects=True).data == b"slash"208 209 211-class TestGenericHandlers(object):210+class TestGenericHandlers:211 """Test how very generic handlers are dispatched to."""212 213 class Custom(Exception):214 pass74 unmodified linesmodified:tests/test_views.py-1 removed
1-# -*- coding: utf-8 -*-1 """2 tests.views3 ~~~~~~~~~~~4 247 unmodified linesmodified:.pre-commit-config.yaml+13 added-6 removed
1 repos:2+ - repo: https://github.com/asottile/pyupgrade3+ rev: v2.1.04+ hooks:5+ - id: pyupgrade6+ args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports3- rev: v1.5.08+ rev: v2.1.09 hooks:10 - id: reorder-python-imports11 name: Reorder Python imports (src, tests)12 files: "^(?!examples/)"8- args: ["--application-directories", ".:src"]13+ args: ["--application-directories", "src"]14 - repo: https://github.com/python/black10- rev: 19.3b015+ rev: 19.10b016 hooks:17 - id: black18 - repo: https://gitlab.com/pycqa/flake814- rev: 3.7.719+ rev: 3.7.920 hooks:21 - id: flake817- additional_dependencies: [flake8-bugbear]22+ additional_dependencies:23+ - flake8-bugbear24+ - flake8-implicit-str-concat25 - repo: https://github.com/pre-commit/pre-commit-hooks19- rev: v2.2.326+ rev: v2.5.027 hooks:28 - id: check-byte-order-marker29 - id: trailing-whitespace30 - id: end-of-file-fixermodified:setup.cfg+4 added-4 removed
18 unmodified lines19 # E = pycodestyle errors20 # F = flake8 pyflakes21 # W = pycodestyle warnings22 # B9 = bugbear opinions23+# ISC = implicit-str-concat23-select = B, E, F, W, B924+select = B, E, F, W, B9, ISC25 ignore =26 # slice notation whitespace, invalid27 E20328 # import at top, too many circular import fixes6 unmodified lines35 W50336 # up to 88 allowed by bugbear B95037 max-line-length = 8038 per-file-ignores =38- # __init__ modules export names39- **/__init__.py: F40140- src/flask/_compat.py: E731, B301, F40139+ # __init__ module exports names40+ src/flask/__init__.py: F401modified:setup.py+2 added-3 removed
1-import io1 import re2 3 from setuptools import find_packages4 from setuptools import setup5 7-with io.open("README.rst", "rt", encoding="utf8") as f:6+with open("README.rst", encoding="utf8") as f:7 readme = f.read()8 10-with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f:9+with open("src/flask/__init__.py", encoding="utf8") as f:10 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)11 12 setup(13 name="Flask",57 unmodified lines