Skip to content

Commit

Permalink
Use f-strings for logging messages and more.
Browse files Browse the repository at this point in the history
  • Loading branch information
UlrichB22 committed Mar 12, 2024
1 parent cbfeb83 commit 37a377b
Show file tree
Hide file tree
Showing 31 changed files with 272 additions and 287 deletions.
14 changes: 7 additions & 7 deletions src/moin/apps/feed/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,9 +57,9 @@ def atom(item_name):
cid = None
if content is None:
if not item_name:
title = "{0}".format(app.cfg.sitename)
title = f"{app.cfg.sitename}"
else:
title = "{0} - {1}".format(app.cfg.sitename, fqname)
title = f"{app.cfg.sitename} - {fqname}"
feed = FeedGenerator()
feed.id(request.url)
feed.title(title)
Expand Down Expand Up @@ -88,7 +88,7 @@ def atom(item_name):
content = render_template('atom.html', get='first_revision', rev=this_rev,
content=Markup(hl_item.content._render_data()), revision=this_revid)
except Exception:
logging.exception("content rendering crashed on item {0}".format(name))
logging.exception(f"content rendering crashed on item {name}")
content = _('MoinMoin feels unhappy.')
author = get_editor_info(rev.meta, external=True)
rev_comment = rev.meta.get(COMMENT, '')
Expand All @@ -97,12 +97,12 @@ def atom(item_name):
if len(rev_comment) > 80:
content = render_template('atom.html', get='comment_cont_merge', comment=rev_comment[79:],
content=Markup(content))
rev_comment = "{0}...".format(rev_comment[:79])
feed_title = "{0} - {1}".format(author.get(NAME, ''), rev_comment)
rev_comment = f"{rev_comment[:79]}..."
feed_title = f"{author.get(NAME, '')} - {rev_comment}"
else:
feed_title = "{0}".format(author.get(NAME, ''))
feed_title = f"{author.get(NAME, '')}"
if not item_name:
feed_title = "{0} - {1}".format(name, feed_title)
feed_title = f"{name} - {feed_title}"
feed_entry = feed.add_entry()
feed_entry.id(url_for_item(name, rev=this_revid, _external=True))
feed_entry.title(feed_title)
Expand Down
12 changes: 6 additions & 6 deletions src/moin/apps/frontend/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,8 +509,8 @@ def add_presenter(wrapped, view, add_trail=False, abort404=True):
:param add_trail: whether to call flaskg.user.add_trail
:param abort404: whether to abort(404) for nonexistent items
"""
@frontend.route('/+{view}/+<rev>/<itemname:item_name>'.format(view=view))
@frontend.route('/+{view}/<itemname:item_name>'.format(view=view), defaults=dict(rev=CURRENT))
@frontend.route(f'/+{view}/+<rev>/<itemname:item_name>')
@frontend.route(f'/+{view}/<itemname:item_name>', defaults=dict(rev=CURRENT))
@wraps(wrapped)
def wrapper(item_name, rev):
if add_trail:
Expand Down Expand Up @@ -1142,7 +1142,7 @@ def log_destroy_action(item, subitem_names, comment, revision=None):
elif subitem_names:
destroy_info[0] = ('An item and all item subitems have been destroyed', '')
for name, val in destroy_info:
logging.info('{0}: {1}'.format(name, val))
logging.info(f'{name}: {val}')


@frontend.route('/+destroy/+<rev>/<itemname:item_name>', methods=['GET', 'POST'])
Expand Down Expand Up @@ -2577,7 +2577,7 @@ def _common_type(ct1, ct2):
def _crash(item, oldrev, newrev):
"""This is called from several places, need to handle passed message"""
error_id = uuid.uuid4()
logging.exception("An exception happened in _render_data (error_id = %s ):" % error_id)
logging.exception(f"An exception happened in _render_data (error_id = {error_id} ):")
return render_template("crash_view.html",
server_time=time.strftime("%Y-%m-%d %H:%M:%S %Z"),
url=request.url,
Expand Down Expand Up @@ -2795,7 +2795,7 @@ def global_tags(namespace):
tags_counts = {}
for meta in metas:
tags = meta.get(TAGS, [])
logging.debug("name {0!r} rev {1} tags {2!r}".format(meta[NAME], meta[REVID], tags))
logging.debug(f"name {meta[NAME]!r} rev {meta[REVID]} tags {tags!r}")
for tag in tags:
tags_counts[tag] = tags_counts.setdefault(tag, 0) + 1
tags_counts = sorted(tags_counts.items())
Expand All @@ -2813,7 +2813,7 @@ def global_tags(namespace):
def cls(count):
# return the css class for this tag
weight = scale * (count - count_min)
return "weight{0}".format(int(weight)) # weight0, ..., weight9
return f"weight{int(weight)}" # weight0, ..., weight9
tags = [(cls(count), tag) for tag, count in tags_counts]
else:
tags = []
Expand Down
28 changes: 14 additions & 14 deletions src/moin/auth/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def get_multistage_continuation_url(auth_name, extra_fields={}):

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


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

def login(self, user_obj, **kw):
return ContinueLogin(user_obj)
Expand All @@ -226,7 +226,7 @@ def request(self, user_obj, **kw):

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

Expand Down Expand Up @@ -254,17 +254,17 @@ def login(self, user_obj, **kw):
if not username and not password:
return ContinueLogin(user_obj)

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

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

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

def login_hint(self):
Expand Down Expand Up @@ -356,23 +356,23 @@ def request(self, user_obj, **kw):
else:
auth_username = request.environ.get(self.env_var)

logging.debug("auth_username = {0!r}".format(auth_username))
logging.debug(f"auth_username = {auth_username!r}")
if auth_username:
auth_username = self.decode_username(auth_username)
auth_username = self.transform_username(auth_username)
logging.debug("auth_username (after decode/transform) = {0!r}".format(auth_username))
logging.debug(f"auth_username (after decode/transform) = {auth_username!r}")
u = user.User(auth_username=auth_username,
auth_method=self.name, auth_attribs=('name', 'password'), trusted=self.trusted)

logging.debug("u: {0!r}".format(u))
logging.debug(f"u: {u!r}")
if u and self.autocreate:
logging.debug("autocreating user")
u.create_or_update()
if u and u.valid:
logging.debug("returning valid user {0!r}".format(u))
logging.debug(f"returning valid user {u!r}")
return u, True # True to get other methods called, too
else:
logging.debug("returning {0!r}".format(user_obj))
logging.debug(f"returning {user_obj!r}")
return user_obj, True


Expand Down Expand Up @@ -455,8 +455,8 @@ def setup_from_session():
auth_method = session['user.auth_method']
auth_attribs = session['user.auth_attribs']
session_token = session['user.session_token']
logging.debug("got from session: {0!r} {1!r} {2!r} {3!r}".format(itemid, trusted, auth_method, auth_attribs))
logging.debug("current auth methods: {0!r}".format(app.cfg.auth_methods))
logging.debug(f"got from session: {itemid!r} {trusted!r} {auth_method!r} {auth_attribs!r}")
logging.debug(f"current auth methods: {app.cfg.auth_methods!r}")
if auth_method and auth_method in app.cfg.auth_methods:
userobj = user.User(itemid,
auth_method=auth_method,
Expand All @@ -468,5 +468,5 @@ def setup_from_session():
userobj.logout_session(False)
# We didn't find user in session data.
userobj = None
logging.debug("session started for user {0!r}".format(userobj))
logging.debug(f"session started for user {userobj!r}")
return userobj
13 changes: 6 additions & 7 deletions src/moin/auth/http.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,26 +48,25 @@ def request(self, user_obj, **kw):

auth = request.authorization
if auth and auth.username and auth.password is not None:
logging.debug("http basic auth, received username: {0!r} password: {1!r}".format(
auth.username, auth.password))
logging.debug(f"http basic auth, received username: {auth.username!r} password: {auth.password!r}")
u = user.User(name=auth.username, password=auth.password,
auth_method=self.name, auth_attribs=[], trusted=self.trusted)
logging.debug("user: {0!r}".format(u))
logging.debug(f"user: {u!r}")

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

logging.debug("u: {0!r}".format(u))
logging.debug(f"u: {u!r}")
if u and self.autocreate:
logging.debug("autocreating user")
u.create_or_update()
if u and u.valid:
logging.debug("returning valid user {0!r}".format(u))
logging.debug(f"returning valid user {u!r}")
return u, True # True to get other methods called, too
else:
logging.debug("returning {0!r}".format(user_obj))
logging.debug(f"returning {user_obj!r}")
return user_obj, True
39 changes: 18 additions & 21 deletions src/moin/auth/ldap_login.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
try:
import ldap
except ImportError as err:
logging.error("You need to have python-ldap installed ({0!s}).".format(err))
logging.error(f"You need to have python-ldap installed ({err!s}).")
raise


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

logging.debug("Trying to initialize {0!r}.".format(server))
logging.debug(f"Trying to initialize {server!r}.")
conn = ldap.initialize(server)
logging.debug("Connected to LDAP server {0!r}.".format(server))
logging.debug(f"Connected to LDAP server {server!r}.")

if self.start_tls and server.startswith('ldap:'):
logging.debug("Trying to start TLS to {0!r}.".format(server))
logging.debug(f"Trying to start TLS to {server!r}.")
try:
conn.start_tls_s()
logging.debug("Using TLS to {0!r}.".format(server))
logging.debug(f"Using TLS to {server!r}.")
except (ldap.SERVER_DOWN, ldap.CONNECT_ERROR) as err:
logging.warning("Couldn't establish TLS to {0!r} (err: {1!s}).".format(server, err))
logging.warning(f"Couldn't establish TLS to {server!r} (err: {err!s}).")
raise

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

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

result_length = len(lusers)
if result_length != 1:
if result_length > 1:
logging.warning("Search found more than one ({0}) matches for {1!r}.".format(
result_length, filterstr))
logging.warning(f"Search found more than one ({result_length}) matches for {filterstr!r}.")
if result_length == 0:
logging.debug("Search found no matches for {0!r}.".format(filterstr, ))
logging.debug(f"Search found no matches for {filterstr!r}.")
if self.report_invalid_credentials:
return ContinueLogin(user_obj, _("Invalid username or password."))
else:
return ContinueLogin(user_obj)

dn, ldap_dict = lusers[0]
if not self.bind_once:
logging.debug("DN found is {0!r}, trying to bind with pw".format(dn))
logging.debug(f"DN found is {dn!r}, trying to bind with pw")
conn.simple_bind_s(dn, password)
logging.debug("Bound with dn {0!r} (username: {1!r})".format(dn, username))
logging.debug(f"Bound with dn {dn!r} (username: {username!r})")

if self.email_callback is None:
if self.email_attribute:
Expand All @@ -229,7 +228,7 @@ def login(self, user_obj, **kw):
sn = ldap_dict.get(self.surname_attribute, [''])[0]
gn = ldap_dict.get(self.givenname_attribute, [''])[0]
if sn and gn:
display_name = "{0}, {1}".format(sn, gn)
display_name = f"{sn}, {gn}"
elif sn:
display_name = sn

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

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

if u and self.autocreate:
logging.debug("calling create_or_update to autocreate user {0!r}".format(u.name))
logging.debug(f"calling create_or_update to autocreate user {u.name!r}")
u.create_or_update(True)
return ContinueLogin(u)

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

except: # noqa
Expand Down
2 changes: 1 addition & 1 deletion src/moin/auth/log.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ def __init__(self, **kw):
super(AuthLog, self).__init__(**kw)

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

def login(self, user_obj, **kw):
self.log('login', user_obj, kw)
Expand Down
2 changes: 1 addition & 1 deletion src/moin/auth/smb_mount.py
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ def __init__(
self.coding = coding

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

import os
import pwd
Expand Down
4 changes: 2 additions & 2 deletions src/moin/cli/maint/index.py
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ def IndexDestroy(tmp):
@click.option('--storage-create', '-s', is_flag=True, required=False, default=False)
def IndexBuild(tmp, procs, limitmb, **kwargs):
if not wiki_index_exists():
logging.error("{} Run 'moin index-create' first.".format(ERR_NO_INDEX))
logging.error(f"{ERR_NO_INDEX} Run 'moin index-create' first.")
raise SystemExit(1)
logging.info("Index build started")
flaskg.add_lineno_attr = False # no need to add lineno attributes while building indexes
Expand Down Expand Up @@ -131,7 +131,7 @@ def IndexDump(tmp, truncate):
raise SystemExit(1)
logging.info("Index dump started")
for idx_name in [LATEST_REVS, ALL_REVS]:
print(" {0} {1} {2}".format("-" * 10, idx_name, "-" * 60))
print(f" {'-' * 10} {idx_name} {'-' * 60}")
for kvs in app.storage.dump(tmp=tmp, idx_name=idx_name):
for k, v in kvs:
v = repr(v)
Expand Down
Loading

0 comments on commit 37a377b

Please sign in to comment.