aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorBen Sturmfels <ben@sturm.com.au>2021-09-23 11:51:04 +1000
committerBen Sturmfels <ben@sturm.com.au>2021-09-23 11:51:04 +1000
commit6f48143f4c60c555b3f571007cdc929ce90920b1 (patch)
tree2a2333a365379d4c4c42faf79bcd9db20aaa8626
parentf90707e22c0380bd0f17e2e724e58ecf91abd5a3 (diff)
downloadmediagoblin-6f48143f4c60c555b3f571007cdc929ce90920b1.tar.lz
mediagoblin-6f48143f4c60c555b3f571007cdc929ce90920b1.tar.xz
mediagoblin-6f48143f4c60c555b3f571007cdc929ce90920b1.zip
Apply pyupgrade --py36-plus.
This removes some 'u' prefixes and converts simple format() calls to f-strings.
-rw-r--r--api-docs/source/conf.py17
-rw-r--r--docs/source/conf.py15
-rw-r--r--mediagoblin/api/views.py40
-rw-r--r--mediagoblin/db/migrations.py4
-rw-r--r--mediagoblin/db/mixin.py2
-rw-r--r--mediagoblin/db/models.py18
-rw-r--r--mediagoblin/gmg_commands/alembic_commands.py2
-rw-r--r--mediagoblin/gmg_commands/dbupdate.py4
-rw-r--r--mediagoblin/gmg_commands/reprocess.py10
-rw-r--r--mediagoblin/init/config.py2
-rw-r--r--mediagoblin/meddleware/csrf.py2
-rw-r--r--mediagoblin/media_types/__init__.py6
-rw-r--r--mediagoblin/media_types/ascii/asciitoimage.py2
-rw-r--r--mediagoblin/media_types/ascii/processing.py2
-rw-r--r--mediagoblin/media_types/audio/audiotospectrogram.py6
-rw-r--r--mediagoblin/media_types/audio/processing.py2
-rw-r--r--mediagoblin/media_types/audio/transcoders.py10
-rw-r--r--mediagoblin/media_types/blog/models.py2
-rw-r--r--mediagoblin/media_types/image/processing.py2
-rw-r--r--mediagoblin/media_types/pdf/processing.py2
-rw-r--r--mediagoblin/media_types/raw_image/processing.py2
-rw-r--r--mediagoblin/media_types/stl/processing.py2
-rw-r--r--mediagoblin/media_types/tools.py4
-rw-r--r--mediagoblin/media_types/video/__init__.py2
-rw-r--r--mediagoblin/media_types/video/processing.py18
-rw-r--r--mediagoblin/media_types/video/transcoders.py10
-rw-r--r--mediagoblin/media_types/video/util.py2
-rw-r--r--mediagoblin/notifications/__init__.py2
-rw-r--r--mediagoblin/notifications/task.py2
-rw-r--r--mediagoblin/oauth/views.py6
-rw-r--r--mediagoblin/plugins/api/__init__.py2
-rw-r--r--mediagoblin/plugins/api/tools.py2
-rw-r--r--mediagoblin/plugins/basic_auth/tools.py4
-rw-r--r--mediagoblin/plugins/flatpagesfile/__init__.py2
-rw-r--r--mediagoblin/plugins/openid/models.py4
-rw-r--r--mediagoblin/plugins/piwigo/tools.py2
-rw-r--r--mediagoblin/plugins/piwigo/views.py2
-rw-r--r--mediagoblin/plugins/trim_whitespace/__init__.py2
-rw-r--r--mediagoblin/processing/__init__.py4
-rw-r--r--mediagoblin/processing/task.py4
-rw-r--r--mediagoblin/storage/cloudfiles.py2
-rw-r--r--mediagoblin/submit/forms.py2
-rw-r--r--mediagoblin/submit/lib.py2
-rw-r--r--mediagoblin/tests/test_api.py26
-rw-r--r--mediagoblin/tests/test_auth.py4
-rw-r--r--mediagoblin/tests/test_edit.py2
-rw-r--r--mediagoblin/tests/test_exif.py2
-rw-r--r--mediagoblin/tests/test_moderation.py18
-rw-r--r--mediagoblin/tests/test_notifications.py2
-rw-r--r--mediagoblin/tests/test_oauth1.py2
-rw-r--r--mediagoblin/tests/test_reporting.py2
-rw-r--r--mediagoblin/tests/test_submission.py14
-rw-r--r--mediagoblin/tools/pluginapi.py2
-rw-r--r--mediagoblin/tools/processing.py4
-rw-r--r--mediagoblin/tools/response.py2
-rw-r--r--mediagoblin/tools/routing.py2
-rw-r--r--mediagoblin/tools/translate.py6
57 files changed, 160 insertions, 162 deletions
diff --git a/api-docs/source/conf.py b/api-docs/source/conf.py
index da524d28..7f51e6d2 100644
--- a/api-docs/source/conf.py
+++ b/api-docs/source/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
#
# GNU MediaGoblin documentation build configuration file, created by
# sphinx-quickstart on Sun Apr 1 01:11:46 2012.
@@ -40,8 +39,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
-project = u'GNU MediaGoblin'
-copyright = u'2011, 2012, GNU MediaGoblin contributors'
+project = 'GNU MediaGoblin'
+copyright = '2011, 2012, GNU MediaGoblin contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -183,8 +182,8 @@ latex_elements = {
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
- ('index', 'GNUMediaGoblin.tex', u'GNU MediaGoblin Documentation',
- u'See AUTHORS', 'manual'),
+ ('index', 'GNUMediaGoblin.tex', 'GNU MediaGoblin Documentation',
+ 'See AUTHORS', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -213,8 +212,8 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
- ('index', 'gnumediagoblin', u'GNU MediaGoblin Documentation',
- [u'See AUTHORS'], 1)
+ ('index', 'gnumediagoblin', 'GNU MediaGoblin Documentation',
+ ['See AUTHORS'], 1)
]
# If true, show URL addresses after external links.
@@ -227,8 +226,8 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- ('index', 'GNUMediaGoblin', u'GNU MediaGoblin Documentation',
- u'See AUTHORS', 'GNUMediaGoblin', 'One line description of project.',
+ ('index', 'GNUMediaGoblin', 'GNU MediaGoblin Documentation',
+ 'See AUTHORS', 'GNUMediaGoblin', 'One line description of project.',
'Miscellaneous'),
]
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 48f68b14..5e6c98d5 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -1,4 +1,3 @@
-# -*- coding: utf-8 -*-
#
# GNU MediaGoblin documentation build configuration file, created by
# sphinx-quickstart on Thu Apr 7 20:10:27 2011.
@@ -42,8 +41,8 @@ source_suffix = '.rst'
master_doc = 'index'
# General information about the project.
-project = u'GNU MediaGoblin'
-copyright = u'2011, 2012 GNU MediaGoblin contributors'
+project = 'GNU MediaGoblin'
+copyright = '2011, 2012 GNU MediaGoblin contributors'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
@@ -186,8 +185,8 @@ htmlhelp_basename = 'GNUMediaGoblindoc'
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
- ('index', 'GNUMediaGoblin.tex', u'GNU MediaGoblin Documentation',
- u'Chris Webber, et al', 'manual'),
+ ('index', 'GNUMediaGoblin.tex', 'GNU MediaGoblin Documentation',
+ 'Chris Webber, et al', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
@@ -219,8 +218,8 @@ latex_documents = [
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
- ('index', 'mediagoblin', u'GNU MediaGoblin Documentation',
- [u'Chris Webber, et al'], 1)
+ ('index', 'mediagoblin', 'GNU MediaGoblin Documentation',
+ ['Chris Webber, et al'], 1)
]
# If true, show URL addresses after external links.
@@ -233,7 +232,7 @@ man_pages = [
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
- ('index', 'mediagoblin', u'GNU MediaGoblin Documentation', u'mediagoblin',
+ ('index', 'mediagoblin', 'GNU MediaGoblin Documentation', 'mediagoblin',
'GNU MediaGoblin', 'Media sharing web application.', 'Miscellaneous'),
]
diff --git a/mediagoblin/api/views.py b/mediagoblin/api/views.py
index b78a19e3..f5e13147 100644
--- a/mediagoblin/api/views.py
+++ b/mediagoblin/api/views.py
@@ -62,7 +62,7 @@ def profile_endpoint(request):
if user is None:
username = request.matchdict["username"]
return json_error(
- "No such 'user' with username '{}'".format(username),
+ f"No such 'user' with username '{username}'",
status=404
)
@@ -77,7 +77,7 @@ def user_endpoint(request):
if user is None:
username = request.matchdict["username"]
return json_error(
- "No such 'user' with username '{}'".format(username),
+ f"No such 'user' with username '{username}'",
status=404
)
@@ -97,7 +97,7 @@ def uploads_endpoint(request):
requested_user = LocalUser.query.filter(LocalUser.username==username).first()
if requested_user is None:
- return json_error("No such 'user' with id '{}'".format(username), 404)
+ return json_error(f"No such 'user' with id '{username}'", 404)
if request.method == "POST":
# Ensure that the user is only able to upload to their own
@@ -121,9 +121,9 @@ def uploads_endpoint(request):
else:
filenames = sorted(mimetypes.guess_all_extensions(mimetype))
if not filenames:
- return json_error('Unknown mimetype: {}'.format(mimetype),
+ return json_error(f'Unknown mimetype: {mimetype}',
status=415)
- filename = 'unknown{}'.format(filenames[0])
+ filename = f'unknown{filenames[0]}'
file_data = FileStorage(
stream=io.BytesIO(request.data),
@@ -153,13 +153,13 @@ def inbox_endpoint(request, inbox=None):
user = LocalUser.query.filter(LocalUser.username==username).first()
if user is None:
- return json_error("No such 'user' with id '{}'".format(username), 404)
+ return json_error(f"No such 'user' with id '{username}'", 404)
# Only the user who's authorized should be able to read their inbox
if user.id != request.user.id:
return json_error(
- "Only '{}' can read this inbox.".format(user.username),
+ f"Only '{user.username}' can read this inbox.",
403
)
@@ -190,7 +190,7 @@ def inbox_endpoint(request, inbox=None):
# build the inbox feed
feed = {
- "displayName": "Activities for {}".format(user.username),
+ "displayName": f"Activities for {user.username}",
"author": user.serialize(request),
"objectTypes": ["activity"],
"url": request.base_url,
@@ -237,7 +237,7 @@ def feed_endpoint(request, outbox=None):
# check if the user exists
if requested_user is None:
- return json_error("No such 'user' with id '{}'".format(username), 404)
+ return json_error(f"No such 'user' with id '{username}'", 404)
if request.data:
data = json.loads(request.data.decode())
@@ -313,7 +313,7 @@ def feed_endpoint(request, outbox=None):
if media is None:
return json_response(
- "No such 'image' with id '{}'".format(media_id),
+ f"No such 'image' with id '{media_id}'",
status=404
)
@@ -326,7 +326,7 @@ def feed_endpoint(request, outbox=None):
if not media.unserialize(data["object"]):
return json_error(
- "Invalid 'image' with id '{}'".format(media_id)
+ f"Invalid 'image' with id '{media_id}'"
)
@@ -346,7 +346,7 @@ def feed_endpoint(request, outbox=None):
# Oh no! We don't know about this type of object (yet)
object_type = obj.get("objectType", None)
return json_error(
- "Unknown object type '{}'.".format(object_type)
+ f"Unknown object type '{object_type}'."
)
# Updating existing objects
@@ -388,7 +388,7 @@ def feed_endpoint(request, outbox=None):
).first()
if comment is None:
return json_error(
- "No such 'comment' with id '{}'.".format(obj_id)
+ f"No such 'comment' with id '{obj_id}'."
)
# Check that the person trying to update the comment is
@@ -436,7 +436,7 @@ def feed_endpoint(request, outbox=None):
if not image.unserialize(obj):
return json_error(
- "Invalid 'image' with id '{}'".format(obj_id)
+ f"Invalid 'image' with id '{obj_id}'"
)
image.generate_slug()
image.save()
@@ -504,7 +504,7 @@ def feed_endpoint(request, outbox=None):
if comment is None:
return json_error(
- "No such 'comment' with id '{}'.".format(obj_id)
+ f"No such 'comment' with id '{obj_id}'."
)
# Make a delete activity
@@ -533,7 +533,7 @@ def feed_endpoint(request, outbox=None):
if entry is None:
return json_error(
- "No such 'image' with id '{}'.".format(obj_id)
+ f"No such 'image' with id '{obj_id}'."
)
# Make the delete activity
@@ -555,7 +555,7 @@ def feed_endpoint(request, outbox=None):
elif request.method != "GET":
return json_error(
- "Unsupported HTTP method {}".format(request.method),
+ f"Unsupported HTTP method {request.method}",
status=501
)
@@ -654,7 +654,7 @@ def object_endpoint(request):
if object_type not in ["image"]:
# not sure why this is 404, maybe ask evan. Maybe 400?
return json_error(
- "Unknown type: {}".format(object_type),
+ f"Unknown type: {object_type}",
status=404
)
@@ -668,7 +668,7 @@ def object_endpoint(request):
media = MediaEntry.query.filter_by(public_id=public_id).first()
if media is None:
return json_error(
- "Can't find '{}' with ID '{}'".format(object_type, object_id),
+ f"Can't find '{object_type}' with ID '{object_id}'",
status=404
)
@@ -805,7 +805,7 @@ def lrdd_lookup(request):
if user is None:
return json_error(
- "Can't find 'user' with username '{}'".format(username))
+ f"Can't find 'user' with username '{username}'")
return json_response([
{
diff --git a/mediagoblin/db/migrations.py b/mediagoblin/db/migrations.py
index 6c5b027c..f00c8019 100644
--- a/mediagoblin/db/migrations.py
+++ b/mediagoblin/db/migrations.py
@@ -425,9 +425,9 @@ class Client_v0(declarative_base()):
def __repr__(self):
if self.application_name:
- return "<Client {} - {}>".format(self.application_name, self.id)
+ return f"<Client {self.application_name} - {self.id}>"
else:
- return "<Client {}>".format(self.id)
+ return f"<Client {self.id}>"
class RequestToken_v0(declarative_base()):
"""
diff --git a/mediagoblin/db/mixin.py b/mediagoblin/db/mixin.py
index 1a47c46f..dd78c791 100644
--- a/mediagoblin/db/mixin.py
+++ b/mediagoblin/db/mixin.py
@@ -188,7 +188,7 @@ class GenerateSlugMixin:
# Can we just append the object's id to the end?
if self.id:
- slug_with_id = "{}-{}".format(slug, self.id)
+ slug_with_id = f"{slug}-{self.id}"
if not self.check_slug_used(slug_with_id):
self.slug = slug_with_id
return # success!
diff --git a/mediagoblin/db/models.py b/mediagoblin/db/models.py
index c5809185..e65690fe 100644
--- a/mediagoblin/db/models.py
+++ b/mediagoblin/db/models.py
@@ -290,7 +290,7 @@ class User(Base, UserMixin):
# Delete user, pass through commit=False/True in kwargs
username = self.username
super().delete(*args, **kwargs)
- _log.info('Deleted user "{}" account'.format(username))
+ _log.info(f'Deleted user "{username}" account')
def has_privilege(self, privilege, allow_admin=True):
"""
@@ -389,7 +389,7 @@ class LocalUser(User):
self.username)
def get_public_id(self, host):
- return "acct:{}@{}".format(self.username, host)
+ return f"acct:{self.username}@{host}"
def serialize(self, request):
user = {
@@ -464,9 +464,9 @@ class Client(Base):
def __repr__(self):
if self.application_name:
- return "<Client {} - {}>".format(self.application_name, self.id)
+ return f"<Client {self.application_name} - {self.id}>"
else:
- return "<Client {}>".format(self.id)
+ return f"<Client {self.id}>"
class RequestToken(Base):
"""
@@ -738,7 +738,7 @@ class MediaEntry(Base, MediaEntryMixin, CommentingMixin):
# Returns list of files we failed to delete
_log.error('No such files from the user "{1}" to delete: '
'{0}'.format(str(error), self.get_actor))
- _log.info('Deleted Media entry id "{}"'.format(self.id))
+ _log.info(f'Deleted Media entry id "{self.id}"')
# Related MediaTag's are automatically cleaned, but we might
# want to clean out unused Tag's too.
if del_orphan_tags:
@@ -858,7 +858,7 @@ class FileKeynames(Base):
name = Column(Unicode, unique=True)
def __repr__(self):
- return "<FileKeyname {!r}: {!r}>".format(self.id, self.name)
+ return f"<FileKeyname {self.id!r}: {self.name!r}>"
@classmethod
def find_or_new(cls, name):
@@ -887,7 +887,7 @@ class MediaFile(Base):
{})
def __repr__(self):
- return "<MediaFile {}: {!r}>".format(self.name, self.file_path)
+ return f"<MediaFile {self.name}: {self.file_path!r}>"
name_helper = relationship(FileKeynames, lazy="joined", innerjoin=True)
name = association_proxy('name_helper', 'name',
@@ -935,7 +935,7 @@ class Tag(Base):
slug = Column(Unicode, nullable=False, unique=True)
def __repr__(self):
- return "<Tag {!r}: {!r}>".format(self.id, self.slug)
+ return f"<Tag {self.id!r}: {self.slug!r}>"
@classmethod
def find_or_new(cls, slug):
@@ -1034,7 +1034,7 @@ class Comment(Base):
# fetch it from self.comment()
raise AttributeError
try:
- _log.debug('Old attr is being accessed: {}'.format(attr))
+ _log.debug(f'Old attr is being accessed: {attr}')
return getattr(self.comment(), attr) # noqa
except Exception as e:
_log.error(e)
diff --git a/mediagoblin/gmg_commands/alembic_commands.py b/mediagoblin/gmg_commands/alembic_commands.py
index f5f982d1..0b22bce6 100644
--- a/mediagoblin/gmg_commands/alembic_commands.py
+++ b/mediagoblin/gmg_commands/alembic_commands.py
@@ -35,7 +35,7 @@ class FudgedCommandLine(config.CommandLine):
plugins = global_config.get('plugins', {}).keys()
for plugin in plugins:
try:
- import_component('{}.models:MODELS'.format(plugin))
+ import_component(f'{plugin}.models:MODELS')
except ImportError:
# It doesn't really matter if there's no models to import
# here.
diff --git a/mediagoblin/gmg_commands/dbupdate.py b/mediagoblin/gmg_commands/dbupdate.py
index c62de91e..c802b374 100644
--- a/mediagoblin/gmg_commands/dbupdate.py
+++ b/mediagoblin/gmg_commands/dbupdate.py
@@ -67,7 +67,7 @@ def gather_database_data(plugins):
for plugin in plugins:
try:
- models = import_component('{}.models:MODELS'.format(plugin))
+ models = import_component(f'{plugin}.models:MODELS')
except ImportError as exc:
_log.debug('No models found for {}: {}'.format(
plugin,
@@ -115,7 +115,7 @@ def run_foundations(db, global_config):
for plugin in plugins:
try:
foundations = import_component(
- '{}.models:FOUNDATIONS'.format(plugin))
+ f'{plugin}.models:FOUNDATIONS')
all_foundations.append((plugin, foundations))
except ImportError as exc:
continue
diff --git a/mediagoblin/gmg_commands/reprocess.py b/mediagoblin/gmg_commands/reprocess.py
index b2a69819..b2ed62fe 100644
--- a/mediagoblin/gmg_commands/reprocess.py
+++ b/mediagoblin/gmg_commands/reprocess.py
@@ -145,7 +145,7 @@ def available(args):
manager = get_processing_manager_for_type(media_type)
except ProcessingManagerDoesNotExist:
entry = MediaEntry.query.filter_by(id=args.id_or_type).first()
- print('No such processing manager for {}'.format(entry.media_type))
+ print(f'No such processing manager for {entry.media_type}')
if args.state:
processors = manager.list_all_processors_by_state(args.state)
@@ -170,7 +170,7 @@ def available(args):
else:
for processor in processors:
if processor.description:
- print(" - {}: {}".format(processor.name, processor.description))
+ print(f" - {processor.name}: {processor.description}")
else:
print(" - %s" % processor.name)
@@ -205,7 +205,7 @@ def run(args, media_id=None):
except ProcessingManagerDoesNotExist:
entry = MediaEntry.query.filter_by(id=media_id).first()
- print('No such processing manager for {}'.format(entry.media_type))
+ print(f'No such processing manager for {entry.media_type}')
def bulk_run(args):
@@ -262,7 +262,7 @@ def thumbs(args):
reprocess_info=reprocess_request)
except ProcessingManagerDoesNotExist:
- print('No such processing manager for {}'.format(entry.media_type))
+ print(f'No such processing manager for {entry.media_type}')
def initial(args):
@@ -278,7 +278,7 @@ def initial(args):
media_entry,
reprocess_action='initial')
except ProcessingManagerDoesNotExist:
- print('No such processing manager for {}'.format(entry.media_type))
+ print(f'No such processing manager for {entry.media_type}')
def reprocess(args):
diff --git a/mediagoblin/init/config.py b/mediagoblin/init/config.py
index 7f9ad32a..fbe7ef08 100644
--- a/mediagoblin/init/config.py
+++ b/mediagoblin/init/config.py
@@ -181,7 +181,7 @@ def generate_validation_report(config, validation_result):
# We don't care about missing values for now.
continue
- report.append("{} = {}".format(section_string, error))
+ report.append(f"{section_string} = {error}")
if report:
return REPORT_HEADER + "\n".join(report)
diff --git a/mediagoblin/meddleware/csrf.py b/mediagoblin/meddleware/csrf.py
index acde2852..75bad794 100644
--- a/mediagoblin/meddleware/csrf.py
+++ b/mediagoblin/meddleware/csrf.py
@@ -116,7 +116,7 @@ class CsrfMeddleware(BaseMeddleware):
def _make_token(self, request):
"""Generate a new token to use for CSRF protection."""
- return "{}".format(getrandbits(self.CSRF_KEYLEN))
+ return f"{getrandbits(self.CSRF_KEYLEN)}"
def verify_tokens(self, request):
"""Verify that the CSRF Cookie exists and that it matches the
diff --git a/mediagoblin/media_types/__init__.py b/mediagoblin/media_types/__init__.py
index 17f520a3..a1556f34 100644
--- a/mediagoblin/media_types/__init__.py
+++ b/mediagoblin/media_types/__init__.py
@@ -68,10 +68,10 @@ def sniff_media_contents(media_file, filename):
'''
media_type = hook_handle('sniff_handler', media_file, filename)
if media_type:
- _log.info('{} accepts the file'.format(media_type))
+ _log.info(f'{media_type} accepts the file')
return media_type, hook_handle(('media_manager', media_type))
else:
- _log.debug('{} did not accept the file'.format(media_type))
+ _log.debug(f'{media_type} did not accept the file')
raise FileTypeNotSupported(
# TODO: Provide information on which file types are supported
_('Sorry, I don\'t support that file type :('))
@@ -129,7 +129,7 @@ def type_match_handler(media_file, filename):
_log.debug(e)
raise
else:
- _log.info('No plugins handled extension {}'.format(ext))
+ _log.info(f'No plugins handled extension {ext}')
else:
_log.info('File {} has no known file extension, let\'s hope '
'the sniffers get it.'.format(filename))
diff --git a/mediagoblin/media_types/ascii/asciitoimage.py b/mediagoblin/media_types/ascii/asciitoimage.py
index 0bd72fe4..8b32986e 100644
--- a/mediagoblin/media_types/ascii/asciitoimage.py
+++ b/mediagoblin/media_types/ascii/asciitoimage.py
@@ -108,7 +108,7 @@ class AsciiToImage:
for line in lines:
line_length = len(line)
- _log.debug('Writing line at {}'.format(char_pos))
+ _log.debug(f'Writing line at {char_pos}')
for _pos in range(0, line_length):
char = line[_pos]
diff --git a/mediagoblin/media_types/ascii/processing.py b/mediagoblin/media_types/ascii/processing.py
index 6c5f3365..b321a461 100644
--- a/mediagoblin/media_types/ascii/processing.py
+++ b/mediagoblin/media_types/ascii/processing.py
@@ -37,7 +37,7 @@ MEDIA_TYPE = 'mediagoblin.media_types.ascii'
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
name, ext = os.path.splitext(filename)
clean_ext = ext[1:].lower()
diff --git a/mediagoblin/media_types/audio/audiotospectrogram.py b/mediagoblin/media_types/audio/audiotospectrogram.py
index 5ad89b93..27eaad1f 100644
--- a/mediagoblin/media_types/audio/audiotospectrogram.py
+++ b/mediagoblin/media_types/audio/audiotospectrogram.py
@@ -278,11 +278,11 @@ if __name__ == "__main__":
import sys
def printProgress(p):
- sys.stdout.write("\rProgress : {}%".format(p))
+ sys.stdout.write(f"\rProgress : {p}%")
sys.stdout.flush()
if not (len(sys.argv) == 2 or len(sys.argv) == 3):
- print("Usage:\n{} input_file [output_file]".format(sys.argv[0]))
+ print(f"Usage:\n{sys.argv[0]} input_file [output_file]")
exit()
audioFile = sys.argv[1]
@@ -292,6 +292,6 @@ if __name__ == "__main__":
else:
outputFile = 'spectrogram.png'
- sys.stdout.write("Input : {}\nOutput : {}\n".format(audioFile, outputFile))
+ sys.stdout.write(f"Input : {audioFile}\nOutput : {outputFile}\n")
drawSpectrogram(audioFile, outputFile, progressCallback = printProgress)
sys.stdout.write("\nDone!\n")
diff --git a/mediagoblin/media_types/audio/processing.py b/mediagoblin/media_types/audio/processing.py
index 0b06c529..f1c613ab 100644
--- a/mediagoblin/media_types/audio/processing.py
+++ b/mediagoblin/media_types/audio/processing.py
@@ -35,7 +35,7 @@ MEDIA_TYPE = 'mediagoblin.media_types.audio'
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
try:
data = discover(media_file.name)
except Exception as e:
diff --git a/mediagoblin/media_types/audio/transcoders.py b/mediagoblin/media_types/audio/transcoders.py
index 308e16d3..b0a9fb5c 100644
--- a/mediagoblin/media_types/audio/transcoders.py
+++ b/mediagoblin/media_types/audio/transcoders.py
@@ -45,7 +45,7 @@ Gst.init(None)
class Python3AudioThumbnailer:
def __init__(self):
- _log.info('Initializing {}'.format(self.__class__.__name__))
+ _log.info(f'Initializing {self.__class__.__name__}')
def spectrogram(self, src, dst, **kw):
from mediagoblin.media_types.audio import audiotospectrogram
@@ -85,7 +85,7 @@ AudioThumbnailer = Python3AudioThumbnailer
class AudioTranscoder:
def __init__(self):
- _log.info('Initializing {}'.format(self.__class__.__name__))
+ _log.info(f'Initializing {self.__class__.__name__}')
# Instantiate MainLoop
self._loop = GObject.MainLoop()
@@ -96,10 +96,10 @@ class AudioTranscoder:
def _on_pad_added(element, pad, connect_to):
caps = pad.query_caps(None)
name = caps.to_string()
- _log.debug('on_pad_added: {}'.format(name))
+ _log.debug(f'on_pad_added: {name}')
if name.startswith('audio') and not connect_to.is_linked():
pad.link(connect_to)
- _log.info('Transcoding {} into {}'.format(src, dst))
+ _log.info(f'Transcoding {src} into {dst}')
self.__on_progress = progress_callback
# Set up pipeline
tolerance = 80000000
@@ -155,7 +155,7 @@ class AudioTranscoder:
(success, percent) = structure.get_int('percent')
if self.__on_progress and success:
self.__on_progress(percent)
- _log.info('{}% done...'.format(percent))
+ _log.info(f'{percent}% done...')
elif message.type == Gst.MessageType.EOS:
_log.info('Done')
self.halt()
diff --git a/mediagoblin/media_types/blog/models.py b/mediagoblin/media_types/blog/models.py
index 6bb5e076..802bbb62 100644
--- a/mediagoblin/media_types/blog/models.py
+++ b/mediagoblin/media_types/blog/models.py
@@ -48,7 +48,7 @@ class Blog(Base, BlogMixin):
@property
def slug_or_id(self):
- return (self.slug or 'blog_{}'.format(self.id))
+ return (self.slug or f'blog_{self.id}')
def get_all_blog_posts(self, state=None):
blog_posts = Session.query(MediaEntry).join(BlogPostData)\
diff --git a/mediagoblin/media_types/image/processing.py b/mediagoblin/media_types/image/processing.py
index 95023731..acc21867 100644
--- a/mediagoblin/media_types/image/processing.py
+++ b/mediagoblin/media_types/image/processing.py
@@ -151,7 +151,7 @@ SUPPORTED_FILETYPES = ['png', 'gif', 'jpg', 'jpeg', 'tiff']
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
name, ext = os.path.splitext(filename)
clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase
diff --git a/mediagoblin/media_types/pdf/processing.py b/mediagoblin/media_types/pdf/processing.py
index 3792cfbd..d6bb4eb5 100644
--- a/mediagoblin/media_types/pdf/processing.py
+++ b/mediagoblin/media_types/pdf/processing.py
@@ -169,7 +169,7 @@ def check_prerequisites():
return True
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
if not check_prerequisites():
return None
diff --git a/mediagoblin/media_types/raw_image/processing.py b/mediagoblin/media_types/raw_image/processing.py
index 68d9bffe..b0178527 100644
--- a/mediagoblin/media_types/raw_image/processing.py
+++ b/mediagoblin/media_types/raw_image/processing.py
@@ -35,7 +35,7 @@ ACCEPTED_EXTENSIONS = ['nef', 'cr2']
# The entire function have to be copied
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
name, ext = os.path.splitext(filename)
clean_ext = ext[1:].lower() # Strip the . from ext and make lowercase
diff --git a/mediagoblin/media_types/stl/processing.py b/mediagoblin/media_types/stl/processing.py
index b4d9fe44..384a668f 100644
--- a/mediagoblin/media_types/stl/processing.py
+++ b/mediagoblin/media_types/stl/processing.py
@@ -48,7 +48,7 @@ BLEND_SCRIPT = pkg_resources.resource_filename(
def sniff_handler(media_file, filename):
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
name, ext = os.path.splitext(filename)
clean_ext = ext[1:].lower()
diff --git a/mediagoblin/media_types/tools.py b/mediagoblin/media_types/tools.py
index 72b4ab16..d773b8d7 100644
--- a/mediagoblin/media_types/tools.py
+++ b/mediagoblin/media_types/tools.py
@@ -40,7 +40,7 @@ def discover(src):
# init before import to work around https://bugzilla.gnome.org/show_bug.cgi?id=736260
from gi.repository import GstPbutils
- _log.info('Discovering {}...'.format(src))
- uri = 'file://{}'.format(src)
+ _log.info(f'Discovering {src}...')
+ uri = f'file://{src}'
discoverer = GstPbutils.Discoverer.new(60 * Gst.SECOND)
return discoverer.discover_uri(uri)
diff --git a/mediagoblin/media_types/video/__init__.py b/mediagoblin/media_types/video/__init__.py
index 356e0bb8..0a936719 100644
--- a/mediagoblin/media_types/video/__init__.py
+++ b/mediagoblin/media_types/video/__init__.py
@@ -40,7 +40,7 @@ class VideoMediaManager(MediaManagerBase):
video_res = video_config['available_resolutions']
video_res.remove(video_config['default_resolution'])
video_res.insert(0, video_config['default_resolution'])
- video_res = ['webm_{}'.format(x) for x in video_res]
+ video_res = [f'webm_{x}' for x in video_res]
return (['webm_video'] + video_res + ['original'])
diff --git a/mediagoblin/media_types/video/processing.py b/mediagoblin/media_types/video/processing.py
index 466ab194..ca7e801c 100644
--- a/mediagoblin/media_types/video/processing.py
+++ b/mediagoblin/media_types/video/processing.py
@@ -49,14 +49,14 @@ class VideoTranscodingFail(BaseProcessingFail):
def sniffer(media_file):
'''New style sniffer, used in two-steps check; requires to have .name'''
- _log.info('Sniffing {}'.format(MEDIA_TYPE))
+ _log.info(f'Sniffing {MEDIA_TYPE}')
try:
data = transcoders.discover(media_file.name)
except Exception as e:
# this is usually GLib.GError, but we don't really care which one
- _log.warning('GStreamer: {}'.format(str(e)))
- raise MissingComponents('GStreamer: {}'.format(str(e)))
- _log.debug('Discovered: {}'.format(data))
+ _log.warning(f'GStreamer: {str(e)}')
+ raise MissingComponents(f'GStreamer: {str(e)}')
+ _log.debug(f'Discovered: {data}')
if not data.get_video_streams():
raise MissingComponents('No video streams found in this video')
@@ -64,7 +64,7 @@ def sniffer(media_file):
if data.get_result() != 0: # it's 0 if success
try:
missing = data.get_misc().get_string('name')
- _log.warning('GStreamer: missing {}'.format(missing))
+ _log.warning(f'GStreamer: missing {missing}')
except AttributeError as e:
# AttributeError happens here on gstreamer >1.4, when get_misc
# returns None. There is a special function to get info about
@@ -74,7 +74,7 @@ def sniffer(media_file):
_log.warning('GStreamer: missing: {}'.format(', '.join(details)))
missing = ', '.join(['{} ({})'.format(*d.split('|')[3:])
for d in details])
- raise MissingComponents('{} is missing'.format(missing))
+ raise MissingComponents(f'{missing} is missing')
return MEDIA_TYPE
@@ -87,13 +87,13 @@ def sniff_handler(media_file, filename):
if clean_ext in EXCLUDED_EXTS:
# We don't handle this filetype, though gstreamer might think we can
- _log.info('Refused to process {} due to excluded extension'.format(filename))
+ _log.info(f'Refused to process {filename} due to excluded extension')
return None
try:
return sniffer(media_file)
except:
- _log.error('Could not discover {}'.format(filename))
+ _log.error(f'Could not discover {filename}')
return None
def get_tags(stream_info):
@@ -258,7 +258,7 @@ class CommonVideoProcessor(MediaProcessor):
# If we didn't transcode, then we need to keep the original
self.did_transcode = False
for each_res in self.video_config['available_resolutions']:
- if 'webm_{}'.format(each_res) in self.entry.media_files:
+ if f'webm_{each_res}' in self.entry.media_files:
self.did_transcode = True
break
if not self.did_transcode or self.video_config['keep_original']:
diff --git a/mediagoblin/media_types/video/transcoders.py b/mediagoblin/media_types/video/transcoders.py
index b5fd08e6..2d03bf4c 100644
--- a/mediagoblin/media_types/video/transcoders.py
+++ b/mediagoblin/media_types/video/transcoders.py
@@ -62,7 +62,7 @@ def capture_thumb(video_path, dest_path, width=None, height=None, percent=0.5):
'''This is a callback to dynamically add element to pipeline'''
caps = pad.query_caps(None)
name = caps.to_string()
- _log.debug('on_pad_added: {}'.format(name))
+ _log.debug(f'on_pad_added: {name}')
if name.startswith('video') and not connect_to.is_linked():
pad.link(connect_to)
@@ -70,7 +70,7 @@ def capture_thumb(video_path, dest_path, width=None, height=None, percent=0.5):
# ! CAPS ! appsink
pipeline = Gst.Pipeline()
uridecodebin = Gst.ElementFactory.make('uridecodebin', None)
- uridecodebin.set_property('uri', 'file://{}'.format(video_path))
+ uridecodebin.set_property('uri', f'file://{video_path}')
videoconvert = Gst.ElementFactory.make('videoconvert', None)
uridecodebin.connect('pad-added', pad_added,
videoconvert.get_static_pad('sink'))
@@ -104,7 +104,7 @@ def capture_thumb(video_path, dest_path, width=None, height=None, percent=0.5):
# timeout of 3 seconds below was set experimentally
state = pipeline.get_state(Gst.SECOND * 3)
if state[0] != Gst.StateChangeReturn.SUCCESS:
- _log.warning('state change failed, {}'.format(state))
+ _log.warning(f'state change failed, {state}')
return
# get duration
@@ -139,7 +139,7 @@ def capture_thumb(video_path, dest_path, width=None, height=None, percent=0.5):
im = Image.frombytes('RGB', (width, height),
buffer.extract_dup(0, buffer.get_size()))
im.save(dest_path)
- _log.info('thumbnail saved to {}'.format(dest_path))
+ _log.info(f'thumbnail saved to {dest_path}')
# cleanup
pipeline.set_state(Gst.State.NULL)
@@ -374,7 +374,7 @@ class VideoTranscoder:
_log.info('{percent}% of {dest} resolution done..'
'.'.format(percent=percent, dest=self.destination_dimensions))
elif message.type == Gst.MessageType.ERROR:
- _log.error('Got error: {}'.format(message.parse_error()))
+ _log.error(f'Got error: {message.parse_error()}')
self.dst_data = None
self.__stop()
diff --git a/mediagoblin/media_types/video/util.py b/mediagoblin/media_types/video/util.py
index 023194b5..88a22caf 100644
--- a/mediagoblin/media_types/video/util.py
+++ b/mediagoblin/media_types/video/util.py
@@ -43,7 +43,7 @@ def skip_transcode(metadata, size):
# XXX: how were we supposed to use it?
medium_config = mgg.global_config['media:medium']
- _log.debug('skip_transcode config: {}'.format(config))
+ _log.debug(f'skip_transcode config: {config}')
metadata_tags = metadata.get_tags()
if not metadata_tags:
diff --git a/mediagoblin/notifications/__init__.py b/mediagoblin/notifications/__init__.py
index 6c31dd00..2869980d 100644
--- a/mediagoblin/notifications/__init__.py
+++ b/mediagoblin/notifications/__init__.py
@@ -91,7 +91,7 @@ def mark_comment_notification_seen(comment_id, user):
object_id=comment_gmr.id
).first()
- _log.debug('Marking {} as seen.'.format(notification))
+ _log.debug(f'Marking {notification} as seen.')
mark_notification_seen(notification)
diff --git a/mediagoblin/notifications/task.py b/mediagoblin/notifications/task.py
index 74d67569..8b300cc8 100644
--- a/mediagoblin/notifications/task.py
+++ b/mediagoblin/notifications/task.py
@@ -35,7 +35,7 @@ class EmailNotificationTask(Task):
'''
def run(self, notification_id, message):
cn = Notification.query.filter_by(id=notification_id).first()
- _log.info('Sending notification email about {}'.format(cn))
+ _log.info(f'Sending notification email about {cn}')
return send_email(
message['from'],
diff --git a/mediagoblin/oauth/views.py b/mediagoblin/oauth/views.py
index 41652172..b9e014f8 100644
--- a/mediagoblin/oauth/views.py
+++ b/mediagoblin/oauth/views.py
@@ -126,7 +126,7 @@ def client_register(request):
logo_uri = data.get("logo_uri", client.logo_url)
if logo_uri is not None and not validate_url(logo_uri):
- error = "Logo URI {} is not a valid URI.".format(logo_uri)
+ error = f"Logo URI {logo_uri} is not a valid URI."
return json_response(
{"error": error},
status=400
@@ -146,7 +146,7 @@ def client_register(request):
for contact in contacts:
if not validate_email(contact):
# not a valid email
- error = "Email {} is not a valid email.".format(contact)
+ error = f"Email {contact} is not a valid email."
return json_response({"error": error}, status=400)
@@ -163,7 +163,7 @@ def client_register(request):
for uri in redirect_uris:
if not validate_url(uri):
# not a valid uri
- error = "URI {} is not a valid URI".format(uri)
+ error = f"URI {uri} is not a valid URI"
return json_response({"error": error}, status=400)
client.redirect_uri = redirect_uris
diff --git a/mediagoblin/plugins/api/__init__.py b/mediagoblin/plugins/api/__init__.py
index 51e22e85..ca7843f4 100644
--- a/mediagoblin/plugins/api/__init__.py
+++ b/mediagoblin/plugins/api/__init__.py
@@ -28,7 +28,7 @@ def setup_plugin():
config = pluginapi.get_config(__name__)
- _log.debug('API config: {}'.format(config))
+ _log.debug(f'API config: {config}')
routes = [
('mediagoblin.plugins.api.test',
diff --git a/mediagoblin/plugins/api/tools.py b/mediagoblin/plugins/api/tools.py
index 954b6e8b..79c63435 100644
--- a/mediagoblin/plugins/api/tools.py
+++ b/mediagoblin/plugins/api/tools.py
@@ -115,7 +115,7 @@ def api_auth(controller):
for auth in PluginManager().get_hook_callables('auth'):
if auth.trigger(request):
- _log.debug('{} believes it is capable of authenticating this request.'.format(auth))
+ _log.debug(f'{auth} believes it is capable of authenticating this request.')
auth_candidates.append(auth)
# If we can't find any authentication methods, we should not let them
diff --git a/mediagoblin/plugins/basic_auth/tools.py b/mediagoblin/plugins/basic_auth/tools.py
index 3e807297..5b89e51b 100644
--- a/mediagoblin/plugins/basic_auth/tools.py
+++ b/mediagoblin/plugins/basic_auth/tools.py
@@ -38,7 +38,7 @@ def bcrypt_check_password(raw_pass, stored_hash, extra_salt=None):
True or False depending on success.
"""
if extra_salt:
- raw_pass = "{}:{}".format(extra_salt, raw_pass)
+ raw_pass = f"{extra_salt}:{raw_pass}"
hashed_pass = bcrypt.hashpw(raw_pass.encode('utf-8'), stored_hash)
@@ -64,7 +64,7 @@ def bcrypt_gen_password_hash(raw_pass, extra_salt=None):
non-database extra salt
"""
if extra_salt:
- raw_pass = "{}:{}".format(extra_salt, raw_pass)
+ raw_pass = f"{extra_salt}:{raw_pass}"
return str(
bcrypt.hashpw(raw_pass.encode('utf-8'), bcrypt.gensalt()))
diff --git a/mediagoblin/plugins/flatpagesfile/__init__.py b/mediagoblin/plugins/flatpagesfile/__init__.py
index 5f267f07..d760137b 100644
--- a/mediagoblin/plugins/flatpagesfile/__init__.py
+++ b/mediagoblin/plugins/flatpagesfile/__init__.py
@@ -34,7 +34,7 @@ _log = logging.getLogger(__name__)
def print_context(c):
s = []
for key, val in c.items():
- s.append('{}: {}'.format(key, repr(val)))
+ s.append(f'{key}: {val!r}')
return '\n'.join(s)
diff --git a/mediagoblin/plugins/openid/models.py b/mediagoblin/plugins/openid/models.py
index e51b401c..433f0493 100644
--- a/mediagoblin/plugins/openid/models.py
+++ b/mediagoblin/plugins/openid/models.py
@@ -41,7 +41,7 @@ class Nonce(Base):
salt = Column(Unicode, primary_key=True)
def __unicode__(self):
- return 'Nonce: {!r}, {!r}'.format(self.server_url, self.salt)
+ return f'Nonce: {self.server_url!r}, {self.salt!r}'
class Association(Base):
@@ -55,7 +55,7 @@ class Association(Base):
assoc_type = Column(Unicode)
def __unicode__(self):
- return 'Association: {!r}, {!r}'.format(self.server_url, self.handle)
+ return f'Association: {self.server_url!r}, {self.handle!r}'
MODELS = [
diff --git a/mediagoblin/plugins/piwigo/tools.py b/mediagoblin/plugins/piwigo/tools.py
index dadd3e77..795beb1c 100644
--- a/mediagoblin/plugins/piwigo/tools.py
+++ b/mediagoblin/plugins/piwigo/tools.py
@@ -130,7 +130,7 @@ def check_form(form):
raise BadRequest()
dump = []
for f in form:
- dump.append("{}={!r}".format(f.name, f.data))
+ dump.append(f"{f.name}={f.data!r}")
_log.debug("form: %s", " ".join(dump))
diff --git a/mediagoblin/plugins/piwigo/views.py b/mediagoblin/plugins/piwigo/views.py
index bd1265c5..5294a386 100644
--- a/mediagoblin/plugins/piwigo/views.py
+++ b/mediagoblin/plugins/piwigo/views.py
@@ -119,7 +119,7 @@ def pwg_images_addSimple(request):
raise BadRequest()
dump = []
for f in form:
- dump.append("{}={!r}".format(f.name, f.data))
+ dump.append(f"{f.name}={f.data!r}")
_log.info("addSimple: %r %s %r", request.form, " ".join(dump),
request.files)
diff --git a/mediagoblin/plugins/trim_whitespace/__init__.py b/mediagoblin/plugins/trim_whitespace/__init__.py
index 6f67218c..713d13d5 100644
--- a/mediagoblin/plugins/trim_whitespace/__init__.py
+++ b/mediagoblin/plugins/trim_whitespace/__init__.py
@@ -64,7 +64,7 @@ class TrimWhiteSpaceMeddleware(meddleware.BaseMeddleware):
# Append ourselves to the list of enabled Meddlewares
meddleware.ENABLED_MEDDLEWARE.append(
- '{}:{}'.format(cls.__module__, cls.__name__))
+ f'{cls.__module__}:{cls.__name__}')
hooks = {
diff --git a/mediagoblin/processing/__init__.py b/mediagoblin/processing/__init__.py
index 540c8304..6a6f61dd 100644
--- a/mediagoblin/processing/__init__.py
+++ b/mediagoblin/processing/__init__.py
@@ -288,7 +288,7 @@ def get_processing_manager_for_type(media_type):
manager_class = hook_handle(('reprocess_manager', media_type))
if not manager_class:
raise ProcessingManagerDoesNotExist(
- "A processing manager does not exist for {}".format(media_type))
+ f"A processing manager does not exist for {media_type}")
manager = manager_class()
return manager
@@ -389,7 +389,7 @@ def store_public(entry, keyname, local_file, target_name=None,
try:
mgg.public_store.copy_local_to_storage(local_file, target_filepath)
except Exception as e:
- _log.error('Exception happened: {}'.format(e))
+ _log.error(f'Exception happened: {e}')
raise PublicStoreFail(keyname=keyname)
# raise an error if the file failed to copy
if not mgg.public_store.file_exists(target_filepath):
diff --git a/mediagoblin/processing/task.py b/mediagoblin/processing/task.py
index 9951c756..9e4efad1 100644
--- a/mediagoblin/processing/task.py
+++ b/mediagoblin/processing/task.py
@@ -38,7 +38,7 @@ def handle_push_urls(feed_url):
Retry 3 times every 2 minutes if run in separate process before failing."""
if not mgg.app_config["push_urls"]:
return # Nothing to do
- _log.debug('Notifying Push servers for feed {}'.format(feed_url))
+ _log.debug(f'Notifying Push servers for feed {feed_url}')
hubparameters = {
'hub.mode': 'publish',
'hub.url': feed_url}
@@ -98,7 +98,7 @@ class ProcessMedia(celery.Task):
entry.state = 'processing'
entry.save()
- _log.debug('Processing {}'.format(entry))
+ _log.debug(f'Processing {entry}')
try:
processor.process(**reprocess_info)
diff --git a/mediagoblin/storage/cloudfiles.py b/mediagoblin/storage/cloudfiles.py
index 0785f8a9..74dc75ec 100644
--- a/mediagoblin/storage/cloudfiles.py
+++ b/mediagoblin/storage/cloudfiles.py
@@ -161,7 +161,7 @@ class CloudFilesStorage(StorageInterface):
# and bandwidth usage. So, override this method and use the
# Cloudfile's "send" interface instead.
# TODO: Fixing write() still seems worthwhile though.
- _log.debug('Sending {} to cloudfiles...'.format(filepath))
+ _log.debug(f'Sending {filepath} to cloudfiles...')
with self.get_file(filepath, 'wb') as dest_file:
with open(filename, 'rb') as source_file:
# Copy to storage system in 4096 byte chunks
diff --git a/mediagoblin/submit/forms.py b/mediagoblin/submit/forms.py
index ac605c73..9e29ffcf 100644
--- a/mediagoblin/submit/forms.py
+++ b/mediagoblin/submit/forms.py
@@ -27,7 +27,7 @@ def get_submit_start_form(form, **kwargs):
max_file_size = kwargs.get('max_file_size')
desc = None
if max_file_size:
- desc = _('Max file size: {} mb'.format(max_file_size))
+ desc = _(f'Max file size: {max_file_size} mb')
class SubmitStartForm(wtforms.Form):
file = wtforms.FileField(
diff --git a/mediagoblin/submit/lib.py b/mediagoblin/submit/lib.py
index 6580a6c1..fcbee185 100644
--- a/mediagoblin/submit/lib.py
+++ b/mediagoblin/submit/lib.py
@@ -161,7 +161,7 @@ def submit_media(mg_app, user, submitted_file, filename,
# Get file size and round to 2 decimal places
file_size = mg_app.queue_store.get_file_size(
entry.queued_media_file) / (1024.0 * 1024)
- file_size = float('{:.2f}'.format(file_size))
+ file_size = float(f'{file_size:.2f}')
# Check if file size is over the limit
if max_file_size and file_size >= max_file_size:
diff --git a/mediagoblin/tests/test_api.py b/mediagoblin/tests/test_api.py
index 5f688857..f987ddc8 100644
--- a/mediagoblin/tests/test_api.py
+++ b/mediagoblin/tests/test_api.py
@@ -55,7 +55,7 @@ class TestAPI:
with self.mock_oauth():
response = test_app.post(
- "/api/user/{}/feed".format(self.active_user.username),
+ f"/api/user/{self.active_user.username}/feed",
json.dumps(activity),
headers=headers
)
@@ -75,7 +75,7 @@ class TestAPI:
with self.mock_oauth():
response = test_app.post(
- "/api/user/{}/uploads".format(self.active_user.username),
+ f"/api/user/{self.active_user.username}/uploads",
data,
headers=headers
)
@@ -192,7 +192,7 @@ class TestAPI:
# Will be self.user trying to upload as self.other_user
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/uploads".format(self.other_user.username),
+ f"/api/user/{self.other_user.username}/uploads",
data,
headers=headers
)
@@ -215,7 +215,7 @@ class TestAPI:
with self.mock_oauth():
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/feed".format(self.other_user.username),
+ f"/api/user/{self.other_user.username}/feed",
json.dumps(activity),
headers=headers
)
@@ -250,7 +250,7 @@ class TestAPI:
with self.mock_oauth():
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/feed".format(self.user.username),
+ f"/api/user/{self.user.username}/feed",
json.dumps(activity),
headers=headers
)
@@ -277,7 +277,7 @@ class TestAPI:
with self.mock_oauth():
response = test_app.post(
- "/api/user/{}/feed".format(self.user.username),
+ f"/api/user/{self.user.username}/feed",
json.dumps(activity),
headers={"Content-Type": "application/json"}
)
@@ -311,7 +311,7 @@ class TestAPI:
with self.mock_oauth():
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/uploads".format(self.user.username),
+ f"/api/user/{self.user.username}/uploads",
data,
headers=headers
)
@@ -406,7 +406,7 @@ class TestAPI:
with self.mock_oauth():
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/feed".format(self.other_user.username),
+ f"/api/user/{self.other_user.username}/feed",
json.dumps(activity),
headers=headers
)
@@ -452,7 +452,7 @@ class TestAPI:
with self.mock_oauth():
with pytest.raises(AppError) as excinfo:
test_app.post(
- "/api/user/{}/feed".format(self.user.username),
+ f"/api/user/{self.user.username}/feed",
json.dumps(activity),
headers=headers
)
@@ -461,7 +461,7 @@ class TestAPI:
def test_profile(self, test_app):
""" Tests profile endpoint """
- uri = "/api/user/{}/profile".format(self.user.username)
+ uri = f"/api/user/{self.user.username}/profile"
with self.mock_oauth():
response = test_app.get(uri)
profile = json.loads(response.body.decode())
@@ -475,7 +475,7 @@ class TestAPI:
def test_user(self, test_app):
""" Test the user endpoint """
- uri = "/api/user/{}/".format(self.user.username)
+ uri = f"/api/user/{self.user.username}/"
with self.mock_oauth():
response = test_app.get(uri)
user = json.loads(response.body.decode())
@@ -501,7 +501,7 @@ class TestAPI:
response, image_data = self._upload_image(test_app, GOOD_JPG)
response, data = self._post_image_to_feed(test_app, image_data)
- uri = "/api/user/{}/feed".format(self.active_user.username)
+ uri = f"/api/user/{self.active_user.username}/feed"
with self.mock_oauth():
response = test_app.get(uri)
feed = json.loads(response.body.decode())
@@ -574,7 +574,7 @@ class TestAPI:
self.active_user = self.other_user
# Fetch the feed
- url = "/api/user/{}/feed".format(self.user.username)
+ url = f"/api/user/{self.user.username}/feed"
with self.mock_oauth():
response = test_app.get(url)
feed = json.loads(response.body.decode())
diff --git a/mediagoblin/tests/test_auth.py b/mediagoblin/tests/test_auth.py
index c5218050..30d7b301 100644
--- a/mediagoblin/tests/test_auth.py
+++ b/mediagoblin/tests/test_auth.py
@@ -164,7 +164,7 @@ def test_register_views(test_app):
## Verify the email activation works
template.clear_test_template_context()
- response = test_app.get("{}?{}".format(path, get_params))
+ response = test_app.get(f"{path}?{get_params}")
response.follow()
context = template.TEMPLATE_TEST_CONTEXT[
'mediagoblin/user_pages/user.html']
@@ -230,7 +230,7 @@ def test_register_views(test_app):
## Verify step 1 of password-change works -- can see form to change password
template.clear_test_template_context()
- response = test_app.get("{}?{}".format(path, get_params))
+ response = test_app.get(f"{path}?{get_params}")
assert 'mediagoblin/plugins/basic_auth/change_fp.html' in \
template.TEMPLATE_TEST_CONTEXT
diff --git a/mediagoblin/tests/test_edit.py b/mediagoblin/tests/test_edit.py
index 1593fa5d..e8780451 100644
--- a/mediagoblin/tests/test_edit.py
+++ b/mediagoblin/tests/test_edit.py
@@ -168,7 +168,7 @@ class TestUserEdit:
# Verify email activation works
template.clear_test_template_context()
get_params = urlparse.urlsplit(email_context['verification_url'])[3]
- res = test_app.get('{}?{}'.format(path, get_params))
+ res = test_app.get(f'{path}?{get_params}')
res.follow()
# New email saved?
diff --git a/mediagoblin/tests/test_exif.py b/mediagoblin/tests/test_exif.py
index 0074e862..38fbd467 100644
--- a/mediagoblin/tests/test_exif.py
+++ b/mediagoblin/tests/test_exif.py
@@ -28,7 +28,7 @@ from .resources import GOOD_JPG, EMPTY_JPG, BAD_JPG, GPS_JPG, BAD_GPS_JPG
def assert_in(a, b):
- assert a in b, "{!r} not in {!r}".format(a, b)
+ assert a in b, f"{a!r} not in {b!r}"
def test_exif_extraction():
diff --git a/mediagoblin/tests/test_moderation.py b/mediagoblin/tests/test_moderation.py
index c262a768..222f6cb7 100644
--- a/mediagoblin/tests/test_moderation.py
+++ b/mediagoblin/tests/test_moderation.py
@@ -69,7 +69,7 @@ class TestModerationViews:
# First, test an admin taking away a privilege from a user
#----------------------------------------------------------------------
response, context = self.do_post({'privilege_name':'commenter'},
- url='/mod/users/{}/privilege/'.format(self.user.username))
+ url=f'/mod/users/{self.user.username}/privilege/')
assert response.status == '302 FOUND'
self.query_for_users()
assert not self.user.has_privilege('commenter')
@@ -77,7 +77,7 @@ class TestModerationViews:
# Then, test an admin giving a privilege to a user
#----------------------------------------------------------------------
response, context = self.do_post({'privilege_name':'commenter'},
- url='/mod/users/{}/privilege/'.format(self.user.username))
+ url=f'/mod/users/{self.user.username}/privilege/')
assert response.status == '302 FOUND'
self.query_for_users()
assert self.user.has_privilege('commenter')
@@ -90,7 +90,7 @@ class TestModerationViews:
with pytest.raises(AppError) as excinfo:
response, context = self.do_post({'privilege_name':'commenter'},
- url='/mod/users/{}/privilege/'.format(self.user.username))
+ url=f'/mod/users/{self.user.username}/privilege/')
assert 'Bad response: 403 FORBIDDEN' in str(excinfo)
self.query_for_users()
@@ -116,7 +116,7 @@ class TestModerationViews:
response, context = self.do_post({'action_to_resolve':['takeaway'],
'take_away_privileges':['commenter'],
'targeted_user':self.user.id},
- url='/mod/reports/{}/'.format(comment_report.id))
+ url=f'/mod/reports/{comment_report.id}/')
self.query_for_users()
comment_report = Report.query.filter(
@@ -137,7 +137,7 @@ class TestModerationViews:
response, context = self.do_post({'action_to_resolve':['sendmessage'],
'message_to_user':'This is your last warning, regular....',
'targeted_user':self.user.id},
- url='/mod/reports/{}/'.format(comment_report.id))
+ url=f'/mod/reports/{comment_report.id}/')
self.query_for_users()
comment_report = Report.query.filter(
@@ -175,7 +175,7 @@ VGhpcyBpcyB5b3VyIGxhc3Qgd2FybmluZywgcmVndWxhci4uLi4=\n',
'targeted_user':self.user.id,
'why_user_was_banned':'',
'user_banned_until':''},
- url='/mod/reports/{}/'.format(comment_report.id))
+ url=f'/mod/reports/{comment_report.id}/')
assert response.status == '302 FOUND'
self.query_for_users()
test_user_ban = UserBan.query.filter(
@@ -196,7 +196,7 @@ VGhpcyBpcyB5b3VyIGxhc3Qgd2FybmluZywgcmVndWxhci4uLi4=\n',
response, context = self.do_post({'action_to_resolve':['takeaway'],
'take_away_privileges':['active'],
'targeted_user':self.admin_user.id},
- url='/mod/reports/{}/'.format(comment_report.id))
+ url=f'/mod/reports/{comment_report.id}/')
self.query_for_users()
assert response.status == '200 OK'
@@ -216,7 +216,7 @@ VGhpcyBpcyB5b3VyIGxhc3Qgd2FybmluZywgcmVndWxhci4uLi4=\n',
response = self.test_app.get('/mod/users/')
assert response.status == "200 OK"
- user_page_url = '/mod/users/{}/'.format(username)
+ user_page_url = f'/mod/users/{username}/'
response = self.test_app.get(user_page_url)
assert response.status == "200 OK"
@@ -227,7 +227,7 @@ VGhpcyBpcyB5b3VyIGxhc3Qgd2FybmluZywgcmVndWxhci4uLi4=\n',
self.login('admin')
username = self.user.username
user_id = self.user.id
- ban_url = '/mod/users/{}/ban/'.format(username)
+ ban_url = f'/mod/users/{username}/ban/'
response, context = self.do_post({
'user_banned_until':'',
'why_user_was_banned':'Because I said so'},
diff --git a/mediagoblin/tests/test_notifications.py b/mediagoblin/tests/test_notifications.py
index d19f2951..acba954d 100644
--- a/mediagoblin/tests/test_notifications.py
+++ b/mediagoblin/tests/test_notifications.py
@@ -147,7 +147,7 @@ otherperson@example.com\n\nSGkgb3RoZXJwZXJzb24sCmNocmlzIGNvbW1lbnRlZCBvbiB5b3VyI
self.logout()
self.login('otherperson', 'nosreprehto')
- self.test_app.get(media_uri_slug + 'c/{}/'.format(comment_id))
+ self.test_app.get(media_uri_slug + f'c/{comment_id}/')
notification = Notification.query.filter_by(id=notification_id).first()
diff --git a/mediagoblin/tests/test_oauth1.py b/mediagoblin/tests/test_oauth1.py
index 345b308e..25f7c0d3 100644
--- a/mediagoblin/tests/test_oauth1.py
+++ b/mediagoblin/tests/test_oauth1.py
@@ -123,7 +123,7 @@ class TestOAuth:
def to_authorize_headers(self, data):
headers = ""
for key, value in data.items():
- headers += '{}="{}",'.format(key, value)
+ headers += f'{key}="{value}",'
return {"Authorization": "OAuth " + headers[:-1]}
def test_request_token(self):
diff --git a/mediagoblin/tests/test_reporting.py b/mediagoblin/tests/test_reporting.py
index 81dc1d89..8dfb1a41 100644
--- a/mediagoblin/tests/test_reporting.py
+++ b/mediagoblin/tests/test_reporting.py
@@ -143,7 +143,7 @@ class TestReportFiling:
{'action_to_resolve':['userban', 'delete'],
'targeted_user':allie_user.id,
'resolution_content':'This is a test of archiving reports.'},
- url='/mod/reports/{}/'.format(comment_report.id))
+ url=f'/mod/reports/{comment_report.id}/')
assert response.status == "302 FOUND"
allie_user, natalie_user = self.query_for_users()
diff --git a/mediagoblin/tests/test_submission.py b/mediagoblin/tests/test_submission.py
index 2f5a2712..348ed03a 100644
--- a/mediagoblin/tests/test_submission.py
+++ b/mediagoblin/tests/test_submission.py
@@ -173,7 +173,7 @@ class BaseTestSubmission:
def check_normal_upload(self, title, filename):
response, context = self.do_post({'title': title}, do_follow=True,
**self.upload_data(filename))
- self.check_url(response, '/u/{}/'.format(self.our_user().username))
+ self.check_url(response, f'/u/{self.our_user().username}/')
assert 'mediagoblin/user_pages/user.html' in context
# Make sure the media view is at least reachable, logged in...
url = '/u/{}/m/{}/'.format(self.our_user().username,
@@ -215,7 +215,7 @@ class TestSubmissionBasics(BaseTestSubmission):
# User uploaded should be the same as GOOD_JPG size in Mb
file_size = os.stat(GOOD_JPG).st_size / (1024.0 * 1024)
- file_size = float('{:.2f}'.format(file_size))
+ file_size = float(f'{file_size:.2f}')
# Reload user
assert self.our_user().uploaded == file_size
@@ -242,7 +242,7 @@ class TestSubmissionBasics(BaseTestSubmission):
response, context = self.do_post({'title': 'Normal upload 4'},
do_follow=True,
**self.upload_data(GOOD_JPG))
- self.check_url(response, '/u/{}/'.format(self.our_user().username))
+ self.check_url(response, f'/u/{self.our_user().username}/')
assert 'mediagoblin/user_pages/user.html' in context
# Shouldn't have uploaded
@@ -257,7 +257,7 @@ class TestSubmissionBasics(BaseTestSubmission):
response, context = self.do_post({'title': 'Normal upload 5'},
do_follow=True,
**self.upload_data(GOOD_JPG))
- self.check_url(response, '/u/{}/'.format(self.our_user().username))
+ self.check_url(response, f'/u/{self.our_user().username}/')
assert 'mediagoblin/user_pages/user.html' in context
# Shouldn't have uploaded
@@ -421,7 +421,7 @@ class TestSubmissionBasics(BaseTestSubmission):
# they'll be caught as failures during the processing step.
response, context = self.do_post({'title': title}, do_follow=True,
**self.upload_data(filename))
- self.check_url(response, '/u/{}/'.format(self.our_user().username))
+ self.check_url(response, f'/u/{self.our_user().username}/')
entry = mg_globals.database.MediaEntry.query.filter_by(title=title).first()
assert entry.state == 'failed'
assert entry.fail_error == 'mediagoblin.processing:BadMediaFail'
@@ -583,7 +583,7 @@ class TestSubmissionVideo(BaseTestSubmission):
assert len(result) == len(video_config['available_resolutions'])
for i in range(len(video_config['available_resolutions'])):
media_file = MediaFile.query.filter_by(media_entry=media.id,
- name=('webm_{}'.format(str(result[i][0])))).first()
+ name=(f'webm_{str(result[i][0])}')).first()
# check media_file label
assert result[i][0] == video_config['available_resolutions'][i]
# check dimensions of media_file
@@ -771,6 +771,6 @@ class TestSubmissionPDF(BaseTestSubmission):
response, context = self.do_post({'title': 'Normal upload 3 (pdf)'},
do_follow=True,
**self.upload_data(GOOD_PDF))
- self.check_url(response, '/u/{}/'.format(self.our_user().username))
+ self.check_url(response, f'/u/{self.our_user().username}/')
assert 'mediagoblin/user_pages/user.html' in context
diff --git a/mediagoblin/tools/pluginapi.py b/mediagoblin/tools/pluginapi.py
index be125a0e..9f74b252 100644
--- a/mediagoblin/tools/pluginapi.py
+++ b/mediagoblin/tools/pluginapi.py
@@ -128,7 +128,7 @@ class PluginManager:
def register_route(self, route):
"""Registers a single route"""
- _log.debug('registering route: {}'.format(route))
+ _log.debug(f'registering route: {route}')
self.routes.append(route)
def get_routes(self):
diff --git a/mediagoblin/tools/processing.py b/mediagoblin/tools/processing.py
index aa086a30..f9efeba7 100644
--- a/mediagoblin/tools/processing.py
+++ b/mediagoblin/tools/processing.py
@@ -47,7 +47,7 @@ def json_processing_callback(entry):
Send an HTTP post to the registered callback url, if any.
'''
if not entry.processing_metadata:
- _log.debug('No processing callback URL for {}'.format(entry))
+ _log.debug(f'No processing callback URL for {entry}')
return
url = entry.processing_metadata[0].callback_url
@@ -76,7 +76,7 @@ def json_processing_callback(entry):
try:
request.urlopen(request)
- _log.debug('Processing callback for {} sent'.format(entry))
+ _log.debug(f'Processing callback for {entry} sent')
return True
except request.HTTPError:
diff --git a/mediagoblin/tools/response.py b/mediagoblin/tools/response.py
index eb9d4e6f..3e175873 100644
--- a/mediagoblin/tools/response.py
+++ b/mediagoblin/tools/response.py
@@ -105,7 +105,7 @@ def render_http_exception(request, exc, description):
elif stock_desc and exc.code == 404:
return render_404(request)
- return render_error(request, title='{} {}'.format(exc.code, exc.name),
+ return render_error(request, title=f'{exc.code} {exc.name}',
err_msg=description,
status=exc.code)
diff --git a/mediagoblin/tools/routing.py b/mediagoblin/tools/routing.py
index ebd2c08e..c06dfb00 100644
--- a/mediagoblin/tools/routing.py
+++ b/mediagoblin/tools/routing.py
@@ -49,7 +49,7 @@ def endpoint_to_controller(rule):
endpoint = rule.endpoint
view_func = rule.gmg_controller
- _log.debug('endpoint: {} view_func: {}'.format(endpoint, view_func))
+ _log.debug(f'endpoint: {endpoint} view_func: {view_func}')
# import the endpoint, or if it's already a callable, call that
if isinstance(view_func, str):
diff --git a/mediagoblin/tools/translate.py b/mediagoblin/tools/translate.py
index ce4cd4d3..ae1d73cb 100644
--- a/mediagoblin/tools/translate.py
+++ b/mediagoblin/tools/translate.py
@@ -69,10 +69,10 @@ def locale_to_lower_upper(locale):
"""
if '-' in locale:
lang, country = locale.split('-', 1)
- return '{}_{}'.format(lang.lower(), country.upper())
+ return f'{lang.lower()}_{country.upper()}'
elif '_' in locale:
lang, country = locale.split('_', 1)
- return '{}_{}'.format(lang.lower(), country.upper())
+ return f'{lang.lower()}_{country.upper()}'
else:
return locale.lower()
@@ -83,7 +83,7 @@ def locale_to_lower_lower(locale):
"""
if '_' in locale:
lang, country = locale.split('_', 1)
- return '{}-{}'.format(lang.lower(), country.lower())
+ return f'{lang.lower()}-{country.lower()}'
else:
return locale.lower()