f-strings everywhere
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 524fd0b · Browse files · 35 files·+227 added−245 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
35 files+227 added−245 removed
- tests:+46 added−49 removed
- other:+181 added−196 removed
Provenance
- Commit
2ae740d- Tree
6956e6d- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
524fd0b
35 files changed+227 added−245 removed
modified:docs/patterns/flashing.rst+1 added-1 removed
101 unmodified lines102 103 To flash a message with a different category, just use the second argument104 to the :func:`~flask.flash` function::105 106- flash(u'Invalid password provided', 'error')106+ flash('Invalid password provided', 'error')107 108 Inside the template you then have to tell the109 :func:`~flask.get_flashed_messages` function to also return the110 categories. The loop looks slightly different in that situation then:40 unmodified linesmodified:docs/patterns/lazyloading.rst+1 added-1 removed
91 unmodified lines92 :meth:`~flask.Flask.add_url_rule` by prefixing a string with the project93 name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::94 95 def url(import_name, url_rules=[], **options):96- view = LazyView('yourapplication.' + import_name)96+ view = LazyView(f"yourapplication.{import_name}")97 for url_rule in url_rules:98 app.add_url_rule(url_rule, view_func=view, **options)99 100 # add a single route to the index view9 unmodified linesmodified:docs/patterns/requestchecksum.rst+1 added-1 removed
50 unmodified lines51 # Accessing this parses the input stream52 files = request.files53 # At this point the hash is fully constructed.54 checksum = hash.hexdigest()55- return 'Hash was: %s' % checksum55+ return f"Hash was: {checksum}"modified:docs/patterns/sqlalchemy.rst+5 added-5 removed
102 unmodified lines103 104 Querying is simple as well:105 106 >>> User.query.all()107-[<User u'admin'>]107+[<User 'admin'>]108 >>> User.query.filter(User.name == 'admin').first()109-<User u'admin'>109+<User 'admin'>110 111 .. _SQLAlchemy: https://www.sqlalchemy.org/112 .. _declarative:113 https://docs.sqlalchemy.org/en/latest/orm/extensions/declarative/85 unmodified lines199 200 To query your database, you use the engine directly or use a connection:201 202 >>> users.select(users.c.id == 1).execute().first()203-(1, u'admin', u'admin@localhost')203+(1, 'admin', 'admin@localhost')204 205 These results are also dict-like tuples:206 207 >>> r = users.select(users.c.id == 1).execute().first()208 >>> r['name']209-u'admin'209+'admin'210 211 You can also pass strings of SQL statements to the212 :meth:`~sqlalchemy.engine.base.Connection.execute` method:213 214 >>> engine.execute('select * from users where id = :1', [1]).first()215-(1, u'admin', u'admin@localhost')215+(1, 'admin', 'admin@localhost')216 217 For more information about SQLAlchemy, head over to the218 `website <https://www.sqlalchemy.org/>`_.modified:docs/patterns/streaming.rst+1 added-1 removed
19 unmodified lines20 @app.route('/large.csv')21 def generate_large_csv():22 def generate():23 for row in iter_all_rows():24- yield ','.join(row) + '\n'24+ yield f"{','.join(row)}\n"25 return Response(generate(), mimetype='text/csv')26 27 Each ``yield`` expression is directly sent to the browser. Note though28 that some WSGI middlewares might break streaming, so be careful there in56 unmodified linesmodified:docs/patterns/viewdecorators.rst+1 added-2 removed
140 unmodified lines141 @wraps(f)142 def decorated_function(*args, **kwargs):143 template_name = template144 if template_name is None:145- template_name = request.endpoint \146- .replace('.', '/') + '.html'145+ template_name = f"'{request.endpoint.replace('.', '/')}.html'"146 ctx = f(*args, **kwargs)147 if ctx is None:148 ctx = {}149 elif not isinstance(ctx, dict):22 unmodified linesmodified:docs/tutorial/blog.rst+1 added-1 removed
205 unmodified lines206 (id,)207 ).fetchone()208 209 if post is None:210- abort(404, "Post id {0} doesn't exist.".format(id))210+ abort(404, f"Post id {id} doesn't exist.")211 212 if check_author and post['author_id'] != g.user['id']:213 abort(403)214 122 unmodified linesmodified:docs/tutorial/views.rst+1 added-1 removed
92 unmodified lines93 error = 'Password is required.'94 elif db.execute(95 'SELECT id FROM user WHERE username = ?', (username,)96 ).fetchone() is not None:97- error = 'User {} is already registered.'.format(username)97+ error = f"User {username} is already registered."98 99 if error is None:100 db.execute(101 'INSERT INTO user (username, password) VALUES (?, ?)',200 unmodified linesmodified:docs/api.rst+6 added-6 removed
56 unmodified lines57 In this case the values of the above mentioned attributes would be58 the following:59 60 ============= ======================================================61- `path` ``u'/π/page.html'``62- `full_path` ``u'/π/page.html?x=y'``63- `script_root` ``u'/myapplication'``64- `base_url` ``u'http://www.example.com/myapplication/π/page.html'``65- `url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``66- `url_root` ``u'http://www.example.com/myapplication/'``61+ `path` ``'/π/page.html'``62+ `full_path` ``'/π/page.html?x=y'``63+ `script_root` ``'/myapplication'``64+ `base_url` ``'http://www.example.com/myapplication/π/page.html'``65+ `url` ``'http://www.example.com/myapplication/π/page.html?x=y'``66+ `url_root` ``'http://www.example.com/myapplication/'``67 ============= ======================================================68 69 70 .. attribute:: request764 unmodified linesmodified:docs/config.rst+2 added-2 removed
594 unmodified lines595 TESTING = False596 DB_SERVER = '192.168.1.56'597 598 @property599- def DATABASE_URI(self): # Note: all caps600- return 'mysql://user@{}/foo'.format(self.DB_SERVER)599+ def DATABASE_URI(self): # Note: all caps600+ return f"mysql://user@{self.DB_SERVER}/foo"601 602 class ProductionConfig(Config):603 """Uses production database server."""604 DB_SERVER = '192.168.19.32'113 unmodified linesmodified:docs/quickstart.rst+5 added-5 removed
445 unmodified lines446 Here is a basic introduction to how the :class:`~markupsafe.Markup` class works::447 448 >>> from markupsafe import Markup449 >>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'450- Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')450+ Markup('<strong>Hello <blink>hacker</blink>!</strong>')451 >>> Markup.escape('<blink>hacker</blink>')452- Markup(u'<blink>hacker</blink>')452+ Markup('<blink>hacker</blink>')453 >>> Markup('<em>Marked up</em> » HTML').striptags()454- u'Marked up \xbb HTML'454+ 'Marked up \xbb HTML'455 456 .. versionchanged:: 0.5457 458 Autoescaping is no longer enabled for all templates. The following149 unmodified lines608 609 @app.route('/upload', methods=['GET', 'POST'])610 def upload_file():611 if request.method == 'POST':612- f = request.files['the_file']613- f.save('/var/www/uploads/' + secure_filename(f.filename))612+ file = request.files['the_file']613+ file.save(f"/var/www/uploads/{secure_filename(f.filename)}")614 ...615 616 For some better examples, checkout the :ref:`uploading-files` pattern.617 304 unmodified linesmodified:docs/templating.rst+2 added-2 removed
220 unmodified lines221 functions)::222 223 @app.context_processor224 def utility_processor():225- def format_price(amount, currency=u'€'):226- return u'{0:.2f}{1}'.format(amount, currency)225+ def format_price(amount, currency="€"):226+ return f"{amount:.2f}{currency}"227 return dict(format_price=format_price)228 229 The context processor above makes the `format_price` function available to all230 templates::6 unmodified linesmodified:docs/testing.rst+6 added-3 removed
163 unmodified lines164 165 def test_login_logout(client):166 """Make sure login and logout works."""167 168- rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])168+ username = flaskr.app.config["USERNAME"]169+ password = flaskr.app.config["PASSWORD"]170+171+ rv = login(client, username, password)172 assert b'You were logged in' in rv.data173 174 rv = logout(client)175 assert b'You were logged out' in rv.data176 174- rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])177+ rv = login(client, f"{username}x", password)178 assert b'Invalid username' in rv.data179 177- rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')180+ rv = login(client, username, f'{password}x')181 assert b'Invalid password' in rv.data182 183 Test Adding Messages184 --------------------280 unmodified linesmodified:src/flask/json/__init__.py+1 added-1 removed
362 unmodified lines363 else:364 data = args or kwargs365 366 return current_app.response_class(367- dumps(data, indent=indent, separators=separators) + "\n",367+ f"{dumps(data, indent=indent, separators=separators)}\n",368 mimetype=current_app.config["JSONIFY_MIMETYPE"],369 )370 371 2 unmodified linesmodified:src/flask/json/tag.py+1 added-1 removed
103 unmodified lines104 )105 106 def to_json(self, value):107 key = next(iter(value))108- return {key + "__": self.serializer.tag(value[key])}108+ return {f"{key}__": self.serializer.tag(value[key])}109 110 def to_python(self, value):111 key = next(iter(value))112 return {key[:-2]: value[key]}194 unmodified linesmodified:src/flask/app.py+27 added-25 removed
583 unmodified lines584 assert (585 bool(static_host) == host_matching586 ), "Invalid static_host/host_matching combination"587 self.add_url_rule(588- self.static_url_path + "/<path:filename>",588+ f"{self.static_url_path}/<path:filename>",589 endpoint="static",590 host=static_host,591 view_func=self.send_static_file,592 )117 unmodified lines710 """711 prefix, package_path = find_package(self.import_name)712 if prefix is None:713 return os.path.join(package_path, "instance")714- return os.path.join(prefix, "var", self.name + "-instance")714+ return os.path.join(prefix, "var", f"{self.name}-instance")715 716 def open_instance_resource(self, resource, mode="rb"):717 """Opens a resource from the application's instance folder718 (:attr:`instance_path`). Otherwise works like364 unmodified lines1083 first_registration = False1084 1085 if blueprint.name in self.blueprints:1086 assert self.blueprints[blueprint.name] is blueprint, (1087- "A name collision occurred between blueprints %r and %r. Both"1088- ' share the same name "%s". Blueprints that are created on the'1089- " fly need unique names."1090- % (blueprint, self.blueprints[blueprint.name], blueprint.name)1087+ "A name collision occurred between blueprints"1088+ f" {blueprint!r} and {self.blueprints[blueprint.name]!r}."1089+ f" Both share the same name {blueprint.name!r}."1090+ f" Blueprints that are created on the fly need unique"1091+ f" names."1092 )1093 else:1094 self.blueprints[blueprint.name] = blueprint1095 self._blueprint_order.append(blueprint)113 unmodified lines1209 if view_func is not None:1210 old_func = self.view_functions.get(endpoint)1211 if old_func is not None and old_func != view_func:1212 raise AssertionError(1212- "View function mapping is overwriting an "1213- "existing endpoint function: %s" % endpoint1213+ "View function mapping is overwriting an existing"1214+ f" endpoint function: {endpoint}"1215 )1216 self.view_functions[endpoint] = view_func1217 1218 def route(self, rule, **options):122 unmodified lines1341 :type f: callable1342 """1343 if isinstance(code_or_exception, HTTPException): # old broken behavior1344 raise ValueError(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)1345+ "Tried to register a handler for an exception instance"1346+ f" {code_or_exception!r}. Handlers can only be"1347+ " registered for exception classes or HTTP error codes."1348 )1349 1350 try:1351 exc_class, code = self._get_exc_class_and_code(code_or_exception)1352 except KeyError:1353 raise KeyError(1353- "'{}' is not a recognized HTTP error code. Use a subclass of"1354- " HTTPException with that code instead.".format(code_or_exception)1354+ f"'{code_or_exception}' is not a recognized HTTP error"1355+ " code. Use a subclass of HTTPException with that code"1356+ " instead."1357 )1358 1359 handlers = self.error_handler_spec.setdefault(key, {}).setdefault(code, {})1360 handlers[exc_class] = f370 unmodified lines1731 # Werkzeug < 0.15 doesn't add the KeyError to the 4001732 # message, add it in manually.1733 # TODO: clean up once Werkzeug >= 0.15.5 is required1734 if e.args[0] not in e.get_description():1733- e.description = "KeyError: '{}'".format(*e.args)1735+ e.description = f"KeyError: {e.args[0]!r}"1736 elif not hasattr(BadRequestKeyError, "show_exception"):1737 e.args = ()1738 1739 if isinstance(e, HTTPException) and not self.trap_http_exception(e):267 unmodified lines2007 2008 # the body must not be None2009 if rv is None:2010 raise TypeError(2009- 'The view function for "{}" did not return a valid response. The'2010- " function either returned None or ended without a return"2011- " statement.".format(request.endpoint)2011+ f"The view function for {request.endpoint!r} did not"2012+ " return a valid response. The function either returned"2013+ " None or ended without a return statement."2014 )2015 2016 # make sure the body is an instance of the response class2017 if not isinstance(rv, self.response_class):11 unmodified lines2029 try:2030 rv = self.response_class.force_type(rv, request.environ)2031 except TypeError as e:2032 raise TypeError(2031- "{e}\nThe view function did not return a valid"2032- " response. The return type must be a string, dict, tuple,"2033- " Response instance, or WSGI callable, but it was a"2034- " {rv.__class__.__name__}.".format(e=e, rv=rv)2033+ f"{e}\nThe view function did not return a valid"2034+ " response. The return type must be a string,"2035+ " dict, tuple, Response instance, or WSGI"2036+ f" callable, but it was a {type(rv).__name__}."2037 ).with_traceback(sys.exc_info()[2])2038 else:2039 raise TypeError(2040 "The view function did not return a valid"2039- " response. The return type must be a string, dict, tuple,"2040- " Response instance, or WSGI callable, but it was a"2041- " {rv.__class__.__name__}.".format(rv=rv)2041+ " response. The return type must be a string,"2042+ " dict, tuple, Response instance, or WSGI"2043+ f" callable, but it was a {type(rv).__name__}."2044 )2045 2046 # prefer the status if it was provided2047 if status is not None:328 unmodified lines2376 wrapped to applying middleware."""2377 return self.wsgi_app(environ, start_response)2378 2379 def __repr__(self):2378- return f"<{self.__class__.__name__} {self.name!r}>"2380+ return f"<{type(self).__name__} {self.name!r}>"modified:src/flask/blueprints.py+1 added-1 removed
244 unmodified lines245 state = self.make_setup_state(app, options, first_registration)246 247 if self.has_static_folder:248 state.add_url_rule(249- self.static_url_path + "/<path:filename>",249+ f"{self.static_url_path}/<path:filename>",250 view_func=self.send_static_file,251 endpoint="static",252 )253 315 unmodified linesmodified:src/flask/cli.py+34 added-40 removed
60 unmodified lines61 if len(matches) == 1:62 return matches[0]63 elif len(matches) > 1:64 raise NoAppException(65- 'Detected multiple Flask applications in module "{module}". Use '66- '"FLASK_APP={module}:name" to specify the correct '67- "one.".format(module=module.__name__)65+ "Detected multiple Flask applications in module"66+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"67+ f" to specify the correct one."68 )69 70 # Search for app factory functions.71- for attr_name in ("create_app", "make_app"):71+ for attr_name in {"create_app", "make_app"}:72 app_factory = getattr(module, attr_name, None)73 74 if inspect.isfunction(app_factory):75 try:4 unmodified lines80 except TypeError:81 if not _called_with_wrong_args(app_factory):82 raise83 raise NoAppException(84- 'Detected factory "{factory}" in module "{module}", but '85- "could not call it without arguments. Use "86- "\"FLASK_APP='{module}:{factory}(args)'\" to specify "87- "arguments.".format(factory=attr_name, module=module.__name__)84+ f"Detected factory {attr_name!r} in module {module.__name__!r},"85+ " but could not call it without arguments. Use"86+ f" \"FLASK_APP='{module.__name__}:{attr_name}(args)'\""87+ " to specify arguments."88 )89 90 raise NoAppException(91- 'Failed to find Flask application or factory in module "{module}". '92- 'Use "FLASK_APP={module}:name to specify one.'.format(module=module.__name__)91+ "Failed to find Flask application or factory in module"92+ f" {module.__name__!r}. Use 'FLASK_APP={module.__name__}:name'"93+ " to specify one."94 )95 96 97 def call_factory(script_info, app_factory, arguments=()):52 unmodified lines150 match = re.match(r"^ *([^ ()]+) *(?:\((.*?) *,? *\))? *$", app_name)151 152 if not match:153 raise NoAppException(153- '"{name}" is not a valid variable name or function '154- "expression.".format(name=app_name)154+ f"{app_name!r} is not a valid variable name or function expression."155 )156 157 name, args = match.groups()158 5 unmodified lines164 if inspect.isfunction(attr):165 if args:166 try: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)172- )168+ except (ValueError, SyntaxError):169+ raise NoAppException(f"Could not parse the arguments in {app_name!r}.")170 else:171 args = ()172 173 try:2 unmodified lines176 if not _called_with_wrong_args(attr):177 raise178 179 raise NoAppException(183- '{e}\nThe factory "{app_name}" in module "{module}" could not '184- "be called with the specified arguments.".format(185- e=e, app_name=app_name, module=module.__name__186- )180+ f"{e}\nThe factory {app_name!r} in module"181+ f" {module.__name__!r} could not be called with the"182+ " specified arguments."183 )184 else:185 app = attr186 187 if isinstance(app, Flask):188 return app189 190 raise NoAppException(195- "A valid Flask application was not obtained from "196- '"{module}:{app_name}".'.format(module=module.__name__, app_name=app_name)191+ "A valid Flask application was not obtained from"192+ f" '{module.__name__}:{app_name}'."193 )194 195 196 def prepare_import(path):34 unmodified lines231 # Reraise the ImportError if it occurred within the imported module.232 # Determine this by checking whether the trace has a depth > 1.233 if sys.exc_info()[2].tb_next:234 raise NoAppException(239- 'While importing "{name}", an ImportError was raised:'240- "\n\n{tb}".format(name=module_name, tb=traceback.format_exc())235+ f"While importing {module_name!r}, an ImportError was"236+ f" raised:\n\n{traceback.format_exc()}"237 )238 elif raise_if_not_found:243- raise NoAppException(f'Could not import "{module_name}".')239+ raise NoAppException(f"Could not import {module_name!r}.")240 else:241 return242 243 module = sys.modules[module_name]10 unmodified lines254 255 import werkzeug256 from . import __version__257 262- message = "Python %(python)s\nFlask %(flask)s\nWerkzeug %(werkzeug)s"258 click.echo(264- message265- % {266- "python": platform.python_version(),267- "flask": __version__,268- "werkzeug": werkzeug.__version__,269- },259+ f"Python {platform.python_version()}\n"260+ f"Flask {__version__}\n"261+ f"Werkzeug {werkzeug.__version__}",262 color=ctx.color,263 )264 ctx.exit()265 384 unmodified lines650 if os.environ.get("WERKZEUG_RUN_MAIN") == "true":651 return652 653 if app_import_path is not None:662- message = f' * Serving Flask app "{app_import_path}"'654+ message = f" * Serving Flask app {app_import_path!r}"655 656 if not eager_loading:657 message += " (lazy loading)"658 2 unmodified lines661 click.echo(f" * Environment: {env}")662 663 if env == "production":664 click.secho(673- " WARNING: This is a development server. "674- "Do not use it in a production deployment.",665+ " WARNING: This is a development server. Do not use it in"666+ " a production deployment.",667 fg="red",668 )669 click.secho(" Use a production WSGI server instead.", dim=True)670 671 if debug is not None:680- click.echo(" * Debug mode: {}".format("on" if debug else "off"))672+ click.echo(f" * Debug mode: {'on' if debug else 'off'}")673 674 675 class CertParamType(click.ParamType):676 """Click option type for the ``--cert`` option. Allows either an123 unmodified lines800 default=None,801 type=SeparatedPathType(),802 help=(803 "Extra files that trigger a reload on change. Multiple paths"812- " are separated by '{}'.".format(os.path.pathsep)804+ f" are separated by {os.path.pathsep!r}."805 ),806 )807 @pass_script_info808 def run_command(45 unmodified lines854 import code855 from .globals import _app_ctx_stack856 857 app = _app_ctx_stack.top.app866- banner = "Python {} on {}\nApp: {} [{}]\nInstance: {}".format(867- sys.version, sys.platform, app.import_name, app.env, app.instance_path,858+ banner = (859+ f"Python {sys.version} on {sys.platform}\n"860+ f"App: {app.import_name} [{app.env}]\n"861+ f"Instance: {app.instance_path}"862 )863 ctx = {}864 865 # Support the regular Python interpreter startup script if someone84 unmodified linesmodified:src/flask/config.py+8 added-8 removed
96 unmodified lines97 if not rv:98 if silent:99 return False100 raise RuntimeError(101- "The environment variable %r is not set "102- "and as such configuration could not be "103- "loaded. Set this variable and make it "104- "point to a configuration file" % variable_name101+ f"The environment variable {variable_name!r} is not set"102+ " and as such configuration could not be loaded. Set"103+ " this variable and make it point to a configuration"104+ " file"105 )106 return self.from_pyfile(rv, silent=silent)107 108 def from_pyfile(self, filename, silent=False):18 unmodified lines127 exec(compile(config_file.read(), filename, "exec"), d.__dict__)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.strerror131+ e.strerror = f"Unable to load configuration file ({e.strerror})"132 raise133 self.from_object(d)134 return True135 63 unmodified lines199 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.strerror203+ e.strerror = f"Unable to load configuration file ({e.strerror})"204 raise205 206 return self.from_mapping(obj)207 10 unmodified lines218 else:219 mappings.append(mapping[0])220 elif len(mapping) > 1:221 raise TypeError(222- "expected at most 1 positional argument, got %d" % len(mapping)222+ f"expected at most 1 positional argument, got {len(mapping)}"223 )224 mappings.append(kwargs.items())225 for mapping in mappings:226 for (key, value) in mapping:42 unmodified lines269 rv[key] = v270 return rv271 272 def __repr__(self):273- return "<{} {}>".format(self.__class__.__name__, dict.__repr__(self))273+ return f"<{type(self).__name__} {dict.__repr__(self)}>"modified:src/flask/ctx.py+4 added-6 removed
86 unmodified lines87 88 def __repr__(self):89 top = _app_ctx_stack.top90 if top is not None:91- return "<flask.g of %r>" % top.app.name91+ return f"<flask.g of {top.app.name!r}>"92 return object.__repr__(self)93 94 95 def after_this_request(f):348 unmodified lines444 # See flask.testing for how this works.445 self.auto_pop(exc_value)446 447 def __repr__(self):448- return "<{} '{}' [{}] of {}>".format(449- self.__class__.__name__,450- self.request.url,451- self.request.method,452- self.app.name,448+ return (449+ f"<{type(self).__name__} {self.request.url!r}"450+ f" [{self.request.method}] of {self.app.name}>"451 )modified:src/flask/debughelpers.py+35 added-35 removed
27 unmodified lines28 29 def __init__(self, request, key):30 form_matches = request.form.getlist(key)31 buf = [32- 'You tried to access the file "%s" in the request.files '33- "dictionary but it does not exist. The mimetype for the request "34- 'is "%s" instead of "multipart/form-data" which means that no '35- "file contents were transmitted. To fix this error you should "36- 'provide enctype="multipart/form-data" in your form.'37- % (key, request.mimetype)32+ f"You tried to access the file {key!r} in the request.files"33+ " dictionary but it does not exist. The mimetype for the"34+ f" request is {request.mimetype!r} instead of"35+ " 'multipart/form-data' which means that no file contents"36+ " were transmitted. To fix this error you should provide"37+ ' enctype="multipart/form-data" in your form.'38 ]39 if form_matches:40+ names = ", ".join(repr(x) for x in form_matches)41 buf.append(42 "\n\nThe browser instead transmitted some file names. "42- "This was submitted: %s" % ", ".join('"%s"' % x for x in form_matches)43+ f"This was submitted: {names}"44 )45 self.msg = "".join(buf)46 47 def __str__(self):8 unmodified lines56 57 def __init__(self, request):58 exc = request.routing_exception59 buf = [59- "A request was sent to this URL (%s) but a redirect was "60- 'issued automatically by the routing system to "%s".'61- % (request.url, exc.new_url)60+ f"A request was sent to this URL ({request.url}) but a"61+ " redirect was issued automatically by the routing system"62+ f" to {exc.new_url!r}."63 ]64 65 # In case just a slash was appended we can be extra helpful65- if request.base_url + "/" == exc.new_url.split("?")[0]:66+ if f"{request.base_url}/" == exc.new_url.split("?")[0]:67 buf.append(67- " The URL was defined with a trailing slash so "68- "Flask will automatically redirect to the URL "69- "with the trailing slash if it was accessed "70- "without one."68+ " The URL was defined with a trailing slash so Flask"69+ " will automatically redirect to the URL with the"70+ " trailing slash if it was accessed without one."71 )72 73 buf.append(74- " Make sure to directly send your %s-request to this URL "75- "since we can't make browsers or HTTP clients redirect "76- "with form data reliably or without user interaction." % request.method74+ " Make sure to directly send your"75+ f" {request.method}-request to this URL since we can't make"76+ " browsers or HTTP clients redirect with form data reliably"77+ " or without user interaction."78 )79 buf.append("\n\nNote: this exception is only raised in debug mode")80 AssertionError.__init__(self, "".join(buf).encode("utf-8"))81 19 unmodified lines101 request.files.__class__ = newcls102 103 104 def _dump_loader_info(loader):104- yield "class: {}.{}".format(type(loader).__module__, type(loader).__name__)105+ yield f"class: {type(loader).__module__}.{type(loader).__name__}"106 for key, value in sorted(loader.__dict__.items()):107 if key.startswith("_"):108 continue109 if isinstance(value, (tuple, list)):110 if not all(isinstance(x, str) for x in value):111 continue111- yield "%s:" % key112+ yield f"{key}:"113 for item in value:113- yield " - %s" % item114+ yield f" - {item}"115 continue116 elif not isinstance(value, (str, int, float, bool)):117 continue118 yield f"{key}: {value!r}"119 120 121 def explain_template_loading_attempts(app, template, attempts):122 """This should help developers understand what failed"""122- info = ['Locating template "%s":' % template]123+ info = [f"Locating template {template!r}:"]124 total_found = 0125 blueprint = None126 reqctx = _request_ctx_stack.top127 if reqctx is not None and reqctx.request.blueprint is not None:128 blueprint = reqctx.request.blueprint129 130 for idx, (loader, srcobj, triple) in enumerate(attempts):131 if isinstance(srcobj, Flask):131- src_info = 'application "%s"' % srcobj.import_name132+ src_info = f"application {srcobj.import_name!r}"133 elif isinstance(srcobj, Blueprint):133- src_info = f'blueprint "{srcobj.name}" ({srcobj.import_name})'134+ src_info = f"blueprint {srcobj.name!r} ({srcobj.import_name})"135 else:136 src_info = repr(srcobj)137 137- info.append("% 5d: trying loader of %s" % (idx + 1, src_info))138+ info.append(f"{idx + 1:5}: trying loader of {src_info}")139 140 for line in _dump_loader_info(loader):140- info.append(" %s" % line)141+ info.append(f" {line}")142 143 if triple is None:144 detail = "no match"145 else:145- detail = "found (%r)" % (triple[1] or "<string>")146+ detail = f"found ({triple[1] or '<string>'!r})"147 total_found += 1147- info.append(" -> %s" % detail)148+ info.append(f" -> {detail}")149 150 seems_fishy = False151 if total_found == 0:152 info.append("Error: the template could not be found.")3 unmodified lines156 seems_fishy = True157 158 if blueprint is not None and seems_fishy:159 info.append(159- " The template was looked up from an endpoint that "160- 'belongs to the blueprint "%s".' % blueprint160+ " The template was looked up from an endpoint that belongs"161+ f" to the blueprint {blueprint!r}."162 )163 info.append(" Maybe you did not place a template in the right folder?")164 info.append(" See https://flask.palletsprojects.com/blueprints/#templates")165 3 unmodified lines169 def explain_ignored_app_run():170 if os.environ.get("WERKZEUG_RUN_MAIN") != "true":171 warn(172 Warning(172- "Silently ignoring app.run() because the "173- "application is run from the flask command line "174- "executable. Consider putting app.run() behind an "175- 'if __name__ == "__main__" guard to silence this '176- "warning."173+ "Silently ignoring app.run() because the application is"174+ " run from the flask command line executable. Consider"175+ ' putting app.run() behind an if __name__ == "__main__"'176+ " guard to silence this warning."177 ),178 stacklevel=3,179 )modified:src/flask/helpers.py+24 added-34 removed
309 unmodified lines310 blueprint_name = request.blueprint311 312 if endpoint[:1] == ".":313 if blueprint_name is not None:314- endpoint = blueprint_name + endpoint314+ endpoint = f"{blueprint_name}{endpoint}"315 else:316 endpoint = endpoint[1:]317 318 external = values.pop("_external", False)44 unmodified lines363 values["_scheme"] = scheme364 return appctx.app.handle_url_build_error(error, endpoint, values)365 366 if anchor is not None:367- rv += "#" + url_quote(anchor)367+ rv += f"#{url_quote(anchor)}"368 return rv369 370 371 def get_template_attribute(template_name, attribute):235 unmodified lines607 608 try:609 attachment_filename = attachment_filename.encode("ascii")610 except UnicodeEncodeError:611+ quoted = url_quote(attachment_filename, safe="")612 filenames = {613 "filename": unicodedata.normalize("NFKD", attachment_filename).encode(614 "ascii", "ignore"615 ),615- "filename*": "UTF-8''%s" % url_quote(attachment_filename, safe=""),616+ "filename*": f"UTF-8''{quoted}",617 }618 else:619 filenames = {"filename": attachment_filename}620 40 unmodified lines661 if add_etags and filename is not None:662 from warnings import warn663 664 try:664- rv.set_etag(665- "%s-%s-%s"666- % (667- os.path.getmtime(filename),668- os.path.getsize(filename),669- adler32(670- filename.encode("utf-8")671- if isinstance(filename, str)672- else filename673- )674- & 0xFFFFFFFF,665+ check = (666+ adler32(667+ filename.encode("utf-8") if isinstance(filename, str) else filename668 )669+ & 0xFFFFFFFF670 )671+ rv.set_etag(672+ f"{os.path.getmtime(filename)}-{os.path.getsize(filename)}-{check}"673+ )674 except OSError:675 warn(679- "Access %s failed, maybe it does not exist, so ignore etags in "680- "headers" % filename,676+ f"Access {filename} failed, maybe it does not exist, so"677+ " ignore etags in headers",678 stacklevel=2,679 )680 681 if conditional:120 unmodified lines802 # namespace package. In this case we pick the root path from the803 # first module that is contained in our package.804 if filepath is None:805 raise RuntimeError(809- "No root path can be found for the provided "810- 'module "%s". This can happen because the '811- "module came from an import hook that does "812- "not provide file name information or because "813- "it's a namespace package. In this case "814- "the root path needs to be explicitly "815- "provided." % import_name806+ "No root path can be found for the provided module"807+ f" {import_name!r}. This can happen because the module"808+ " came from an import hook that does not provide file"809+ " name information or because it's a namespace package."810+ " In this case the root path needs to be explicitly"811+ " provided."812 )813 814 # filepath is import_name.py for a module, or __init__.py for a package.815 return os.path.dirname(os.path.abspath(filepath))2 unmodified lines818 def _matching_loader_thinks_module_is_package(loader, mod_name):819 """Given the loader that loaded a module and the module this function820 attempts to figure out if the given module is actually a package.821 """822+ cls = type(loader)823 # If the loader can tell us if something is a package, we can824 # directly ask the loader.825 if hasattr(loader, "is_package"):826 return loader.is_package(mod_name)827 # importlib's namespace loaders do not have this functionality but828 # all the modules it loads are packages, so we can take advantage of829 # this information.833- elif (834- loader.__class__.__module__ == "_frozen_importlib"835- and loader.__class__.__name__ == "NamespaceLoader"836- ):830+ elif cls.__module__ == "_frozen_importlib" and cls.__name__ == "NamespaceLoader":831 return True832 # Otherwise we need to fail with an error that explains what went833 # wrong.834 raise AttributeError(841- (842- "%s.is_package() method is missing but is required by Flask of "843- "PEP 302 import hooks. If you do not use import hooks and "844- "you encounter this error please file a bug against Flask."845- )846- % loader.__class__.__name__835+ f"{cls.__name__}.is_package() method is missing but is required"836+ " for PEP 302 import hooks."837 )838 839 840 def _find_package_path(root_mod_name):162 unmodified lines1003 return self._static_url_path1004 1005 if self.static_folder is not None:1006 basename = os.path.basename(self.static_folder)1017- return ("/" + basename).rstrip("/")1007+ return f"/{basename}".rstrip("/")1008 1009 @static_url_path.setter1010 def static_url_path(self, value):1011 if value is not None:122 unmodified linesmodified:src/flask/sessions.py+7 added-7 removed
206 unmodified lines207 # remove any leading '.' since we'll add that later208 rv = rv.rsplit(":", 1)[0].lstrip(".")209 210 if "." not in rv:211- # Chrome doesn't allow names without a '.'212- # this should only come up with localhost213- # hack around this by not setting the name, and show a warning211+ # Chrome doesn't allow names without a '.'. This should only212+ # come up with localhost. Hack around this by not setting213+ # the name, and show a warning.214 warnings.warn(215- '"{rv}" is not a valid cookie domain, it must contain a ".".'216- " Add an entry to your hosts file, for example"217- ' "{rv}.localdomain", and use that instead.'.format(rv=rv)215+ f"{rv!r} is not a valid cookie domain, it must contain"216+ " a '.'. Add an entry to your hosts file, for example"217+ f" '{rv}.localdomain', and use that instead."218 )219 app.config["SESSION_COOKIE_DOMAIN"] = False220 return None221 9 unmodified lines231 232 # if this is not an ip and app is mounted at the root, allow subdomain233 # matching by adding a '.' prefix234 if self.get_cookie_path(app) == "/" and not ip:235- rv = "." + rv235+ rv = f".{rv}"236 237 app.config["SESSION_COOKIE_DOMAIN"] = rv238 return rv239 154 unmodified linesmodified:src/flask/testing.py+4 added-5 removed
67 unmodified lines68 if url_scheme is None:69 url_scheme = app.config["PREFERRED_URL_SCHEME"]70 71 url = url_parse(path)72- base_url = "{scheme}://{netloc}/{path}".format(73- scheme=url.scheme or url_scheme,74- netloc=url.netloc or http_host,75- path=app_root.lstrip("/"),72+ base_url = (73+ f"{url.scheme or url_scheme}://{url.netloc or http_host}"74+ f"/{app_root.lstrip('/')}"75 )76 path = url.path77 78 if url.query:33 unmodified lines112 def __init__(self, *args, **kwargs):113 super().__init__(*args, **kwargs)114 self.environ_base = {115 "REMOTE_ADDR": "127.0.0.1",117- "HTTP_USER_AGENT": "werkzeug/" + werkzeug.__version__,116+ "HTTP_USER_AGENT": f"werkzeug/{werkzeug.__version__}",117 }118 119 @contextmanager120 def session_transaction(self, *args, **kwargs):143 unmodified linesmodified:src/flask/views.py+2 added-2 removed
24 unmodified lines25 class MyView(View):26 methods = ['GET']27 28 def dispatch_request(self, name):29- return 'Hello %s!' % name29+ return f"Hello {name}!"30 31 app.add_url_rule('/hello/<name>', view_func=MyView.as_view('myview'))32 33 When you want to decorate a pluggable view you will have to either do that122 unmodified lines156 # retry with GET.157 if meth is None and request.method == "HEAD":158 meth = getattr(self, "get", None)159 160- assert meth is not None, "Unimplemented method %r" % request.method160+ assert meth is not None, f"Unimplemented method {request.method!r}"161 return meth(*args, **kwargs)modified:tests/conftest.py+11 added-14 removed
114 unmodified lines115 def __init__(self, loader):116 self.loader = loader117 118 def __getattr__(self, name):119- if name in ("archive", "get_filename"):120- msg = "Mocking a loader which does not have `%s.`" % name121- raise AttributeError(msg)119+ if name in {"archive", "get_filename"}:120+ raise AttributeError(f"Mocking a loader which does not have {name!r}.")121 return getattr(self.loader, name)122 123 old_get_loader = pkgutil.get_loader124 21 unmodified lines146 def site_packages(modules_tmpdir, monkeypatch):147 """Create a fake site-packages."""148 rv = (149 modules_tmpdir.mkdir("lib")151- .mkdir("python{x[0]}.{x[1]}".format(x=sys.version_info))150+ .mkdir(f"python{sys.version_info.major}.{sys.version_info.minor}")151 .mkdir("site-packages")152 )153 monkeypatch.syspath_prepend(str(rv))154 return rv4 unmodified lines159 """Generate egg from package name inside base and put the egg into160 sys.path."""161 162 def inner(name, base=modules_tmpdir):164- if not isinstance(name, str):165- raise ValueError(name)163 base.join(name).ensure_dir()164 base.join(name).join("__init__.py").ensure()165 166 egg_setup = base.join("setup.py")167 egg_setup.write(168 textwrap.dedent(172- """173- from setuptools import setup174- setup(name='{}',175- version='1.0',176- packages=['site_egg'],177- zip_safe=True)178- """.format(179- name169+ f"""170+ from setuptools import setup171+ setup(172+ name="{name}",173+ version="1.0",174+ packages=["site_egg"],175+ zip_safe=True,176 )177+ """178 )179 )180 181 import subprocess17 unmodified linesmodified:tests/test_basic.py+4 added-4 removed
359 unmodified lines360 361 rv = client.get("/", "http://localhost:5000/")362 assert "domain" not in rv.headers["set-cookie"].lower()363 w = recwarn.pop(UserWarning)364- assert '"localhost" is not a valid cookie domain' in str(w.message)364+ assert "'localhost' is not a valid cookie domain" in str(w.message)365 366 367 def test_session_ip_warning(recwarn, app, client):368 app.config.update(SERVER_NAME="127.0.0.1:5000")725 unmodified lines1094 with client:1095 with pytest.raises(DebugFilesKeyError) as e:1096 client.post("/fail", data={"foo": "index.txt"})1097 assert "no file contents were transmitted" in str(e.value)1098- assert 'This was submitted: "index.txt"' in str(e.value)1098+ assert "This was submitted: 'index.txt'" in str(e.value)1099 1100 1101 def test_response_types(app, client):1102 @app.route("/text")717 unmodified lines1820 app.config["SERVER_NAME"] = "localhost.localdomain"1821 1822 @app.route("/", subdomain="<user>")1823 def index(user):1824- return "index for %s" % user1824+ return f"index for {user}"1825 1826 rv = client.get("/", "http://mitsuhiko.localhost.localdomain/")1827 assert rv.data == b"index for mitsuhiko"1828 4 unmodified lines1833 client = app.test_client()1834 1835 @app.route("/", subdomain="<user>")1836 def index(user):1837- return "index for %s" % user1837+ return f"index for {user}"1838 1839 rv = client.get("/", "http://mitsuhiko.localhost.localdomain:3000/")1840 assert rv.data == b"index for mitsuhiko"1841 127 unmodified linesmodified:tests/test_blueprints.py+1 added-1 removed
142 unmodified lines143 bp = flask.Blueprint("test", __name__)144 145 @bp.route("/foo", defaults={"baz": 42})146 def foo(bar, baz):147- return "%s/%d" % (bar, baz)147+ return f"{bar}/{baz:d}"148 149 @bp.route("/bar")150 def bar(bar):151 return str(bar)710 unmodified linesmodified:tests/test_cli.py+6 added-6 removed
266 unmodified lines267 268 ctx = MockCtx()269 get_version(ctx, None, "test")270 out, err = capsys.readouterr()271- assert "Python " + python_version() in out272- assert "Flask " + flask_version in out273- assert "Werkzeug " + werkzeug_version in out271+ assert f"Python {python_version()}" in out272+ assert f"Flask {flask_version}" in out273+ assert f"Werkzeug {werkzeug_version}" in out274 275 276 def test_scriptinfo(test_apps, monkeypatch):277 """Test of ScriptInfo."""9 unmodified lines287 obj = ScriptInfo(app_import_path=cli_app_path)288 app = obj.load_app()289 assert app.name == "testapp"290 assert obj.load_app() is app291- obj = ScriptInfo(app_import_path=cli_app_path + ":testapp")291+ obj = ScriptInfo(app_import_path=f"{cli_app_path}:testapp")292 app = obj.load_app()293 assert app.name == "testapp"294 assert obj.load_app() is app295 109 unmodified lines405 click.echo(str(current_app.debug))406 407 result = runner.invoke(cli, ["test"])408 assert result.exit_code == 0409- assert result.output == "%s\n" % str(not set_debug_flag)409+ assert result.output == f"{not set_debug_flag}\n"410 411 412 def test_print_exceptions(runner):413 """Print the stacktrace if the CLI."""241 unmodified lines655 bp = Blueprint("blue", __name__, cli_group="blue")656 app.register_blueprint(bp)657 658 result = app.test_cli_runner().invoke(args=["blue", "--help"])659- assert result.exit_code == 2, "Unexpected success:\n\n" + result.output659+ assert result.exit_code == 2, f"Unexpected success:\n\n{result.output}"modified:tests/test_config.py+5 added-7 removed
26 unmodified lines27 28 29 def test_config_from_pyfile():30 app = flask.Flask(__name__)31- app.config.from_pyfile(__file__.rsplit(".", 1)[0] + ".py")31+ app.config.from_pyfile(f"{__file__.rsplit('.', 1)[0]}.py")32 common_object_test(app)33 34 35 def test_config_from_object():47 unmodified lines83 assert "'FOO_SETTINGS' is not set" in str(e.value)84 assert not app.config.from_envvar("FOO_SETTINGS", silent=True)85 86 monkeypatch.setattr(87- "os.environ", {"FOO_SETTINGS": __file__.rsplit(".", 1)[0] + ".py"}87+ "os.environ", {"FOO_SETTINGS": f"{__file__.rsplit('.', 1)[0]}.py"}88 )89 assert app.config.from_envvar("FOO_SETTINGS")90 common_object_test(app)91 92 unmodified lines184 def test_from_pyfile_weird_encoding(tmpdir, encoding):185 f = tmpdir.join("my_config.py")186 f.write_binary(187 textwrap.dedent(188+ f"""189+ # -*- coding: {encoding} -*-190+ TEST_VALUE = "föö"191 """189- # -*- coding: {} -*-190- TEST_VALUE = "föö"191- """.format(192- encoding193- )192 ).encode(encoding)193 )194 app = flask.Flask(__name__)195 app.config.from_pyfile(str(f))2 unmodified linesmodified:tests/test_helpers.py+8 added-6 removed
284 unmodified lines285 286 class MyEncoder(flask.json.JSONEncoder):287 def default(self, o):288 if isinstance(o, X):289- return "<%d>" % o.val289+ return f"<{o.val}>"290 return flask.json.JSONEncoder.default(self, o)291 292 class MyDecoder(flask.json.JSONDecoder):293 def __init__(self, *args, **kwargs):19 unmodified lines313 )314 assert rv.data == b'"<42>"'315 316 def test_blueprint_json_customization(self, app, client):317- class X: # noqa: B903, for Python2 compatibility317+ class X:318+ __slots__ = ("val",)319+320 def __init__(self, val):321 self.val = val322 323 class MyEncoder(flask.json.JSONEncoder):324 def default(self, o):325 if isinstance(o, X):324- return "<%d>" % o.val326+ return f"<{o.val}>"327 328 return flask.json.JSONEncoder.default(self, o)329 330 class MyDecoder(flask.json.JSONDecoder):357 unmodified lines688 "static/index.html", as_attachment=True, attachment_filename=filename689 )690 rv.close()691 content_disposition = rv.headers["Content-Disposition"]690- assert "filename=%s" % ascii in content_disposition692+ assert f"filename={ascii}" in content_disposition693 if utf8:692- assert "filename*=UTF-8''" + utf8 in content_disposition694+ assert f"filename*=UTF-8''{utf8}" in content_disposition695 else:696 assert "filename*=UTF-8''" not in content_disposition697 698 def test_static_file(self, app, req_ctx):120 unmodified lines819 class MyView(MethodView):820 def get(self, id=None):821 if id is None:822 return "List"821- return "Get %d" % id823+ return f"Get {id:d}"824 825 def post(self):826 return "Create"827 204 unmodified linesmodified:tests/test_reqctx.py+2 added-2 removed
108 unmodified lines109 110 def test_context_binding(app):111 @app.route("/")112 def index():113- return "Hello %s!" % flask.request.args["name"]113+ return f"Hello {flask.request.args['name']}!"114 115 @app.route("/meh")116 def meh():117 return flask.request.url19 unmodified lines137 138 def test_manual_context_binding(app):139 @app.route("/")140 def index():141- return "Hello %s!" % flask.request.args["name"]141+ return f"Hello {flask.request.args['name']}!"142 143 ctx = app.test_request_context("/?name=World")144 ctx.push()145 assert index() == "Hello World!"184 unmodified linesmodified:tests/test_templating.py+4 added-4 removed
412 unmodified lines413 class _TestHandler(logging.Handler):414 def handle(self, record):415 called.append(True)416 text = str(record.msg)417- assert '1: trying loader of application "blueprintapp"' in text417+ assert "1: trying loader of application 'blueprintapp'" in text418 assert (419- '2: trying loader of blueprint "admin" (blueprintapp.apps.admin)'419+ "2: trying loader of blueprint 'admin' (blueprintapp.apps.admin)"420 ) in text421 assert (422- '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 (426- '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+2 added-2 removed
57 unmodified lines58 return flask.request.remote_addr59 60 rv = client.get("/")61 assert rv.data == b"127.0.0.1"62- assert flask.g.user_agent == "werkzeug/" + werkzeug.__version__62+ assert flask.g.user_agent == f"werkzeug/{werkzeug.__version__}"63 64 65 def test_environ_base_modified(app, client, app_ctx):66 @app.route("/")253 unmodified lines320 @pytest.mark.skipif(blinker is None, reason="blinker is not installed")321 def test_client_json_no_app_context(app, client):322 @app.route("/hello", methods=["POST"])323 def hello():324- return "Hello, {}!".format(flask.request.json["name"])324+ return f"Hello, {flask.request.json['name']}!"325 326 class Namespace:327 count = 0328 105 unmodified linesmodified:tests/test_user_error_handler.py+3 added-3 removed
27 unmodified lines28 assert isinstance(e, InternalServerError)29 original = getattr(e, "original_exception", None)30 31 if original is not None:32- return "wrapped " + type(original).__name__32+ return f"wrapped {type(original).__name__}"33 34 return "direct"35 36 @app.route("/custom")200 unmodified lines237 def report_error(self, e):238 original = getattr(e, "original_exception", None)239 240 if original is not None:241- return "wrapped " + type(original).__name__241+ return f"wrapped {type(original).__name__}"242 243- return "direct " + type(e).__name__243+ return f"direct {type(e).__name__}"244 245 @pytest.mark.parametrize("to_handle", (InternalServerError, 500))246 def test_handle_class_or_code(self, app, client, to_handle):247 """``InternalServerError`` and ``500`` are aliases, they should41 unmodified lines