Skip to content

Commit 5e04b22

Browse files
authored
Merge pull request #1646 from UlrichB22/f_strings
Use f-strings for logging messages and more.
2 parents cbfeb83 + 37a377b commit 5e04b22

File tree

31 files changed

+272
-287
lines changed

31 files changed

+272
-287
lines changed

src/moin/apps/feed/views.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -57,9 +57,9 @@ def atom(item_name):
5757
cid = None
5858
if content is None:
5959
if not item_name:
60-
title = "{0}".format(app.cfg.sitename)
60+
title = f"{app.cfg.sitename}"
6161
else:
62-
title = "{0} - {1}".format(app.cfg.sitename, fqname)
62+
title = f"{app.cfg.sitename} - {fqname}"
6363
feed = FeedGenerator()
6464
feed.id(request.url)
6565
feed.title(title)
@@ -88,7 +88,7 @@ def atom(item_name):
8888
content = render_template('atom.html', get='first_revision', rev=this_rev,
8989
content=Markup(hl_item.content._render_data()), revision=this_revid)
9090
except Exception:
91-
logging.exception("content rendering crashed on item {0}".format(name))
91+
logging.exception(f"content rendering crashed on item {name}")
9292
content = _('MoinMoin feels unhappy.')
9393
author = get_editor_info(rev.meta, external=True)
9494
rev_comment = rev.meta.get(COMMENT, '')
@@ -97,12 +97,12 @@ def atom(item_name):
9797
if len(rev_comment) > 80:
9898
content = render_template('atom.html', get='comment_cont_merge', comment=rev_comment[79:],
9999
content=Markup(content))
100-
rev_comment = "{0}...".format(rev_comment[:79])
101-
feed_title = "{0} - {1}".format(author.get(NAME, ''), rev_comment)
100+
rev_comment = f"{rev_comment[:79]}..."
101+
feed_title = f"{author.get(NAME, '')} - {rev_comment}"
102102
else:
103-
feed_title = "{0}".format(author.get(NAME, ''))
103+
feed_title = f"{author.get(NAME, '')}"
104104
if not item_name:
105-
feed_title = "{0} - {1}".format(name, feed_title)
105+
feed_title = f"{name} - {feed_title}"
106106
feed_entry = feed.add_entry()
107107
feed_entry.id(url_for_item(name, rev=this_revid, _external=True))
108108
feed_entry.title(feed_title)

src/moin/apps/frontend/views.py

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -509,8 +509,8 @@ def add_presenter(wrapped, view, add_trail=False, abort404=True):
509509
:param add_trail: whether to call flaskg.user.add_trail
510510
:param abort404: whether to abort(404) for nonexistent items
511511
"""
512-
@frontend.route('/+{view}/+<rev>/<itemname:item_name>'.format(view=view))
513-
@frontend.route('/+{view}/<itemname:item_name>'.format(view=view), defaults=dict(rev=CURRENT))
512+
@frontend.route(f'/+{view}/+<rev>/<itemname:item_name>')
513+
@frontend.route(f'/+{view}/<itemname:item_name>', defaults=dict(rev=CURRENT))
514514
@wraps(wrapped)
515515
def wrapper(item_name, rev):
516516
if add_trail:
@@ -1142,7 +1142,7 @@ def log_destroy_action(item, subitem_names, comment, revision=None):
11421142
elif subitem_names:
11431143
destroy_info[0] = ('An item and all item subitems have been destroyed', '')
11441144
for name, val in destroy_info:
1145-
logging.info('{0}: {1}'.format(name, val))
1145+
logging.info(f'{name}: {val}')
11461146

11471147

11481148
@frontend.route('/+destroy/+<rev>/<itemname:item_name>', methods=['GET', 'POST'])
@@ -2577,7 +2577,7 @@ def _common_type(ct1, ct2):
25772577
def _crash(item, oldrev, newrev):
25782578
"""This is called from several places, need to handle passed message"""
25792579
error_id = uuid.uuid4()
2580-
logging.exception("An exception happened in _render_data (error_id = %s ):" % error_id)
2580+
logging.exception(f"An exception happened in _render_data (error_id = {error_id} ):")
25812581
return render_template("crash_view.html",
25822582
server_time=time.strftime("%Y-%m-%d %H:%M:%S %Z"),
25832583
url=request.url,
@@ -2795,7 +2795,7 @@ def global_tags(namespace):
27952795
tags_counts = {}
27962796
for meta in metas:
27972797
tags = meta.get(TAGS, [])
2798-
logging.debug("name {0!r} rev {1} tags {2!r}".format(meta[NAME], meta[REVID], tags))
2798+
logging.debug(f"name {meta[NAME]!r} rev {meta[REVID]} tags {tags!r}")
27992799
for tag in tags:
28002800
tags_counts[tag] = tags_counts.setdefault(tag, 0) + 1
28012801
tags_counts = sorted(tags_counts.items())
@@ -2813,7 +2813,7 @@ def global_tags(namespace):
28132813
def cls(count):
28142814
# return the css class for this tag
28152815
weight = scale * (count - count_min)
2816-
return "weight{0}".format(int(weight)) # weight0, ..., weight9
2816+
return f"weight{int(weight)}" # weight0, ..., weight9
28172817
tags = [(cls(count), tag) for tag, count in tags_counts]
28182818
else:
28192819
tags = []

src/moin/auth/__init__.py

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -166,7 +166,7 @@ def get_multistage_continuation_url(auth_name, extra_fields={}):
166166

167167
# the url should be absolute so we use _external
168168
url = url_for('frontend.login', login_submit='1', stage=auth_name, _external=True, **extra_fields)
169-
logging.debug("multistage_continuation_url: {0}".format(url))
169+
logging.debug(f"multistage_continuation_url: {url}")
170170
return url
171171

172172

@@ -216,7 +216,7 @@ class BaseAuth:
216216
def __init__(self, trusted=False, **kw):
217217
self.trusted = trusted
218218
if kw:
219-
raise TypeError("got unexpected arguments %r" % kw)
219+
raise TypeError(f"got unexpected arguments {kw!r}")
220220

221221
def login(self, user_obj, **kw):
222222
return ContinueLogin(user_obj)
@@ -226,7 +226,7 @@ def request(self, user_obj, **kw):
226226

227227
def logout(self, user_obj, **kw):
228228
if self.name and user_obj and user_obj.auth_method == self.name:
229-
logging.debug("{0}: logout - invalidating user {1!r}".format(self.name, user_obj.name))
229+
logging.debug(f"{self.name}: logout - invalidating user {user_obj.name!r}")
230230
user_obj.valid = False
231231
return user_obj, True
232232

@@ -254,17 +254,17 @@ def login(self, user_obj, **kw):
254254
if not username and not password:
255255
return ContinueLogin(user_obj)
256256

257-
logging.debug("{0}: performing login action".format(self.name))
257+
logging.debug(f"{self.name}: performing login action")
258258

259259
if username and not password:
260260
return ContinueLogin(user_obj, _('Missing password. Please enter user name and password.'))
261261

262262
u = user.User(name=username, password=password, auth_method=self.name, trusted=self.trusted)
263263
if u.valid:
264-
logging.debug("{0}: successfully authenticated user {1!r} (valid)".format(self.name, u.name))
264+
logging.debug(f"{self.name}: successfully authenticated user {u.name!r} (valid)")
265265
return ContinueLogin(u)
266266
else:
267-
logging.debug("{0}: could not authenticate user {1!r} (not valid)".format(self.name, username))
267+
logging.debug(f"{self.name}: could not authenticate user {username!r} (not valid)")
268268
return ContinueLogin(user_obj, _("Invalid username or password."))
269269

270270
def login_hint(self):
@@ -356,23 +356,23 @@ def request(self, user_obj, **kw):
356356
else:
357357
auth_username = request.environ.get(self.env_var)
358358

359-
logging.debug("auth_username = {0!r}".format(auth_username))
359+
logging.debug(f"auth_username = {auth_username!r}")
360360
if auth_username:
361361
auth_username = self.decode_username(auth_username)
362362
auth_username = self.transform_username(auth_username)
363-
logging.debug("auth_username (after decode/transform) = {0!r}".format(auth_username))
363+
logging.debug(f"auth_username (after decode/transform) = {auth_username!r}")
364364
u = user.User(auth_username=auth_username,
365365
auth_method=self.name, auth_attribs=('name', 'password'), trusted=self.trusted)
366366

367-
logging.debug("u: {0!r}".format(u))
367+
logging.debug(f"u: {u!r}")
368368
if u and self.autocreate:
369369
logging.debug("autocreating user")
370370
u.create_or_update()
371371
if u and u.valid:
372-
logging.debug("returning valid user {0!r}".format(u))
372+
logging.debug(f"returning valid user {u!r}")
373373
return u, True # True to get other methods called, too
374374
else:
375-
logging.debug("returning {0!r}".format(user_obj))
375+
logging.debug(f"returning {user_obj!r}")
376376
return user_obj, True
377377

378378

@@ -455,8 +455,8 @@ def setup_from_session():
455455
auth_method = session['user.auth_method']
456456
auth_attribs = session['user.auth_attribs']
457457
session_token = session['user.session_token']
458-
logging.debug("got from session: {0!r} {1!r} {2!r} {3!r}".format(itemid, trusted, auth_method, auth_attribs))
459-
logging.debug("current auth methods: {0!r}".format(app.cfg.auth_methods))
458+
logging.debug(f"got from session: {itemid!r} {trusted!r} {auth_method!r} {auth_attribs!r}")
459+
logging.debug(f"current auth methods: {app.cfg.auth_methods!r}")
460460
if auth_method and auth_method in app.cfg.auth_methods:
461461
userobj = user.User(itemid,
462462
auth_method=auth_method,
@@ -468,5 +468,5 @@ def setup_from_session():
468468
userobj.logout_session(False)
469469
# We didn't find user in session data.
470470
userobj = None
471-
logging.debug("session started for user {0!r}".format(userobj))
471+
logging.debug(f"session started for user {userobj!r}")
472472
return userobj

src/moin/auth/http.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -48,26 +48,25 @@ def request(self, user_obj, **kw):
4848

4949
auth = request.authorization
5050
if auth and auth.username and auth.password is not None:
51-
logging.debug("http basic auth, received username: {0!r} password: {1!r}".format(
52-
auth.username, auth.password))
51+
logging.debug(f"http basic auth, received username: {auth.username!r} password: {auth.password!r}")
5352
u = user.User(name=auth.username, password=auth.password,
5453
auth_method=self.name, auth_attribs=[], trusted=self.trusted)
55-
logging.debug("user: {0!r}".format(u))
54+
logging.debug(f"user: {u!r}")
5655

5756
if not u or not u.valid:
5857
from werkzeug import Response
5958
from werkzeug.exceptions import abort
6059
response = Response(_('Please log in first.'), 401,
61-
{'WWW-Authenticate': 'Basic realm="{0}"'.format(self.realm)})
60+
{'WWW-Authenticate': f'Basic realm="{self.realm}"'})
6261
abort(response)
6362

64-
logging.debug("u: {0!r}".format(u))
63+
logging.debug(f"u: {u!r}")
6564
if u and self.autocreate:
6665
logging.debug("autocreating user")
6766
u.create_or_update()
6867
if u and u.valid:
69-
logging.debug("returning valid user {0!r}".format(u))
68+
logging.debug(f"returning valid user {u!r}")
7069
return u, True # True to get other methods called, too
7170
else:
72-
logging.debug("returning {0!r}".format(user_obj))
71+
logging.debug(f"returning {user_obj!r}")
7372
return user_obj, True

src/moin/auth/ldap_login.py

Lines changed: 18 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@
2929
try:
3030
import ldap
3131
except ImportError as err:
32-
logging.error("You need to have python-ldap installed ({0!s}).".format(err))
32+
logging.error(f"You need to have python-ldap installed ({err!s}).")
3333
raise
3434

3535

@@ -157,28 +157,28 @@ def login(self, user_obj, **kw):
157157
if value is not None:
158158
ldap.set_option(option, value)
159159

160-
logging.debug("Trying to initialize {0!r}.".format(server))
160+
logging.debug(f"Trying to initialize {server!r}.")
161161
conn = ldap.initialize(server)
162-
logging.debug("Connected to LDAP server {0!r}.".format(server))
162+
logging.debug(f"Connected to LDAP server {server!r}.")
163163

164164
if self.start_tls and server.startswith('ldap:'):
165-
logging.debug("Trying to start TLS to {0!r}.".format(server))
165+
logging.debug(f"Trying to start TLS to {server!r}.")
166166
try:
167167
conn.start_tls_s()
168-
logging.debug("Using TLS to {0!r}.".format(server))
168+
logging.debug(f"Using TLS to {server!r}.")
169169
except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR) as err:
170-
logging.warning("Couldn't establish TLS to {0!r} (err: {1!s}).".format(server, err))
170+
logging.warning(f"Couldn't establish TLS to {server!r} (err: {err!s}).")
171171
raise
172172

173173
# you can use %(username)s and %(password)s here to get the stuff entered in the form:
174174
binddn = self.bind_dn % locals()
175175
bindpw = self.bind_pw % locals()
176176
conn.simple_bind_s(binddn, bindpw)
177-
logging.debug("Bound with binddn {0!r}".format(binddn))
177+
logging.debug(f"Bound with binddn {binddn!r}")
178178

179179
# you can use %(username)s here to get the stuff entered in the form:
180180
filterstr = self.search_filter % locals()
181-
logging.debug("Searching {0!r}".format(filterstr))
181+
logging.debug(f"Searching {filterstr!r}")
182182
attrs = [getattr(self, attr) for attr in [
183183
'email_attribute',
184184
'displayname_attribute',
@@ -190,27 +190,26 @@ def login(self, user_obj, **kw):
190190
# we remove entries with dn == None to get the real result list:
191191
lusers = [(_dn, _ldap_dict) for _dn, _ldap_dict in lusers if _dn is not None]
192192
for _dn, _ldap_dict in lusers:
193-
logging.debug("dn:{0!r}".format(_dn))
193+
logging.debug(f"dn:{_dn!r}")
194194
for key, val in _ldap_dict.items():
195-
logging.debug(" {0!r}: {1!r}".format(key, val))
195+
logging.debug(f" {key!r}: {val!r}")
196196

197197
result_length = len(lusers)
198198
if result_length != 1:
199199
if result_length > 1:
200-
logging.warning("Search found more than one ({0}) matches for {1!r}.".format(
201-
result_length, filterstr))
200+
logging.warning(f"Search found more than one ({result_length}) matches for {filterstr!r}.")
202201
if result_length == 0:
203-
logging.debug("Search found no matches for {0!r}.".format(filterstr, ))
202+
logging.debug(f"Search found no matches for {filterstr!r}.")
204203
if self.report_invalid_credentials:
205204
return ContinueLogin(user_obj, _("Invalid username or password."))
206205
else:
207206
return ContinueLogin(user_obj)
208207

209208
dn, ldap_dict = lusers[0]
210209
if not self.bind_once:
211-
logging.debug("DN found is {0!r}, trying to bind with pw".format(dn))
210+
logging.debug(f"DN found is {dn!r}, trying to bind with pw")
212211
conn.simple_bind_s(dn, password)
213-
logging.debug("Bound with dn {0!r} (username: {1!r})".format(dn, username))
212+
logging.debug(f"Bound with dn {dn!r} (username: {username!r})")
214213

215214
if self.email_callback is None:
216215
if self.email_attribute:
@@ -229,7 +228,7 @@ def login(self, user_obj, **kw):
229228
sn = ldap_dict.get(self.surname_attribute, [''])[0]
230229
gn = ldap_dict.get(self.givenname_attribute, [''])[0]
231230
if sn and gn:
232-
display_name = "{0}, {1}".format(sn, gn)
231+
display_name = f"{sn}, {gn}"
233232
elif sn:
234233
display_name = sn
235234

@@ -251,12 +250,11 @@ def login(self, user_obj, **kw):
251250
username, email, display_name))
252251

253252
except ldap.INVALID_CREDENTIALS:
254-
logging.debug("invalid credentials (wrong password?) for dn {0!r} (username: {1!r})".format(
255-
dn, username))
253+
logging.debug(f"invalid credentials (wrong password?) for dn {dn!r} (username: {username!r})")
256254
return CancelLogin(_("Invalid username or password."))
257255

258256
if u and self.autocreate:
259-
logging.debug("calling create_or_update to autocreate user {0!r}".format(u.name))
257+
logging.debug(f"calling create_or_update to autocreate user {u.name!r}")
260258
u.create_or_update(True)
261259
return ContinueLogin(u)
262260

@@ -265,8 +263,7 @@ def login(self, user_obj, **kw):
265263
# authenticator object in cfg.auth list (there could be some second
266264
# ldap authenticator that queries a backup server or any other auth
267265
# method).
268-
logging.error("LDAP server {0} failed ({1!s}). "
269-
"Trying to authenticate with next auth list entry.".format(server, err))
266+
logging.error(f"LDAP server {server} failed ({err!s}). Trying to authenticate with next auth list entry.")
270267
return ContinueLogin(user_obj, _("LDAP server {server} failed.").format(server=server))
271268

272269
except: # noqa

src/moin/auth/log.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ def __init__(self, **kw):
2323
super(AuthLog, self).__init__(**kw)
2424

2525
def log(self, action, user_obj, kw):
26-
logging.info('{0}: user_obj={1!r} kw={2!r}'.format(action, user_obj, kw))
26+
logging.info(f'{action}: user_obj={user_obj!r} kw={kw!r}')
2727

2828
def login(self, user_obj, **kw):
2929
self.log('login', user_obj, kw)

src/moin/auth/smb_mount.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def __init__(
5151
self.coding = coding
5252

5353
def do_smb(self, username, password, login):
54-
logging.debug("login={0} logout={1}: got name={2!r}".format(login, not login, username))
54+
logging.debug(f"login={login} logout={not login}: got name={username!r}")
5555

5656
import os
5757
import pwd

src/moin/cli/maint/index.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ def IndexDestroy(tmp):
7878
@click.option('--storage-create', '-s', is_flag=True, required=False, default=False)
7979
def IndexBuild(tmp, procs, limitmb, **kwargs):
8080
if not wiki_index_exists():
81-
logging.error("{} Run 'moin index-create' first.".format(ERR_NO_INDEX))
81+
logging.error(f"{ERR_NO_INDEX} Run 'moin index-create' first.")
8282
raise SystemExit(1)
8383
logging.info("Index build started")
8484
flaskg.add_lineno_attr = False # no need to add lineno attributes while building indexes
@@ -131,7 +131,7 @@ def IndexDump(tmp, truncate):
131131
raise SystemExit(1)
132132
logging.info("Index dump started")
133133
for idx_name in [LATEST_REVS, ALL_REVS]:
134-
print(" {0} {1} {2}".format("-" * 10, idx_name, "-" * 60))
134+
print(f" {'-' * 10} {idx_name} {'-' * 60}")
135135
for kvs in app.storage.dump(tmp=tmp, idx_name=idx_name):
136136
for k, v in kvs:
137137
v = repr(v)

0 commit comments

Comments
 (0)