forked from orbit-oss/flask
f-strings everywhere
This commit is contained in:
parent
524fd0bc8c
commit
2ae740dd49
35 changed files with 227 additions and 245 deletions
12
docs/api.rst
12
docs/api.rst
|
|
@ -58,12 +58,12 @@ Incoming Request Data
|
|||
the following:
|
||||
|
||||
============= ======================================================
|
||||
`path` ``u'/π/page.html'``
|
||||
`full_path` ``u'/π/page.html?x=y'``
|
||||
`script_root` ``u'/myapplication'``
|
||||
`base_url` ``u'http://www.example.com/myapplication/π/page.html'``
|
||||
`url` ``u'http://www.example.com/myapplication/π/page.html?x=y'``
|
||||
`url_root` ``u'http://www.example.com/myapplication/'``
|
||||
`path` ``'/π/page.html'``
|
||||
`full_path` ``'/π/page.html?x=y'``
|
||||
`script_root` ``'/myapplication'``
|
||||
`base_url` ``'http://www.example.com/myapplication/π/page.html'``
|
||||
`url` ``'http://www.example.com/myapplication/π/page.html?x=y'``
|
||||
`url_root` ``'http://www.example.com/myapplication/'``
|
||||
============= ======================================================
|
||||
|
||||
|
||||
|
|
|
|||
|
|
@ -596,8 +596,8 @@ your configuration classes::
|
|||
DB_SERVER = '192.168.1.56'
|
||||
|
||||
@property
|
||||
def DATABASE_URI(self): # Note: all caps
|
||||
return 'mysql://user@{}/foo'.format(self.DB_SERVER)
|
||||
def DATABASE_URI(self): # Note: all caps
|
||||
return f"mysql://user@{self.DB_SERVER}/foo"
|
||||
|
||||
class ProductionConfig(Config):
|
||||
"""Uses production database server."""
|
||||
|
|
|
|||
|
|
@ -103,7 +103,7 @@ error messages could be displayed with a red background.
|
|||
To flash a message with a different category, just use the second argument
|
||||
to the :func:`~flask.flash` function::
|
||||
|
||||
flash(u'Invalid password provided', 'error')
|
||||
flash('Invalid password provided', 'error')
|
||||
|
||||
Inside the template you then have to tell the
|
||||
:func:`~flask.get_flashed_messages` function to also return the
|
||||
|
|
|
|||
|
|
@ -93,7 +93,7 @@ write this by having a function that calls into
|
|||
name and a dot, and by wrapping `view_func` in a `LazyView` as needed. ::
|
||||
|
||||
def url(import_name, url_rules=[], **options):
|
||||
view = LazyView('yourapplication.' + import_name)
|
||||
view = LazyView(f"yourapplication.{import_name}")
|
||||
for url_rule in url_rules:
|
||||
app.add_url_rule(url_rule, view_func=view, **options)
|
||||
|
||||
|
|
|
|||
|
|
@ -52,4 +52,4 @@ Example usage::
|
|||
files = request.files
|
||||
# At this point the hash is fully constructed.
|
||||
checksum = hash.hexdigest()
|
||||
return 'Hash was: %s' % checksum
|
||||
return f"Hash was: {checksum}"
|
||||
|
|
|
|||
|
|
@ -104,9 +104,9 @@ You can insert entries into the database like this:
|
|||
Querying is simple as well:
|
||||
|
||||
>>> User.query.all()
|
||||
[<User u'admin'>]
|
||||
[<User 'admin'>]
|
||||
>>> User.query.filter(User.name == 'admin').first()
|
||||
<User u'admin'>
|
||||
<User 'admin'>
|
||||
|
||||
.. _SQLAlchemy: https://www.sqlalchemy.org/
|
||||
.. _declarative:
|
||||
|
|
@ -200,19 +200,19 @@ SQLAlchemy will automatically commit for us.
|
|||
To query your database, you use the engine directly or use a connection:
|
||||
|
||||
>>> users.select(users.c.id == 1).execute().first()
|
||||
(1, u'admin', u'admin@localhost')
|
||||
(1, 'admin', 'admin@localhost')
|
||||
|
||||
These results are also dict-like tuples:
|
||||
|
||||
>>> r = users.select(users.c.id == 1).execute().first()
|
||||
>>> r['name']
|
||||
u'admin'
|
||||
'admin'
|
||||
|
||||
You can also pass strings of SQL statements to the
|
||||
:meth:`~sqlalchemy.engine.base.Connection.execute` method:
|
||||
|
||||
>>> engine.execute('select * from users where id = :1', [1]).first()
|
||||
(1, u'admin', u'admin@localhost')
|
||||
(1, 'admin', 'admin@localhost')
|
||||
|
||||
For more information about SQLAlchemy, head over to the
|
||||
`website <https://www.sqlalchemy.org/>`_.
|
||||
|
|
|
|||
|
|
@ -21,7 +21,7 @@ data and to then invoke that function and pass it to a response object::
|
|||
def generate_large_csv():
|
||||
def generate():
|
||||
for row in iter_all_rows():
|
||||
yield ','.join(row) + '\n'
|
||||
yield f"{','.join(row)}\n"
|
||||
return Response(generate(), mimetype='text/csv')
|
||||
|
||||
Each ``yield`` expression is directly sent to the browser. Note though
|
||||
|
|
|
|||
|
|
@ -142,8 +142,7 @@ Here is the code for that decorator::
|
|||
def decorated_function(*args, **kwargs):
|
||||
template_name = template
|
||||
if template_name is None:
|
||||
template_name = request.endpoint \
|
||||
.replace('.', '/') + '.html'
|
||||
template_name = f"'{request.endpoint.replace('.', '/')}.html'"
|
||||
ctx = f(*args, **kwargs)
|
||||
if ctx is None:
|
||||
ctx = {}
|
||||
|
|
|
|||
|
|
@ -447,11 +447,11 @@ Here is a basic introduction to how the :class:`~markupsafe.Markup` class works:
|
|||
|
||||
>>> from markupsafe import Markup
|
||||
>>> Markup('<strong>Hello %s!</strong>') % '<blink>hacker</blink>'
|
||||
Markup(u'<strong>Hello <blink>hacker</blink>!</strong>')
|
||||
Markup('<strong>Hello <blink>hacker</blink>!</strong>')
|
||||
>>> Markup.escape('<blink>hacker</blink>')
|
||||
Markup(u'<blink>hacker</blink>')
|
||||
Markup('<blink>hacker</blink>')
|
||||
>>> Markup('<em>Marked up</em> » HTML').striptags()
|
||||
u'Marked up \xbb HTML'
|
||||
'Marked up \xbb HTML'
|
||||
|
||||
.. versionchanged:: 0.5
|
||||
|
||||
|
|
@ -609,8 +609,8 @@ Werkzeug provides for you::
|
|||
@app.route('/upload', methods=['GET', 'POST'])
|
||||
def upload_file():
|
||||
if request.method == 'POST':
|
||||
f = request.files['the_file']
|
||||
f.save('/var/www/uploads/' + secure_filename(f.filename))
|
||||
file = request.files['the_file']
|
||||
file.save(f"/var/www/uploads/{secure_filename(f.filename)}")
|
||||
...
|
||||
|
||||
For some better examples, checkout the :ref:`uploading-files` pattern.
|
||||
|
|
|
|||
|
|
@ -222,8 +222,8 @@ functions)::
|
|||
|
||||
@app.context_processor
|
||||
def utility_processor():
|
||||
def format_price(amount, currency=u'€'):
|
||||
return u'{0:.2f}{1}'.format(amount, currency)
|
||||
def format_price(amount, currency="€"):
|
||||
return f"{amount:.2f}{currency}"
|
||||
return dict(format_price=format_price)
|
||||
|
||||
The context processor above makes the `format_price` function available to all
|
||||
|
|
|
|||
|
|
@ -165,16 +165,19 @@ invalid credentials. Add this new test function::
|
|||
def test_login_logout(client):
|
||||
"""Make sure login and logout works."""
|
||||
|
||||
rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'])
|
||||
username = flaskr.app.config["USERNAME"]
|
||||
password = flaskr.app.config["PASSWORD"]
|
||||
|
||||
rv = login(client, username, password)
|
||||
assert b'You were logged in' in rv.data
|
||||
|
||||
rv = logout(client)
|
||||
assert b'You were logged out' in rv.data
|
||||
|
||||
rv = login(client, flaskr.app.config['USERNAME'] + 'x', flaskr.app.config['PASSWORD'])
|
||||
rv = login(client, f"{username}x", password)
|
||||
assert b'Invalid username' in rv.data
|
||||
|
||||
rv = login(client, flaskr.app.config['USERNAME'], flaskr.app.config['PASSWORD'] + 'x')
|
||||
rv = login(client, username, f'{password}x')
|
||||
assert b'Invalid password' in rv.data
|
||||
|
||||
Test Adding Messages
|
||||
|
|
|
|||
|
|
@ -207,7 +207,7 @@ it from each view.
|
|||
).fetchone()
|
||||
|
||||
if post is None:
|
||||
abort(404, "Post id {0} doesn't exist.".format(id))
|
||||
abort(404, f"Post id {id} doesn't exist.")
|
||||
|
||||
if check_author and post['author_id'] != g.user['id']:
|
||||
abort(403)
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ write templates to generate the HTML form.
|
|||
elif db.execute(
|
||||
'SELECT id FROM user WHERE username = ?', (username,)
|
||||
).fetchone() is not None:
|
||||
error = 'User {} is already registered.'.format(username)
|
||||
error = f"User {username} is already registered."
|
||||
|
||||
if error is None:
|
||||
db.execute(
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue