Skip to content
Myr

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

54 files+169 added−230 removed

modified:docs/conf.py+4 added-6 removed
50 unmodified lines
51singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}52html_static_path = ["_static"]53html_favicon = "_static/flask-icon.png"54html_logo = "_static/flask-icon.png"55html_title = "Flask Documentation ({})".format(version)55html_title = f"Flask Documentation ({version})"56html_show_sourcelink = False5758# LaTeX ----------------------------------------------------------------5960latex_documents = [61 (master_doc, "Flask-{}.tex".format(version), html_title, author, "manual")62]60latex_documents = [(master_doc, f"Flask-{version}.tex", html_title, author, "manual")]6162# Local Extensions -----------------------------------------------------6364
8 unmodified lines
73 else:74 words = None7576 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}"8081 if words is None:82 words = url83
11 unmodified lines
modified:examples/javascript/js_example/__init__.py+1 added-1 removed
1from flask import Flask23app = Flask(__name__)45from js_example import views5from js_example import views # noqa: F401
modified:examples/javascript/js_example/views.py+1 added-1 removed
6 unmodified lines
78@app.route("/", defaults={"js": "plain"})9@app.route("/<any(plain, jquery, fetch):js>")10def index(js):11 return render_template("{0}.html".format(js), js=js)11 return render_template(f"{js}.html", js=js)121314@app.route("/add", methods=["POST"])15def add():
3 unmodified lines
modified:examples/javascript/setup.py+1 added-3 removed
1import io21from setuptools import find_packages2from setuptools import setup36with io.open("README.rst", "rt", encoding="utf8") as f:4with open("README.rst", encoding="utf8") as f:5 readme = f.read()67setup(8 name="js_example",
13 unmodified lines
modified:examples/tutorial/flaskr/auth.py+1 added-1 removed
62 unmodified lines
63 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."6869 if error is None:70 # the name is available, store it in the database and go to71 # the login page
45 unmodified lines
modified:examples/tutorial/flaskr/blog.py+1 added-1 removed
47 unmodified lines
48 .fetchone()49 )5051 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.")5354 if check_author and post["author_id"] != g.user["id"]:55 abort(403)56
69 unmodified lines
modified:examples/tutorial/tests/conftest.py+1 added-1 removed
42 unmodified lines
43 """A test runner for the app's Click commands."""44 return app.test_cli_runner()454647class AuthActions(object):47class AuthActions:48 def __init__(self, client):49 self._client = client5051 def login(self, username="test", password="test"):
11 unmodified lines
modified:examples/tutorial/tests/test_db.py+1 added-1 removed
15 unmodified lines
16 assert "closed" in str(e.value)171819def test_init_db_command(runner, monkeypatch):20 class Recorder(object):20 class Recorder:21 called = False2223 def fake_init_db():24 Recorder.called = True
5 unmodified lines
modified:examples/tutorial/setup.py+1 added-3 removed
1import io21from setuptools import find_packages2from setuptools import setup36with io.open("README.rst", "rt", encoding="utf8") as f:4with open("README.rst", encoding="utf8") as f:5 readme = f.read()67setup(8 name="flaskr",
13 unmodified lines
modified:src/flask/json/__init__.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2flask.json3~~~~~~~~~~4
279 unmodified lines
284 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 rv
78 unmodified lines
modified:src/flask/json/tag.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2Tagged JSON3~~~~~~~~~~~4
47 unmodified lines
52from ..json import dumps53from ..json import loads545557class JSONTag(object):56class JSONTag:57 """Base class for defining type tags for :class:`TaggedJSONSerializer`."""5859 __slots__ = ("serializer",)60
59 unmodified lines
120121 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()}125126 tag = to_json127128
82 unmodified lines
211 def to_python(self, value):212 return parse_date(value)213214216class TaggedJSONSerializer(object):215class 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 lines
267 key = tag.key268269 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.")272273 self.tags[key] = tag274275 if index is None:
31 unmodified lines
modified:src/flask/__init__.py-1 removed
1# -*- coding: utf-8 -*-1"""2 flask3 ~~~~~4
54 unmodified lines
modified:src/flask/__main__.py-1 removed
1# -*- coding: utf-8 -*-1"""2 flask.__main__3 ~~~~~~~~~~~~~~4
10 unmodified lines
modified:src/flask/app.py+6 added-7 removed
1# -*- coding: utf-8 -*-1"""2 flask.app3 ~~~~~~~~~4
1104 unmodified lines
1109 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 lines
1178 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}11831184 # Methods that should always be added1185 required_methods = set(getattr(view_func, "required_methods", ()))1186
153 unmodified lines
1340 :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 )13481349 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 )13561357 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})
451 unmodified lines
18091810 .. 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 )18151816 def raise_routing_exception(self, request):1817 """Exceptions that are recording during routing are reraised with
556 unmodified lines
2374 wrapped to applying middleware."""2375 return self.wsgi_app(environ, start_response)23762377 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 lines
16# a singleton sentinel value for parameter defaults17_sentinel = object()181921class BlueprintSetupState(object):20class 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 lines
78 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 )878889class Blueprint(_PackageBoundObject):
479 unmodified lines
modified:src/flask/cli.py+13 added-20 removed
1# -*- coding: utf-8 -*-1"""2 flask.cli3 ~~~~~~~~~4
1 unmodified line
67 :copyright: 2010 Pallets8 :license: BSD-3-Clause9"""11from __future__ import print_function1210import ast11import inspect12import os13import platform
149 unmodified lines
163164 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 lines
239 '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 return246247 module = sys.modules[module_name]
33 unmodified lines
281 is_eager=True,282)283284288class DispatchingApp(object):285class 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 lines
340 rv = self._load_unlocked()341 return rv(environ, start_response)342343347class ScriptInfo(object):344class 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 the
138 unmodified lines
487 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 ())494495 if add_version_option:
83 unmodified lines
579 )580581 kwargs["obj"] = obj582 kwargs.setdefault("auto_envvar_prefix", "FLASK")586 return super(FlaskGroup, self).main(*args, **kwargs)583 return super().main(*args, **kwargs)584585586def _path_is_ancestor(path, other):587 """Take ``other`` and remove the length of ``path`` from it. Then join it
70 unmodified lines
658 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":659 return660661 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}"'663664 if not eager_loading:665 message += " (lazy loading)"666667 click.echo(message)668672 click.echo(" * Environment: {0}".format(env))669 click.echo(f" * Environment: {env}")670671 if env == "production":672 click.secho(673 " WARNING: This is a development server. "
2 unmodified lines
676 )677 click.secho(" Use a production WSGI server instead.", dim=True)678679 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"))681682683class CertParamType(click.ParamType):684 """Click option type for the ``--cert`` option. Allows either an
77 unmodified lines
762 """763764 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]768769770@click.command("run", short_help="Run a development server.")
91 unmodified lines
862 import code863 from .globals import _app_ctx_stack864865 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 = {}870871 # 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)877878 ctx.update(app.make_shell_context())879
76 unmodified lines
modified:src/flask/config.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2 flask.config3 ~~~~~~~~~~~~4
8 unmodified lines
1314from werkzeug.utils import import_string151618class ConfigAttribute(object):17class ConfigAttribute:18 """Makes an attribute forward to the config"""1920 def __init__(self, name, get_converter=None):21 self.__name__ = name
102 unmodified lines
124 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 raise
62 unmodified lines
195196 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 False202203 e.strerror = "Unable to load configuration file (%s)" % e.strerror
65 unmodified lines
269 rv[key] = v270 return rv271272 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 lines
21# a singleton sentinel value for parameter defaults22_sentinel = object()232426class _AppCtxGlobals(object):25class _AppCtxGlobals:26 """A plain object. Used as a namespace for storing data during an27 application context.2829 Creating an app context automatically creates this object, which is
168 unmodified lines
198 """199 return _app_ctx_stack.top is not None200201203class AppContext(object):202class 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 created
25 unmodified lines
232 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)238239 def __enter__(self):240 self.push()
2 unmodified lines
243 def __exit__(self, exc_type, exc_value, tb):244 self.pop(exc_value)245246248class RequestContext(object):247class 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 lines
418 # Get rid of the app as well if necessary.419 if app_ctx is not None:420 app_ctx.pop(exc)421423 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})"425426 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_exception
15 unmodified lines
444 # See flask.testing for how this works.445 self.auto_pop(exc_value)446447 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 line
modified:src/flask/debughelpers.py+3 added-4 removed
1# -*- coding: utf-8 -*-1"""2 flask.debughelpers3 ~~~~~~~~~~~~~~~~~~4
95 unmodified lines
100 request.files.__class__ = newcls101102103def _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 lines
113 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}"118119120def explain_template_loading_attempts(app, template, attempts):121 """This should help developers understand what failed"""
7 unmodified lines
129 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)136137 info.append("% 5d: trying loader of %s" % (idx + 1, src_info))
42 unmodified lines
modified:src/flask/globals.py-1 removed
1# -*- coding: utf-8 -*-1"""2 flask.globals3 ~~~~~~~~~~~~~4
57 unmodified lines
modified:src/flask/helpers.py+4 added-6 removed
1# -*- coding: utf-8 -*-1"""2 flask.helpers3 ~~~~~~~~~~~~~4
148 unmodified lines
153 # 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 lines
930 return base_dir, package_path931 return None, package_path932933936class locked_cached_property(object):934class 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 for
17 unmodified lines
956 obj.__dict__[self.__name__] = value957 return value958959962class _PackageBoundObject(object):960class _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 lines
1134 """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 line
modified:src/flask/logging.py-3 removed
1# -*- coding: utf-8 -*-1"""2flask.logging3~~~~~~~~~~~~~45:copyright: 2010 Pallets6:license: BSD-3-Clause7"""9from __future__ import absolute_import108import logging9import sys1011from werkzeug.local import LocalProxy
66 unmodified lines
modified:src/flask/sessions.py+5 added-6 removed
1# -*- coding: utf-8 -*-1"""2 flask.sessions3 ~~~~~~~~~~~~~~4
70 unmodified lines
75 def on_update(self):76 self.modified = True77 self.accessed = True7880 super(SecureCookieSession, self).__init__(initial, on_update)79 super().__init__(initial, on_update)8081 def __getitem__(self, key):82 self.accessed = True84 return super(SecureCookieSession, self).__getitem__(key)83 return super().__getitem__(key)8485 def get(self, key, default=None):86 self.accessed = True88 return super(SecureCookieSession, self).get(key, default)87 return super().get(key, default)8889 def setdefault(self, key, default=None):90 self.accessed = True92 return super(SecureCookieSession, self).setdefault(key, default)91 return super().setdefault(key, default)929394class NullSession(SecureCookieSession):95 """Class used to generate nicer error messages if sessions are not
11 unmodified lines
107 __setitem__ = __delitem__ = clear = pop = popitem = update = setdefault = _fail108 del _fail109110112class SessionInterface(object):111class 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 have
278 unmodified lines
modified:src/flask/signals.py+2 added-3 removed
1# -*- coding: utf-8 -*-1"""2 flask.signals3 ~~~~~~~~~~~~~4
9 unmodified lines
14 signals_available = True15except ImportError:16 signals_available = False1719 class Namespace(object):18 class Namespace:19 def signal(self, name, doc=None):20 return _FakeSignal(name, doc)2123 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 lines
modified:src/flask/templating.py-1 removed
1# -*- coding: utf-8 -*-1"""2 flask.templating3 ~~~~~~~~~~~~~~~~4
150 unmodified lines
modified:src/flask/testing.py+6 added-7 removed
1# -*- coding: utf-8 -*-1"""2 flask.testing3 ~~~~~~~~~~~~~4
44 unmodified lines
49 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 lines
62 http_host = app.config.get("SERVER_NAME") or "localhost"63 app_root = app.config["APPLICATION_ROOT"]6465 if subdomain:67 http_host = "{0}.{1}".format(subdomain, http_host)66 http_host = f"{subdomain}.{http_host}"6768 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]70
9 unmodified lines
80 sep = b"?" if isinstance(url.query, bytes) else "?"81 path += sep + url.query8283 self.app = app85 super(EnvironBuilder, self).__init__(path, base_url, *args, **kwargs)84 super().__init__(path, base_url, *args, **kwargs)8586 def json_dumps(self, obj, **kwargs):87 """Serialize ``obj`` to a JSON-formatted string.88
21 unmodified lines
110111 preserve_context = False112113 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 lines
237 """238239 def __init__(self, app, **kwargs):240 self.app = app242 super(FlaskCliRunner, self).__init__(**kwargs)241 super().__init__(**kwargs)242243 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>` for
14 unmodified lines
260261 if "obj" not in kwargs:262 kwargs["obj"] = ScriptInfo(create_app=lambda: self.app)263265 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 lines
14 ["get", "post", "head", "options", "delete", "put", "trace", "patch"]15)161719class View(object):18class 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 lines
111 defines.112 """113114 def __init__(cls, name, bases, d):116 super(MethodViewType, cls).__init__(name, bases, d)115 super().__init__(name, bases, d)116117 if "methods" not in d:118 methods = set()119
42 unmodified lines
modified:src/flask/wrappers.py+2 added-3 removed
1# -*- coding: utf-8 -*-1"""2 flask.wrappers3 ~~~~~~~~~~~~~~4
15 unmodified lines
20 json_module = json2122 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}")2526 raise BadRequest()2728
103 unmodified lines
132 if current_app:133 return current_app.config["MAX_COOKIE_SIZE"]134135 # return Werkzeug's default when not in an app context137 return super(Response, self).max_cookie_size136 return super().max_cookie_size
modified:tests/test_apps/cliapp/app.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23testapp = Flask("testapp")
modified:tests/test_apps/cliapp/factory.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask234def create_app():
13 unmodified lines
modified:tests/test_apps/cliapp/importerrorapp.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23raise ImportError()4
1 unmodified line
modified:tests/test_apps/cliapp/multiapp.py-3 removed
1from __future__ import absolute_import2from __future__ import print_function31from flask import Flask23app1 = Flask("app1")4app2 = Flask("app2")
modified:tests/conftest.py+3 added-4 removed
1# -*- coding: utf-8 -*-1"""2 tests.conftest3 ~~~~~~~~~~~~~~4
105 unmodified lines
110 """111 if not request.param:112 return113115 class LimitedLoader(object):114 class LimitedLoader:115 def __init__(self, loader):116 self.loader = loader117118 def __getattr__(self, name):
51 unmodified lines
170 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 lines
185186 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_path192193 return inner
8 unmodified lines
modified:tests/test_appctx.py+2 added-3 removed
1# -*- coding: utf-8 -*-1"""2 tests.appctx3 ~~~~~~~~~~~~4
156 unmodified lines
161 assert repr(flask.g) == "<flask.g of 'flask_test'>"162163164def test_custom_app_ctx_globals_class(app):166 class CustomRequestGlobals(object):165 class CustomRequestGlobals:166 def __init__(self):167 self.spam = "eggs"168169 app.app_ctx_globals_class = CustomRequestGlobals
18 unmodified lines
188 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 ""193194 res = client.get("/")195 assert res.status_code == 200196 assert res.data == b""
23 unmodified lines
modified:tests/test_basic.py+24 added-25 removed
1# -*- coding: utf-8 -*-1"""2 tests.basic3 ~~~~~~~~~~~~~~~~~~~~~4
271 unmodified lines
276 assert "httponly" in rv.headers["set-cookie"].lower()277278279def 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 lines
581 # instead of propagating exceptions.582583 @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 ""589590 @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 ""599600 @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 ""610611 @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 ""618619 @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 ""629630 @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 ""637638 # Create new test client on each test to clean flashed messages.639
460 unmodified lines
11001101def 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"11051106 @app.route("/bytes")1107 def from_bytes():1109 return u"Hällo Wörld".encode("utf-8")1108 return "Hällo Wörld".encode()11091110 @app.route("/full_tuple")1111 def from_full_tuple():1112 return (
28 unmodified lines
1141 @app.route("/dict")1142 def from_dict():1143 return {"foo": "bar"}, 20111441146 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()11471148 rv = client.get("/full_tuple")1149 assert rv.data == b"Meh"1150 assert rv.headers["X-Foo"] == "Testing"
458 unmodified lines
1609 assert url == expected161016111612def test_nonascii_pathinfo(app, client):1614 @app.route(u"/киртест")1613 @app.route("/киртест")1614 def index():1615 return "Hello World!"16161618 rv = client.get(u"/киртест")1617 rv = client.get("/киртест")1618 assert rv.data == b"Hello World!"161916201621def test_debug_mode_complains_after_first_request(app, client):
251 unmodified lines
1873 assert rv.data == b"b"187418751876def 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 lines
1905 rv = {}19061907 # 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} ..."19101911 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} ..."191519161917@pytest.mark.parametrize(1918 "host,port,server_name,expect_host,expect_port",
50 unmodified lines
modified:tests/test_blueprints.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.blueprints3 ~~~~~~~~~~~~~~~~4
857 unmodified lines
modified:tests/test_cli.py+1 added-4 removed
1# -*- coding: utf-8 -*-1"""2 tests.test_cli3 ~~~~~~~~~~~~~~4
1 unmodified line
6 :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.11from __future__ import absolute_import1210import os11import ssl12import sys13import types
243 unmodified lines
257 from flask import __version__ as flask_version258 from werkzeug import __version__ as werkzeug_version259 from platform import python_version260264 class MockCtx(object):261 class MockCtx:262 resilient_parsing = False263 color = None264265 def exit(self):
394 unmodified lines
modified:tests/test_config.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2 tests.test_config3 ~~~~~~~~~~~~~~~~~4
58 unmodified lines
63 app.config.from_mapping({}, {})646566def test_config_from_class():68 class Base(object):67 class Base:68 TEST_KEY = "foo"6970 class Test(Base):71 SECRET_KEY = "config"
112 unmodified lines
184def 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 line
195 )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 lines
9 def to_python(self, value):10 return value.split(",")1112 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)1516 app.url_map.converters["list"] = ListConverter17
23 unmodified lines
modified:tests/test_helpers.py+23 added-24 removed
1# -*- coding: utf-8 -*-1"""2 tests.helpers3 ~~~~~~~~~~~~~~~~~~~~~~~4
31 unmodified lines
36 except LookupError:37 return False383941class FakePath(object):40class FakePath:41 """Fake object to represent a ``PathLike object``.4243 This represents a ``pathlib.Path`` object in python 3.44 See: https://www.python.org/dev/peps/pep-0519/
26 unmodified lines
71 def dst(self, dt):72 return datetime.timedelta()737476class TestJSON(object):75class 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 lines
124 rv = client.post("/json", data='"foo"', content_type="application/x+json")125 assert rv.data == b"foo"126127 @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):131132 app.config["JSON_AS_ASCII"] = test_value134 rv = flask.json.dumps(u"\N{SNOWMAN}")133 rv = flask.json.dumps("\N{SNOWMAN}")134 assert rv == expected135136 def test_json_dump_to_file(self, app, app_ctx):137 test_data = {"name": "Flask"}
77 unmodified lines
215 datetime.date(1975, 1, 5),216 )217218 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 lines
260261 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 lines
278 )279 assert rv == '<a ng-data=\'{"x": ["foo", "bar", "baz\\u0027"]}\'></a>'280281 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 = val285286 class MyEncoder(flask.json.JSONEncoder):
26 unmodified lines
313 )314 assert rv.data == b'"<42>"'315316 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 = val320321 class MyEncoder(flask.json.JSONEncoder):
44 unmodified lines
366 @app.route("/")367 def index():368 return flask.request.args["foo"]369371 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()373374 def test_json_key_sorting(self, app, client):375 app.debug = True376
64 unmodified lines
441 except AssertionError:442 assert lines == sorted_by_str443444446class PyBytesIO(object):445class PyBytesIO:446 def __init__(self, *args, **kwargs):447 self._io = io.BytesIO(*args, **kwargs)448449 def __getattr__(self, name):450 return getattr(self._io, name)451452454class TestSendfile(object):453class 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 lines
514515 @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 lines
671 ("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 lines
773 with pytest.raises(exception):774 flask.send_from_directory("static", "bad\x00")775776778class TestUrlFor(object):777class TestUrlFor:778 def test_url_for_with_anchor(self, app, req_ctx):779 @app.route("/")780 def index():781 return "42"
50 unmodified lines
832 assert flask.url_for("myview", id=42, _method="GET") == "/myview/42"833 assert flask.url_for("myview", _method="POST") == "/myview/create"834835837class TestNoImports(object):836class TestNoImports:837 """Test Flasks are created without import.838839 Avoiding ``__import__`` helps create Flask instances where there are errors840 at import time. Those runtime errors will be apparent to the user soon
10 unmodified lines
851 except NotImplementedError:852 AssertionError("Flask(import_name) is importing import_name.")853854856class TestStreaming(object):855class TestStreaming:856 def test_streaming_with_context(self, app, client):857 @app.route("/")858 def index():859 def generate():
22 unmodified lines
882883 def test_streaming_with_context_and_custom_close(self, app, client):884 called = []885887 class Wrapper(object):886 class Wrapper:887 def __init__(self, gen):888 self._gen = gen889890 def __iter__(self):
34 unmodified lines
925 rv = client.get("/")926 assert rv.data == b"flask"927928930class TestSafeJoin(object):929class 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 lines
966 with pytest.raises(NotFound):967 print(flask.safe_join(*args))968969971class TestHelpers(object):970class TestHelpers:971 @pytest.mark.parametrize(972 "debug, expected_flag, expected_default_flag",973 [974 ("", False, False),
55 unmodified lines
modified:tests/test_instance_config.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.test_instance3 ~~~~~~~~~~~~~~~~~~~4
124 unmodified lines
modified:tests/test_json_tag.py+1 added-2 removed
1# -*- coding: utf-8 -*-1"""2tests.test_json_tag3~~~~~~~~~~~~~~~~~~~4
41 unmodified lines
46 assert isinstance(s.order[0], TagDict)474849def 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 = data5354 class TagFoo(JSONTag):
38 unmodified lines
modified:tests/test_logging.py-1 removed
1# -*- coding: utf-8 -*-1"""2tests.test_logging3~~~~~~~~~~~~~~~~~~~4
101 unmodified lines
modified:tests/test_regression.py+1 added-2 removed
1# -*- coding: utf-8 -*-1"""2 tests.regression3 ~~~~~~~~~~~~~~~~~~~~~~~~~~4
13 unmodified lines
1819_gc_lock = threading.Lock()202123class assert_no_leak(object):22class assert_no_leak:23 def __enter__(self):24 gc.disable()25 _gc_lock.acquire()26 loc = flask._request_ctx_stack._local
69 unmodified lines
modified:tests/test_reqctx.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2 tests.reqctx3 ~~~~~~~~~~~~4
143 unmodified lines
148 index()149150151@pytest.mark.skipif(greenlet is None, reason="greenlet not installed")153class TestGreenletContextCopying(object):152class TestGreenletContextCopying:153 def test_greenlet_context_copying(self, app, client):154 greenlets = []155156 @app.route("/")
80 unmodified lines
237 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)242243 class CustomFlask(flask.Flask):244 session_interface = PathAwareSessionInterface()245
43 unmodified lines
289 builder = EnvironBuilder(app)290 environ = builder.get_environ()291292 # use a non-printable character in the Host - this is key to this test294 environ["HTTP_HOST"] = u"\x8a"293 environ["HTTP_HOST"] = "\x8a"294295 with app.request_context(environ):296 response = app.full_dispatch_request()297 assert response.status_code == 400
11 unmodified lines
309 builder = EnvironBuilder(app)310 environ = builder.get_environ()311312 # these characters are all IDNA-compatible314 environ["HTTP_HOST"] = u"ąśźäüжŠßя.com"313 environ["HTTP_HOST"] = "ąśźäüжŠßя.com"314315 with app.request_context(environ):316 response = app.full_dispatch_request()317
12 unmodified lines
modified:tests/test_signals.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.signals3 ~~~~~~~~~~~~~~~~~~~~~~~4
201 unmodified lines
modified:tests/test_subclassing.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.subclassing3 ~~~~~~~~~~~~~~~~~4
27 unmodified lines
modified:tests/test_templating.py+3 added-4 removed
1# -*- coding: utf-8 -*-1"""2 tests.templating3 ~~~~~~~~~~~~~~~~4
410 unmodified lines
415 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 text429430 with app.test_client() as c:
22 unmodified lines
modified:tests/test_testing.py+4 added-5 removed
1# -*- coding: utf-8 -*-1"""2 tests.testing3 ~~~~~~~~~~~~~4
115 unmodified lines
120121def 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"'126127128def test_blueprint_with_subdomain():129 app = flask.Flask(__name__, subdomain_matching=True)
192 unmodified lines
322 @app.route("/hello", methods=["POST"])323 def hello():324 return "Hello, {}!".format(flask.request.json["name"])325327 class Namespace(object):326 class Namespace:327 count = 0328329 def add(self, app):330 self.count += 1
69 unmodified lines
400 assert "Hello" in result.output401402403def test_cli_custom_obj(app):405 class NS(object):404 class NS:405 called = False406407 def create_app():408 NS.called = True
25 unmodified lines
modified:tests/test_user_error_handler.py+1 added-2 removed
1# -*- coding: utf-8 -*-1"""2tests.test_user_error_handler3~~~~~~~~~~~~~~~~~~~~~~~~~~~~~4
201 unmodified lines
206 # Don't handle RequestRedirect raised when adding slash.207 assert c.get("/slash", follow_redirects=True).data == b"slash"208209211class TestGenericHandlers(object):210class TestGenericHandlers:211 """Test how very generic handlers are dispatched to."""212213 class Custom(Exception):214 pass
74 unmodified lines
modified:tests/test_views.py-1 removed
1# -*- coding: utf-8 -*-1"""2 tests.views3 ~~~~~~~~~~~4
247 unmodified lines
modified:.pre-commit-config.yaml+13 added-6 removed
1repos: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-fixer
modified:setup.cfg+4 added-4 removed
18 unmodified lines
19# E = pycodestyle errors20# F = flake8 pyflakes21# W = pycodestyle warnings22# B9 = bugbear opinions23# ISC = implicit-str-concat23select = B, E, F, W, B924select = B, E, F, W, B9, ISC25ignore =26 # slice notation whitespace, invalid27 E20328 # import at top, too many circular import fixes
6 unmodified lines
35 W50336# up to 88 allowed by bugbear B95037max-line-length = 8038per-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: F401
modified:setup.py+2 added-3 removed
1import io1import re23from setuptools import find_packages4from setuptools import setup57with io.open("README.rst", "rt", encoding="utf8") as f:6with open("README.rst", encoding="utf8") as f:7 readme = f.read()810with io.open("src/flask/__init__.py", "rt", encoding="utf8") as f:9with open("src/flask/__init__.py", encoding="utf8") as f:10 version = re.search(r'__version__ = "(.*?)"', f.read()).group(1)1112setup(13 name="Flask",
57 unmodified lines