Skip to content

Commit c79a25c

Browse files
committed
start UP031 by fixing simple %s strings
1 parent 5594cda commit c79a25c

File tree

15 files changed

+51
-59
lines changed

15 files changed

+51
-59
lines changed

openlibrary/accounts/__init__.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ def get_group(name):
1616
"""
1717
Returns the group named 'name'.
1818
"""
19-
return web.ctx.site.get("/usergroup/%s" % name)
19+
return web.ctx.site.get(f"/usergroup/{name}")
2020

2121

2222
class RunAs:

openlibrary/accounts/model.py

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ def generate_uuid():
102102

103103
def send_verification_email(username, email):
104104
"""Sends account verification email."""
105-
key = "account/%s/verify" % username
105+
key = f"account/{username}/verify"
106106

107107
doc = create_link_doc(key, username, email)
108108
web.ctx.site.store[key] = doc
@@ -288,14 +288,14 @@ def get_creation_info(self):
288288
return doc.get_creation_info()
289289

290290
def get_activation_link(self):
291-
key = "account/%s/verify" % self.username
291+
key = f"account/{self.username}/verify"
292292
if doc := web.ctx.site.store.get(key):
293293
return Link(doc)
294294
else:
295295
return False
296296

297297
def get_password_reset_link(self):
298-
key = "account/%s/password" % self.username
298+
key = f"account/{self.username}/password"
299299
if doc := web.ctx.site.store.get(key):
300300
return Link(doc)
301301
else:
@@ -466,7 +466,7 @@ def create(
466466
raise ValueError('something_went_wrong')
467467

468468
if verified:
469-
key = "account/%s/verify" % username
469+
key = f"account/{username}/verify"
470470
doc = create_link_doc(key, username, email)
471471
web.ctx.site.store[key] = doc
472472
web.ctx.site.activate_account(username=username)
@@ -583,7 +583,7 @@ def link(self, itemname):
583583
"""Careful, this will save any other changes to the ol user object as
584584
well
585585
"""
586-
itemname = itemname if itemname.startswith('@') else '@%s' % itemname
586+
itemname = itemname if itemname.startswith('@') else f'@{itemname}'
587587

588588
_ol_account = web.ctx.site.store.get(self._key)
589589
_ol_account['internetarchive_itemname'] = itemname

openlibrary/admin/numbers.py

Lines changed: 9 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -37,12 +37,12 @@ class NoStats(TypeError):
3737
def query_single_thing(db, typ, start, end):
3838
"Query the counts a single type from the things table"
3939
q1 = "SELECT id as id from thing where key=$typ"
40-
typ = '/type/%s' % typ
40+
typ = f'/type/{typ}'
4141
result = db.query(q1, vars=locals())
4242
try:
4343
kid = result[0].id
4444
except IndexError:
45-
raise InvalidType("No id for type '/type/%s in the database" % typ)
45+
raise InvalidType(f"No id for type '/type/{typ} in the database")
4646
q2 = (
4747
"select count(*) as count from thing where type=%d and created >= '%s' and created < '%s'"
4848
% (kid, start, end)
@@ -77,11 +77,8 @@ def admin_range__human_edits(**kargs):
7777
end = kargs['end'].strftime("%Y-%m-%d %H:%M:%S")
7878
db = kargs['thingdb']
7979
except KeyError as k:
80-
raise TypeError("%s is a required argument for admin_range__human_edits" % k)
81-
q1 = (
82-
"SELECT count(*) AS count FROM transaction WHERE created >= '%s' and created < '%s'"
83-
% (start, end)
84-
)
80+
raise TypeError(f"{k} is a required argument for admin_range__human_edits")
81+
q1 = f"SELECT count(*) AS count FROM transaction WHERE created >= '{start}' and created < '{end}'"
8582
result = db.query(q1)
8683
total_edits = result[0].count
8784
q1 = (
@@ -103,7 +100,7 @@ def admin_range__bot_edits(**kargs):
103100
end = kargs['end'].strftime("%Y-%m-%d %H:%M:%S")
104101
db = kargs['thingdb']
105102
except KeyError as k:
106-
raise TypeError("%s is a required argument for admin_range__bot_edits" % k)
103+
raise TypeError(f"{k} is a required argument for admin_range__bot_edits")
107104
q1 = (
108105
"SELECT count(*) AS count FROM transaction t, version v WHERE "
109106
f"v.transaction_id=t.id AND t.created >= '{start}' and t.created < '{end}' AND "
@@ -121,11 +118,8 @@ def admin_range__covers(**kargs):
121118
end = kargs['end'].strftime("%Y-%m-%d %H:%M:%S")
122119
db = kargs['coverdb']
123120
except KeyError as k:
124-
raise TypeError("%s is a required argument for admin_range__covers" % k)
125-
q1 = (
126-
"SELECT count(*) as count from cover where created>= '%s' and created < '%s'"
127-
% (start, end)
128-
)
121+
raise TypeError(f"{k} is a required argument for admin_range__covers")
122+
q1 = f"SELECT count(*) as count from cover where created>= '{start}' and created < '{end}'"
129123
result = db.query(q1)
130124
count = result[0].count
131125
return count
@@ -151,7 +145,7 @@ def admin_range__loans(**kargs):
151145
start = kargs['start']
152146
end = kargs['end']
153147
except KeyError as k:
154-
raise TypeError("%s is a required argument for admin_total__ebooks" % k)
148+
raise TypeError(f"{k} is a required argument for admin_total__ebooks")
155149
result = db.query(
156150
"SELECT count(*) as count FROM stats"
157151
" WHERE type='loan'"
@@ -177,7 +171,7 @@ def admin_total__lists(**kargs):
177171
try:
178172
db = kargs['thingdb']
179173
except KeyError as k:
180-
raise TypeError("%s is a required argument for admin_total__lists" % k)
174+
raise TypeError(f"{k} is a required argument for admin_total__lists")
181175
# Computing total number of lists
182176
q1 = "SELECT id as id from thing where key='/type/list'"
183177
result = db.query(q1)

openlibrary/catalog/add_book/__init__.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ def __init__(self, f):
8787
self.f = f
8888

8989
def __str__(self):
90-
return "coverstore responded with: '%s'" % self.f
90+
return f"coverstore responded with: '{self.f}'"
9191

9292

9393
class RequiredField(Exception):
@@ -380,7 +380,7 @@ def create_ol_subjects_for_ocaid(ocaid, subjects):
380380
if r.status_code != 200:
381381
return f'{item.identifier} failed: {r.content}'
382382
else:
383-
return "success for %s" % item.identifier
383+
return f"success for {item.identifier}"
384384

385385

386386
def update_ia_metadata_for_ol_edition(edition_id):
@@ -395,7 +395,7 @@ def update_ia_metadata_for_ol_edition(edition_id):
395395

396396
data = {'error': 'No qualifying edition'}
397397
if edition_id:
398-
ed = web.ctx.site.get('/books/%s' % edition_id)
398+
ed = web.ctx.site.get(f'/books/{edition_id}')
399399
if ed.ocaid:
400400
work = ed.works[0] if ed.get('works') else None
401401
if work and work.key:

openlibrary/code.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@ def setup():
3131

3232
for p in old_plugins:
3333
logger.info("loading plugin %s", p)
34-
modname = "openlibrary.plugins.%s.code" % p
34+
modname = f"openlibrary.plugins.{p}.code"
3535
path = "openlibrary/plugins/" + p
3636
template.load_templates(path, lazy=True)
3737
macro.load_macros(path, lazy=True)

openlibrary/core/ia.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ def get_api_response(url: str, params: dict | None = None) -> dict:
3535
else:
3636
logger.info(f'{r.status_code} response received from {url}')
3737
except Exception as e:
38-
logger.exception('Exception occurred accessing %s.' % url)
38+
logger.exception(f'Exception occurred accessing {url}.')
3939
stats.end()
4040
return api_response
4141

@@ -124,7 +124,7 @@ def get_cover_url(item_id):
124124

125125

126126
def get_item_manifest(item_id, item_server, item_path):
127-
url = 'https://%s/BookReader/BookReaderJSON.php' % item_server
127+
url = f'https://{item_server}/BookReader/BookReaderJSON.php'
128128
url += f'?itemPath={item_path}&itemId={item_id}&server={item_server}'
129129
return get_api_response(url)
130130

openlibrary/core/lending.py

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -176,7 +176,7 @@ def compose_ia_url(
176176
sorts = ['']
177177
for sort in sorts:
178178
params.append(('sort[]', sort))
179-
base_url = "http://%s/advancedsearch.php" % config_bookreader_host
179+
base_url = f"http://{config_bookreader_host}/advancedsearch.php"
180180
return base_url + '?' + urlencode(params)
181181

182182

@@ -286,11 +286,11 @@ def get_available(
286286
for item in items:
287287
if item.get('openlibrary_work'):
288288
results[item['openlibrary_work']] = item['openlibrary_edition']
289-
books = web.ctx.site.get_many(['/books/%s' % olid for olid in results.values()])
289+
books = web.ctx.site.get_many([f'/books/{olid}' for olid in results.values()])
290290
books = add_availability(books)
291291
return books
292292
except Exception: # TODO: Narrow exception scope
293-
logger.exception("get_available(%s)" % url)
293+
logger.exception(f"get_available({url})")
294294
return {'error': 'request_timeout'}
295295

296296

@@ -566,12 +566,12 @@ def is_loaned_out_on_acs4(identifier: str) -> bool:
566566

567567
def is_loaned_out_on_ia(identifier: str) -> bool | None:
568568
"""Returns True if the item is checked out on Internet Archive."""
569-
url = "https://archive.org/services/borrow/%s?action=status" % identifier
569+
url = f"https://archive.org/services/borrow/{identifier}?action=status"
570570
try:
571571
response = requests.get(url).json()
572572
return response and response.get('checkedout')
573573
except Exception: # TODO: Narrow exception scope
574-
logger.exception("is_loaned_out_on_ia(%s)" % identifier)
574+
logger.exception(f"is_loaned_out_on_ia({identifier})")
575575
return None
576576

577577

@@ -607,12 +607,12 @@ def get_loan(identifier, user_key=None):
607607
try:
608608
_loan = _get_ia_loan(identifier, account and userkey2userid(account.username))
609609
except Exception: # TODO: Narrow exception scope
610-
logger.exception("get_loan(%s) 1 of 2" % identifier)
610+
logger.exception(f"get_loan({identifier}) 1 of 2")
611611

612612
try:
613613
_loan = _get_ia_loan(identifier, account and account.itemname)
614614
except Exception: # TODO: Narrow exception scope
615-
logger.exception("get_loan(%s) 2 of 2" % identifier)
615+
logger.exception(f"get_loan({identifier}) 2 of 2")
616616

617617
return _loan
618618

openlibrary/core/models.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -295,7 +295,7 @@ def get_ebook_info(self):
295295
d['borrowed'] = doc.get("borrowed") == "true"
296296
d['daisy_only'] = False
297297
elif 'printdisabled' not in collections:
298-
d['read_url'] = "https://archive.org/stream/%s" % self.ocaid
298+
d['read_url'] = f"https://archive.org/stream/{self.ocaid}"
299299
d['daisy_only'] = False
300300
return d
301301

@@ -415,7 +415,7 @@ def from_isbn(
415415
if book_id == asin:
416416
query = {"type": "/type/edition", 'identifiers': {'amazon': asin}}
417417
else:
418-
query = {"type": "/type/edition", 'isbn_%s' % len(book_id): book_id}
418+
query = {"type": "/type/edition", f'isbn_{len(book_id)}': book_id}
419419

420420
if matches := web.ctx.site.things(query):
421421
return web.ctx.site.get(matches[0])
@@ -841,12 +841,12 @@ def get_username(self):
841841
return self.key.split("/")[-1]
842842

843843
def preferences(self):
844-
key = "%s/preferences" % self.key
844+
key = f"{self.key}/preferences"
845845
prefs = web.ctx.site.get(key)
846846
return (prefs and prefs.dict().get('notifications')) or self.DEFAULT_PREFERENCES
847847

848848
def save_preferences(self, new_prefs, msg='updating user preferences'):
849-
key = '%s/preferences' % self.key
849+
key = f'{self.key}/preferences'
850850
old_prefs = web.ctx.site.get(key)
851851
prefs = (old_prefs and old_prefs.dict()) or {
852852
'key': key,
@@ -859,7 +859,7 @@ def save_preferences(self, new_prefs, msg='updating user preferences'):
859859

860860
def is_usergroup_member(self, usergroup):
861861
if not usergroup.startswith('/usergroup/'):
862-
usergroup = '/usergroup/%s' % usergroup
862+
usergroup = f'/usergroup/{usergroup}'
863863
return usergroup in [g.key for g in self.usergroups]
864864

865865
def is_subscribed_user(self, username):
@@ -914,7 +914,7 @@ def get_lists(self, seed=None, limit=100, offset=0, sort=True):
914914
# @cache.memoize(engine="memcache", key="user-avatar")
915915
def get_avatar_url(cls, username):
916916
username = username.split('/people/')[-1]
917-
user = web.ctx.site.get('/people/%s' % username)
917+
user = web.ctx.site.get(f'/people/{username}')
918918
itemname = user.get_account().get('internetarchive_itemname')
919919

920920
return f'https://archive.org/services/img/{itemname}'
@@ -1041,7 +1041,7 @@ def render_link(self, cls=None):
10411041
"""
10421042
extra_attrs = ''
10431043
if cls:
1044-
extra_attrs += 'class="%s" ' % cls
1044+
extra_attrs += f'class="{cls}" '
10451045
# Why nofollow?
10461046
return f'<a rel="nofollow" href="{self.key}" {extra_attrs}>{web.net.htmlquote(self.displayname)}</a>'
10471047

@@ -1058,7 +1058,7 @@ def from_key(cls, key: str):
10581058
:rtype: UserGroup | None
10591059
"""
10601060
if not key.startswith('/usergroup/'):
1061-
key = "/usergroup/%s" % key
1061+
key = f"/usergroup/{key}"
10621062
return web.ctx.site.get(key)
10631063

10641064
def add_user(self, userkey: str) -> None:

openlibrary/core/stats.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def increment(key, n=1, rate=1.0):
4848
"Increments the value of ``key`` by ``n``"
4949
global client
5050
if client:
51-
pystats_logger.debug("Incrementing %s" % key)
51+
pystats_logger.debug(f"Incrementing {key}")
5252
for i in range(n):
5353
try:
5454
client.increment(key, sample_rate=rate)

openlibrary/core/vendors.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,7 @@ def serialize(product: Any) -> dict:
247247
'url': "https://www.amazon.com/dp/{}/?tag={}".format(
248248
product.asin, h.affiliate_id('amazon')
249249
),
250-
'source_records': ['amazon:%s' % product.asin],
250+
'source_records': [f'amazon:{product.asin}'],
251251
'isbn_10': [product.asin] if asin_is_isbn10 else [],
252252
'isbn_13': [isbn_13] if isbn_13 else [],
253253
'price': price and price.display_amount,

0 commit comments

Comments
 (0)