From c18b3b75cf7994661e2976e0af35df14f8231056 Mon Sep 17 00:00:00 2001 From: Bomme <13520622+Bomme@users.noreply.github.com> Date: Thu, 2 Feb 2023 20:37:51 +0100 Subject: [PATCH] pyupgrade: automatic removal of Python2 code pyupgrade --py3-plus --keep-percent-format I excluded tagrecommendation, similarity and clustering (For the latter I didn't know if Py2 should still be supported) I tweaked some small changes by hand --- .../add_examples_to_api_docs_source_files.py | 3 +- .../generate_analysis_rst.py | 2 - _docs/api/source/conf.py | 9 +- accounts/admin.py | 36 +++-- accounts/forms.py | 41 +++--- accounts/management/__init__.py | 1 - accounts/management/commands/__init__.py | 1 - .../commands/clean_old_tmp_upload_files.py | 1 - accounts/migrations/0001_initial.py | 2 - .../0002_profile_is_deleted_user.py | 2 - .../migrations/0003_auto_20160914_1100.py | 2 - accounts/migrations/0004_profile_is_adult.py | 2 - ...05_emailpreferencetype_useremailsetting.py | 2 - .../migrations/0006_copy_email_settings.py | 3 - .../migrations/0007_auto_20170328_1851.py | 2 - .../migrations/0008_auto_20170331_1702.py | 2 - accounts/migrations/0009_sameuser.py | 2 - .../migrations/0010_auto_20170510_0945.py | 2 - .../0011_profile_last_donation_email_sent.py | 2 - ...2_profile_donations_reminder_email_sent.py | 2 - .../0013_profile_sound_signature.py | 2 - accounts/migrations/0014_oldusername.py | 2 - .../migrations/0015_auto_20171129_1537.py | 2 - .../migrations/0016_oldusername_created.py | 2 - .../migrations/0017_auto_20180124_1150.py | 2 - .../0018_sameuser_case_insensitive_emails.py | 3 - accounts/migrations/0019_emailbounce.py | 4 +- accounts/migrations/0019_gdpracceptance.py | 2 - .../0020_deleted_unusuable_password.py | 2 - .../migrations/0020_merge_20180710_1458.py | 2 - .../migrations/0021_auto_20190222_1105.py | 2 - .../migrations/0021_merge_20180712_1536.py | 2 - .../migrations/0022_auto_20190611_1647.py | 2 - accounts/migrations/0023_deleteduser.py | 2 - .../migrations/0024_auto_20190927_1658.py | 2 - accounts/migrations/0025_deleteduser_user.py | 2 - .../migrations/0026_auto_20191010_1437.py | 2 - .../migrations/0027_deleteduser_last_login.py | 2 - .../migrations/0028_auto_20191010_1448.py | 2 - .../migrations/0029_auto_20191010_1509.py | 2 - .../migrations/0030_auto_20191016_1457.py | 2 - .../migrations/0031_auto_20201113_1132.py | 2 - .../migrations/0032_auto_20210409_1344.py | 2 - .../migrations/0033_auto_20210412_0742.py | 2 - .../migrations/0034_auto_20210412_1738.py | 2 - .../migrations/0035_merge_20220317_1204.py | 2 - .../migrations/0036_auto_20230201_1102.py | 2 - accounts/models.py | 17 +-- accounts/templatetags/display_user.py | 1 - accounts/tests/test_profile.py | 15 +-- accounts/tests/test_spam.py | 5 +- accounts/tests/test_upload.py | 91 ++++++------- accounts/tests/test_user.py | 120 ++++++++--------- accounts/tests/test_views.py | 1 - accounts/urls.py | 2 - accounts/views.py | 14 +- apiv2/admin.py | 2 - apiv2/apiv2_utils.py | 44 +++--- apiv2/authentication.py | 4 +- apiv2/combined_search_strategies.py | 6 - apiv2/examples.py | 2 - apiv2/exceptions.py | 3 - apiv2/forms.py | 2 - apiv2/management/commands/basic_api_tests.py | 4 - .../commands/consolidate_api_usage_data.py | 5 +- apiv2/migrations/0001_initial.py | 2 - .../0002_apiv2client_oauth_client.py | 2 - .../0003_remove_apiv2client_scope.py | 2 - apiv2/migrations/0004_auto_20161019_1114.py | 2 - apiv2/migrations/0005_auto_20190222_1105.py | 2 - apiv2/migrations/0006_auto_20201230_1530.py | 4 +- apiv2/migrations/0007_auto_20230201_1102.py | 2 - apiv2/models.py | 8 +- apiv2/oauth2_urls.py | 2 - apiv2/serializers.py | 22 ++- apiv2/tests.py | 10 +- apiv2/throttling.py | 7 +- apiv2/urls.py | 2 - apiv2/views.py | 27 ++-- bookmarks/admin.py | 2 - bookmarks/forms.py | 7 +- bookmarks/migrations/0001_initial.py | 2 - .../migrations/0002_auto_20211214_2013.py | 2 - .../migrations/0003_auto_20230201_1102.py | 2 - bookmarks/models.py | 9 +- bookmarks/tests.py | 6 +- bookmarks/views.py | 5 +- comments/admin.py | 2 - comments/forms.py | 4 +- comments/migrations/0001_initial.py | 2 - comments/migrations/0002_comment_sound.py | 2 - .../migrations/0004_auto_20170627_1721.py | 2 - .../migrations/0005_auto_20170710_1642.py | 2 - comments/models.py | 7 +- comments/urls.py | 2 - donations/admin.py | 1 - donations/forms.py | 7 +- .../commands/check_missing_donations.py | 3 +- .../commands/send_donation_request_emails.py | 1 - donations/migrations/0001_initial.py | 2 - .../migrations/0002_auto_20170116_1704.py | 2 - .../migrations/0003_donationsmodalsettings.py | 2 - ...lsettings_never_show_modal_to_uploaders.py | 2 - .../migrations/0005_donationsemailsettings.py | 2 - .../migrations/0006_auto_20170710_1524.py | 2 - .../0007_donationsemailsettings_enabled.py | 2 - donations/migrations/0008_donation_source.py | 2 - .../migrations/0009_auto_20171002_1710.py | 2 - .../migrations/0010_auto_20171222_1352.py | 2 - donations/models.py | 1 - donations/tests.py | 13 +- donations/urls.py | 2 - donations/views.py | 2 - favorites/admin.py | 2 - favorites/migrations/0001_initial.py | 4 +- favorites/models.py | 7 +- follow/admin.py | 2 - follow/follow_utils.py | 6 +- .../management/commands/send_stream_emails.py | 7 +- follow/migrations/0001_initial.py | 6 +- follow/migrations/0002_auto_20190506_1459.py | 2 - follow/models.py | 11 +- follow/tests.py | 2 - follow/urls.py | 2 - follow/views.py | 1 - forum/admin.py | 2 - forum/forms.py | 6 +- forum/migrations/0001_initial.py | 4 +- forum/migrations/0002_auto_20171127_1627.py | 2 - forum/migrations/0003_auto_20230201_1102.py | 2 - forum/models.py | 13 +- forum/templatetags/display_forum_objects.py | 2 - .../display_forum_search_results.py | 2 - forum/templatetags/smileys.py | 2 +- forum/tests.py | 46 +++---- forum/urls.py | 2 - forum/views.py | 7 +- freesound/__init__.py | 2 - freesound/celery.py | 1 - freesound/local_settings.example.py | 2 - freesound/middleware.py | 11 +- freesound/settings.py | 40 +++--- freesound/urls.py | 2 - general/admin.py | 2 - general/management/commands/build_static.py | 2 +- .../management/commands/clean_data_volume.py | 3 +- .../post_sounds_to_tagrecommendation.py | 1 - general/management/commands/prune_database.py | 2 - .../management/commands/similarity_update.py | 1 - general/migrations/0001_initial.py | 2 - general/models.py | 9 +- general/tasks.py | 1 - general/templatetags/absurl.py | 2 +- general/templatetags/bw_templatetags.py | 3 - general/templatetags/filter_img.py | 1 - general/templatetags/paginator.py | 10 +- general/templatetags/util.py | 4 +- general/tests.py | 4 +- geotags/admin.py | 2 - geotags/migrations/0001_initial.py | 2 - geotags/migrations/0002_auto_20220111_1251.py | 2 - .../migrations/0003_geotag_location_name.py | 2 - geotags/migrations/0004_auto_20230201_1102.py | 2 - geotags/models.py | 4 +- geotags/tests.py | 3 +- geotags/urls.py | 2 - messages/admin.py | 2 - messages/forms.py | 6 +- messages/migrations/0001_initial.py | 2 - messages/models.py | 9 +- messages/templatetags/display_message.py | 2 - messages/tests/test_message_notifications.py | 12 +- messages/tests/test_message_write.py | 6 +- messages/views.py | 2 +- monitor/management/commands/generate_stats.py | 1 - monitor/models.py | 2 - monitor/views.py | 1 - ratings/admin.py | 2 - ratings/migrations/0001_initial.py | 4 +- ratings/migrations/0002_rating_sound.py | 2 - ratings/models.py | 7 +- ratings/urls.py | 2 - ratings/views.py | 1 - search/forms.py | 2 +- .../post_dirty_sounds_to_search_engine.py | 1 - .../commands/reindex_search_engine_forum.py | 1 - search/templatetags/search.py | 9 +- search/tests.py | 5 +- search/views.py | 9 +- sounds/admin.py | 26 ++-- sounds/forms.py | 26 ++-- sounds/management.py | 1 - .../management/commands/check_sound_paths.py | 4 +- .../commands/create_random_sounds.py | 1 - .../commands/create_remix_groups.py | 4 +- .../commands/orchestrate_analysis.py | 7 +- .../management/commands/update_cdn_sounds.py | 1 - sounds/migrations/0001_initial.py | 4 +- sounds/migrations/0002_auto_20160728_1516.py | 2 - sounds/migrations/0003_auto_20160914_1100.py | 2 - .../migrations/0004_deletedsound_created.py | 2 - sounds/migrations/0005_auto_20161004_1500.py | 2 - sounds/migrations/0006_auto_20161005_1533.py | 2 - sounds/migrations/0007_auto_20161018_1809.py | 4 +- sounds/migrations/0008_soundoftheday.py | 2 - sounds/migrations/0009_download_license.py | 2 - sounds/migrations/0010_auto_20170712_1537.py | 2 - sounds/migrations/0011_auto_20170928_1441.py | 2 - sounds/migrations/0012_auto_20171002_1710.py | 2 - sounds/migrations/0013_remove_triggers.py | 2 - sounds/migrations/0014_auto_20171124_1628.py | 2 - ...load_packdownloadjson_packdownloadsound.py | 2 - sounds/migrations/0015_auto_20171124_1651.py | 2 - sounds/migrations/0016_merge_20171201_1822.py | 2 - sounds/migrations/0017_auto_20180117_1553.py | 2 - sounds/migrations/0018_auto_20180209_1540.py | 2 - sounds/migrations/0019_bulkuploadprogress.py | 2 - .../migrations/0019_remove_download_pack.py | 2 - .../0020_update_download_indexes.py | 2 - sounds/migrations/0021_auto_20180320_1554.py | 2 - sounds/migrations/0022_auto_20180321_1048.py | 2 - sounds/migrations/0023_auto_20180322_1129.py | 2 - sounds/migrations/0024_auto_20180503_1326.py | 2 - sounds/migrations/0024_merge_20180403_1616.py | 2 - ...ulkuploadprogress_original_csv_filename.py | 2 - sounds/migrations/0026_auto_20180404_1652.py | 2 - sounds/migrations/0027_auto_20180406_1208.py | 2 - sounds/migrations/0028_auto_20180411_1634.py | 2 - sounds/migrations/0029_merge_20180510_1627.py | 2 - sounds/migrations/0030_auto_20180618_1305.py | 2 - sounds/migrations/0031_soundanalysis.py | 2 - sounds/migrations/0032_auto_20180905_1301.py | 4 +- sounds/migrations/0033_auto_20190528_1554.py | 2 - .../0034_make_latest_index_20190712_1616.py | 2 - sounds/migrations/0035_auto_20190724_1509.py | 2 - ...ound_uploaded_with_bulk_upload_progress.py | 2 - .../migrations/0037_license_short_summary.py | 2 - sounds/migrations/0038_auto_20210412_1539.py | 2 - sounds/migrations/0039_auto_20210607_1404.py | 2 - sounds/migrations/0040_auto_20220207_1627.py | 4 +- .../0041_soundanalysis_analysis_time.py | 2 - sounds/migrations/0042_auto_20220209_1027.py | 2 - sounds/migrations/0043_auto_20220209_1027.py | 2 - sounds/migrations/0044_auto_20220209_1136.py | 4 +- sounds/migrations/0045_add_new_licenses.py | 2 - sounds/migrations/0046_auto_20230201_1102.py | 2 - sounds/models.py | 31 ++--- sounds/templatetags/display_pack.py | 1 - sounds/templatetags/display_remix.py | 2 - sounds/templatetags/display_sound.py | 1 - sounds/templatetags/sound_signature.py | 1 - sounds/tests/test_manager.py | 9 +- sounds/tests/test_sound.py | 56 ++++---- sounds/views.py | 13 +- support/admin.py | 1 - support/models.py | 1 - support/tests.py | 4 +- support/views.py | 1 - tags/admin.py | 2 - tags/migrations/0001_initial.py | 4 +- tags/models.py | 9 +- tags/tests.py | 1 - tickets/admin.py | 3 - tickets/forms.py | 4 +- tickets/migrations/0001_initial.py | 2 - tickets/migrations/0002_auto_20160505_1202.py | 2 - tickets/migrations/0003_ticket_sound.py | 2 - tickets/migrations/0004_copy.py | 3 - tickets/migrations/0005_auto_20160608_1546.py | 2 - .../migrations/0006_remove_ticket_source.py | 2 - tickets/migrations/0007_auto_20170626_1755.py | 2 - .../migrations/0008_copy_message_to_ticket.py | 2 - tickets/migrations/0009_auto_20190528_1554.py | 2 - tickets/models.py | 12 +- tickets/tests.py | 27 ++-- tickets/urls.py | 2 - tickets/views.py | 1 - utils/audioprocessing/color_schemes.py | 3 - utils/audioprocessing/convert_to_mp3.py | 1 - utils/audioprocessing/convert_to_wav.py | 2 - .../freesound_audio_processing.py | 8 +- utils/audioprocessing/processing.py | 17 +-- utils/audioprocessing/wav2png.py | 3 - utils/aws.py | 3 +- utils/dbtime.py | 3 +- utils/downloads.py | 1 - utils/encryption.py | 1 - utils/filesystem.py | 5 +- utils/forms.py | 6 +- utils/images.py | 1 - utils/locations.py | 4 +- utils/logging_filters.py | 1 - utils/mail.py | 5 +- utils/management_commands.py | 4 +- utils/mirror_files.py | 3 +- utils/nginxsendfile.py | 4 +- utils/pagination.py | 2 +- utils/paypal/wrapper.py | 8 +- utils/ratelimit.py | 1 - utils/search/__init__.py | 9 +- utils/search/backends/solr555pysolr.py | 9 +- utils/search/backends/solr_common.py | 10 +- .../backends/test_search_engine_backend.py | 1 - utils/search/lucene_parser.py | 10 +- utils/search/search_forum.py | 1 - utils/search/search_sounds.py | 1 - utils/similarity_utilities.py | 1 - utils/sound_upload.py | 11 +- utils/tagrecommendation_utilities.py | 1 - utils/test_helpers.py | 2 - utils/tests/test_forms.py | 2 - utils/tests/test_logging_filters.py | 4 +- utils/tests/test_pagination.py | 1 - utils/tests/test_processing.py | 6 +- utils/tests/test_search_general.py | 43 +++--- utils/tests/test_text.py | 126 +++++++++--------- utils/tests/tests.py | 1 - utils/text.py | 8 +- wiki/admin.py | 2 - wiki/forms.py | 5 +- wiki/migrations/0001_initial.py | 2 - wiki/models.py | 5 +- wiki/urls.py | 2 - 323 files changed, 593 insertions(+), 1211 deletions(-) diff --git a/_docs/api/add_examples_to_api_docs_source_files.py b/_docs/api/add_examples_to_api_docs_source_files.py index f1696b9e0e..fb7fd6c739 100644 --- a/_docs/api/add_examples_to_api_docs_source_files.py +++ b/_docs/api/add_examples_to_api_docs_source_files.py @@ -1,4 +1,3 @@ -from __future__ import print_function from future import standard_library standard_library.install_aliases() import sys @@ -28,7 +27,7 @@ def get_formatted_examples_for_view(view_name): return output -with open('source/resources.rst', 'r') as f: +with open('source/resources.rst') as f: newlines = [] for line in f.readlines(): if '{{examples_' in line: diff --git a/_docs/api/generate_analysis_documentation/generate_analysis_rst.py b/_docs/api/generate_analysis_documentation/generate_analysis_rst.py index 164abbe03d..72f9bd48ee 100644 --- a/_docs/api/generate_analysis_documentation/generate_analysis_rst.py +++ b/_docs/api/generate_analysis_documentation/generate_analysis_rst.py @@ -1,11 +1,9 @@ # Generate skeleton for documentation, # add essentia documentation links by hand -from __future__ import print_function from future import standard_library standard_library.install_aliases() -from builtins import range import urllib.request, urllib.error, urllib.parse,json diff --git a/_docs/api/source/conf.py b/_docs/api/source/conf.py index d40372c7f6..514c4f9c49 100644 --- a/_docs/api/source/conf.py +++ b/_docs/api/source/conf.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound API documentation build configuration file, created by # sphinx-quickstart on Mon Sep 6 11:41:46 2010. @@ -37,8 +36,8 @@ master_doc = 'index' # General information about the project. -project = u'Freesound API' -copyright = u'2014, Universitat Pompeu Fabra' +project = 'Freesound API' +copyright = '2014, Universitat Pompeu Fabra' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the @@ -172,8 +171,8 @@ # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ - ('index', 'FreesoundAPI.tex', u'Freesound API Documentation', - u'Vincent Akkermans, Bram de Jong', 'manual'), + ('index', 'FreesoundAPI.tex', 'Freesound API Documentation', + 'Vincent Akkermans, Bram de Jong', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of diff --git a/accounts/admin.py b/accounts/admin.py index aa58850da5..59ad9b67c9 100644 --- a/accounts/admin.py +++ b/accounts/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -64,9 +62,9 @@ class DeletedUserAdmin(admin.ModelAdmin): search_fields = ('=username',) def get_object_link(self, obj): - return '{1}'.format( + return '{}'.format( reverse('admin:accounts_deleteduser_change', args=[obj.id]), - 'DeletedUser: {0}'.format(obj.username)) + 'DeletedUser: {}'.format(obj.username)) get_object_link.short_description = 'DeletedUser' get_object_link.allow_tags = True get_object_link.admin_order_field = 'username' @@ -75,13 +73,13 @@ def get_view_link(self, obj): if obj.user is None: return '-' else: - return '{1}'.format( + return '{}'.format( reverse('account', args=[obj.user.username]), obj.user.username) get_view_link.short_description = 'View on site' get_view_link.allow_tags = True def get_num_sounds(self, obj): - return '{0}'.format(obj.profile.num_sounds) + return '{}'.format(obj.profile.num_sounds) get_num_sounds.short_description = '# sounds' @@ -148,7 +146,7 @@ class FreesoundUserAdmin(DjangoObjectActions, UserAdmin): def get_queryset(self, request): # Override 'get_queryset' to optimize query by using select_related on appropriate fields - qs = super(FreesoundUserAdmin, self).get_queryset(request) + qs = super().get_queryset(request) qs = qs.select_related('profile') return qs @@ -158,22 +156,22 @@ def has_delete_permission(self, request, obj=None): return False def get_view_link(self, obj): - return '{1}'.format( + return '{}'.format( reverse('account', args=[obj.username]), obj.username) get_view_link.short_description = 'View on site' get_view_link.allow_tags = True def get_num_sounds(self, obj): - return '{0}'.format(obj.profile.num_sounds) + return '{}'.format(obj.profile.num_sounds) get_num_sounds.short_description = '# sounds' def get_num_posts(self, obj): - return '{0}'.format(obj.profile.num_posts) + return '{}'.format(obj.profile.num_posts) get_num_posts.short_description = '# posts' def get_actions(self, request): # Disable the "delete" action in the list - actions = super(FreesoundUserAdmin, self).get_actions(request) + actions = super().get_actions(request) if 'delete_selected' in actions: del actions['delete_selected'] return actions @@ -183,7 +181,7 @@ def delete_preserve_sounds(self, request, obj): if request.method == "POST": delete_action = tasks.DELETE_USER_KEEP_SOUNDS_ACTION_NAME delete_reason = DeletedUser.DELETION_REASON_DELETED_BY_ADMIN - web_logger.info('Requested async deletion of user {0} - {1}'.format(obj.id, delete_action)) + web_logger.info('Requested async deletion of user {} - {}'.format(obj.id, delete_action)) # Create a UserDeletionRequest with a status of 'Deletion action was triggered' UserDeletionRequest.objects.create(user_from=request.user, @@ -215,7 +213,7 @@ def delete_include_sounds(self, request, obj): if request.method == "POST": delete_action = tasks.DELETE_USER_DELETE_SOUNDS_ACTION_NAME delete_reason = DeletedUser.DELETION_REASON_DELETED_BY_ADMIN - web_logger.info('Requested async deletion of user {0} - {1}'.format(obj.id, delete_action)) + web_logger.info('Requested async deletion of user {} - {}'.format(obj.id, delete_action)) # Create a UserDeletionRequest with a status of 'Deletion action was triggered' UserDeletionRequest.objects.create(user_from=request.user, @@ -253,7 +251,7 @@ def delete_spammer(self, request, obj): if request.method == "POST": delete_action = tasks.DELETE_SPAMMER_USER_ACTION_NAME delete_reason = DeletedUser.DELETION_REASON_SPAMMER - web_logger.info('Requested async deletion of user {0} - {1}'.format(obj.id, delete_action)) + web_logger.info('Requested async deletion of user {} - {}'.format(obj.id, delete_action)) # Create a UserDeletionRequest with a status of 'Deletion action was triggered' UserDeletionRequest.objects.create(user_from=request.user, @@ -290,7 +288,7 @@ def full_delete(self, request, obj): if request.method == "POST": delete_action = tasks.FULL_DELETE_USER_ACTION_NAME delete_reason = DeletedUser.DELETION_REASON_DELETED_BY_ADMIN - web_logger.info('Requested async deletion of user {0} - {1}'.format(obj.id, delete_action)) + web_logger.info('Requested async deletion of user {} - {}'.format(obj.id, delete_action)) # Create a UserDeletionRequest with a status of 'Deletion action was triggered' UserDeletionRequest.objects.create(user_from=request.user, @@ -373,16 +371,16 @@ class UserDeletionRequestAdmin(admin.ModelAdmin): def get_queryset(self, request): # Override 'get_queryset' to optimize query by using select_related on appropriate fields - qs = super(UserDeletionRequestAdmin, self).get_queryset(request) + qs = super().get_queryset(request) qs = qs.select_related('user_from', 'deleted_user', 'user_to') return qs def deleted_user_link(self, obj): if obj.deleted_user is None: return '-' - return '{1}'.format( + return '{}'.format( reverse('admin:accounts_deleteduser_change', args=[obj.deleted_user_id]), - 'DeletedUser: {0}'.format(obj.deleted_user.username)) + 'DeletedUser: {}'.format(obj.deleted_user.username)) deleted_user_link.allow_tags = True deleted_user_link.admin_order_field = 'deleted_user' @@ -391,7 +389,7 @@ def deleted_user_link(self, obj): def user_to_link(self, obj): if obj.user_to is None: return '-' - return '{1}'.format( + return '{}'.format( reverse('admin:auth_user_change', args=[obj.user_to_id]), obj.user_to.username) user_to_link.allow_tags = True diff --git a/accounts/forms.py b/accounts/forms.py index 6226305cab..88ca9b32ab 100644 --- a/accounts/forms.py +++ b/accounts/forms.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -21,8 +20,6 @@ import logging -from builtins import object -from builtins import str from captcha.fields import ReCaptchaField from django import forms from django.conf import settings @@ -122,7 +119,7 @@ class TermsOfServiceForm(forms.Form): class TermsOfServiceFormBW(TermsOfServiceForm): def __init__(self, *args, **kwargs): - super(TermsOfServiceFormBW, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['accepted_tos'].widget.attrs['class'] = 'bw-checkbox' self.fields['accepted_license_change'].widget.attrs['class'] = 'bw-checkbox' @@ -148,7 +145,7 @@ class FileChoiceForm(forms.Form): files = forms.MultipleChoiceField() def __init__(self, files, *args, **kwargs): - super(FileChoiceForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) choices = list(files.items()) self.fields['files'].choices = choices @@ -160,7 +157,7 @@ def get_user_by_email(email): class UsernameField(forms.CharField): """ Username field, 3~30 characters, allows only alphanumeric chars, required by default """ def __init__(self, required=True): - super(UsernameField, self).__init__( + super().__init__( label="Username", min_length=3, max_length=30, @@ -236,7 +233,7 @@ def clean_email1(self): return email1 def clean(self): - cleaned_data = super(RegistrationForm, self).clean() + cleaned_data = super().clean() return cleaned_data def save(self): @@ -261,7 +258,7 @@ class BwRegistrationForm(RegistrationForm): def __init__(self, *args, **kwargs): kwargs.update(dict(auto_id='id_%s_registration')) kwargs.update(dict(label_suffix='')) - super(BwRegistrationForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Customize some placeholders and classes, remove labels and help texts self.fields['username'].label = False @@ -289,14 +286,14 @@ class BwProblemsLoggingInForm(forms.Form): username_or_email = forms.CharField(label="", help_text="", max_length=254) def __init__(self, *args, **kwargs): - super(BwProblemsLoggingInForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['username_or_email'].widget.attrs['placeholder'] = 'Your email or username' class FsAuthenticationForm(AuthenticationForm): def __init__(self, *args, **kwargs): - super(FsAuthenticationForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.error_messages.update({ 'inactive': mark_safe("You are trying to log in with an inactive account, please activate " "your account first." % reverse("accounts-resend-activation")), @@ -309,7 +306,7 @@ def __init__(self, *args, **kwargs): class BwFsAuthenticationForm(FsAuthenticationForm): def __init__(self, *args, **kwargs): - super(BwFsAuthenticationForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Customize form placeholders and remove labels self.fields['username'].label = False @@ -356,7 +353,7 @@ def __init__(self, request, *args, **kwargs): kwargs.update(initial={ 'username': request.user.username }) - super(ProfileForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.n_times_changed_username = OldUsername.objects.filter(user_id=self.request.user.id).count() if self.n_times_changed_username < 1: @@ -422,7 +419,7 @@ def clean_sound_signature(self): return sound_signature - class Meta(object): + class Meta: model = Profile fields = ('home_page', 'about', 'signature', 'sound_signature', 'is_adult', 'not_shown_in_online_users_list', ) @@ -437,7 +434,7 @@ class BwProfileForm(ProfileForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwProfileForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Customize some placeholders and classes, remove labels and help texts self.fields['username'].widget.attrs['placeholder'] = 'Write your name here (30 characters maximum)' @@ -465,7 +462,7 @@ def __init__(self, *args, **kwargs): self.fields['is_adult'].help_text = False self.fields['not_shown_in_online_users_list'].widget = forms.HiddenInput() - class Meta(object): + class Meta: model = Profile fields = ('username', 'home_page', 'about', 'signature', 'sound_signature', 'is_adult', ) @@ -477,7 +474,7 @@ class EmailResetForm(forms.Form): def __init__(self, *args, **kwargs): # Using init function to pass user variable so later we can perform check_password in clean_password function self.user = kwargs.pop('user', None) - super(EmailResetForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_password(self): if not self.user.check_password(self.cleaned_data["password"]): @@ -485,8 +482,8 @@ def clean_password(self): return self.cleaned_data['password'] -DELETE_CHOICES = [('only_user', mark_safe(u'Delete only my user account information')), - ('delete_sounds', mark_safe(u'Delete my user account information, my sounds and packs'))] +DELETE_CHOICES = [('only_user', mark_safe('Delete only my user account information')), + ('delete_sounds', mark_safe('Delete my user account information, my sounds and packs'))] class DeleteUserForm(forms.Form): @@ -525,13 +522,13 @@ def __init__(self, *args, **kwargs): 'delete_sounds': 'only_user', 'encrypted_link': encrypted_link } - super(DeleteUserForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class BwDeleteUserForm(DeleteUserForm): def __init__(self, *args, **kwargs): - super(BwDeleteUserForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['delete_sounds'].label = False # NOTE: the line below will add 'bw-radio' to all individual radio elements of # forms.RadioSelect but also to the main ul element that wraps them all. This is not @@ -551,7 +548,7 @@ class EmailSettingsForm(forms.Form): class BwEmailSettingsForm(EmailSettingsForm): def __init__(self, *args, **kwargs): - super(BwEmailSettingsForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['email_types'].label = False # NOTE: the line below will add 'bw-checkbox' to all individual checkbox elements of # forms.CheckboxSelectMultiple but also to the main ul element that wraps them all. This is not @@ -629,7 +626,7 @@ def save(self, domain_override=None, class BwSetPasswordForm(SetPasswordForm): def __init__(self, *args, **kwargs): - super(BwSetPasswordForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Customize some placeholders and classes, remove labels and help texts self.fields['new_password1'].label = False diff --git a/accounts/management/__init__.py b/accounts/management/__init__.py index 8b13789179..e69de29bb2 100644 --- a/accounts/management/__init__.py +++ b/accounts/management/__init__.py @@ -1 +0,0 @@ - diff --git a/accounts/management/commands/__init__.py b/accounts/management/commands/__init__.py index 8b13789179..e69de29bb2 100644 --- a/accounts/management/commands/__init__.py +++ b/accounts/management/commands/__init__.py @@ -1 +0,0 @@ - diff --git a/accounts/management/commands/clean_old_tmp_upload_files.py b/accounts/management/commands/clean_old_tmp_upload_files.py index 5d84e549e3..632e958df2 100644 --- a/accounts/management/commands/clean_old_tmp_upload_files.py +++ b/accounts/management/commands/clean_old_tmp_upload_files.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import print_function from django.core.management.base import BaseCommand from django.conf import settings diff --git a/accounts/migrations/0001_initial.py b/accounts/migrations/0001_initial.py index 051acbcfeb..bc73a9412f 100644 --- a/accounts/migrations/0001_initial.py +++ b/accounts/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0002_profile_is_deleted_user.py b/accounts/migrations/0002_profile_is_deleted_user.py index 6e6bc5f64b..8c9f00852a 100644 --- a/accounts/migrations/0002_profile_is_deleted_user.py +++ b/accounts/migrations/0002_profile_is_deleted_user.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-28 15:13 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0003_auto_20160914_1100.py b/accounts/migrations/0003_auto_20160914_1100.py index 096958ce5d..aeedfe3e40 100644 --- a/accounts/migrations/0003_auto_20160914_1100.py +++ b/accounts/migrations/0003_auto_20160914_1100.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-14 11:00 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0004_profile_is_adult.py b/accounts/migrations/0004_profile_is_adult.py index c1e9f27e51..760886ab59 100644 --- a/accounts/migrations/0004_profile_is_adult.py +++ b/accounts/migrations/0004_profile_is_adult.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-18 16:40 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0005_emailpreferencetype_useremailsetting.py b/accounts/migrations/0005_emailpreferencetype_useremailsetting.py index 5c3427a627..d1f29c5f06 100644 --- a/accounts/migrations/0005_emailpreferencetype_useremailsetting.py +++ b/accounts/migrations/0005_emailpreferencetype_useremailsetting.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-03-28 18:16 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0006_copy_email_settings.py b/accounts/migrations/0006_copy_email_settings.py index 7633e33b82..fd6d16cdf6 100644 --- a/accounts/migrations/0006_copy_email_settings.py +++ b/accounts/migrations/0006_copy_email_settings.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - from tickets import TICKET_STATUS_CLOSED from django.db import models, migrations from django.contrib.contenttypes.models import ContentType diff --git a/accounts/migrations/0007_auto_20170328_1851.py b/accounts/migrations/0007_auto_20170328_1851.py index 1b4906cd8f..97f566c02b 100644 --- a/accounts/migrations/0007_auto_20170328_1851.py +++ b/accounts/migrations/0007_auto_20170328_1851.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-03-28 18:51 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0008_auto_20170331_1702.py b/accounts/migrations/0008_auto_20170331_1702.py index b90cafedf3..f79405c3c2 100644 --- a/accounts/migrations/0008_auto_20170331_1702.py +++ b/accounts/migrations/0008_auto_20170331_1702.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-03-31 17:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0009_sameuser.py b/accounts/migrations/0009_sameuser.py index 5ac2a4d4b7..9927ee7d58 100644 --- a/accounts/migrations/0009_sameuser.py +++ b/accounts/migrations/0009_sameuser.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-09 15:25 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0010_auto_20170510_0945.py b/accounts/migrations/0010_auto_20170510_0945.py index 3ebf614929..eb99d27bad 100644 --- a/accounts/migrations/0010_auto_20170510_0945.py +++ b/accounts/migrations/0010_auto_20170510_0945.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-05-10 09:45 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0011_profile_last_donation_email_sent.py b/accounts/migrations/0011_profile_last_donation_email_sent.py index e886826932..ff6ba7ed2d 100644 --- a/accounts/migrations/0011_profile_last_donation_email_sent.py +++ b/accounts/migrations/0011_profile_last_donation_email_sent.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-10 11:06 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0012_profile_donations_reminder_email_sent.py b/accounts/migrations/0012_profile_donations_reminder_email_sent.py index 7008ba3e4c..609135024f 100644 --- a/accounts/migrations/0012_profile_donations_reminder_email_sent.py +++ b/accounts/migrations/0012_profile_donations_reminder_email_sent.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-11 10:46 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0013_profile_sound_signature.py b/accounts/migrations/0013_profile_sound_signature.py index 157f437ca5..c5a0fd4b23 100644 --- a/accounts/migrations/0013_profile_sound_signature.py +++ b/accounts/migrations/0013_profile_sound_signature.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-10-30 16:27 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0014_oldusername.py b/accounts/migrations/0014_oldusername.py index ccc02a101d..d5c264a61f 100644 --- a/accounts/migrations/0014_oldusername.py +++ b/accounts/migrations/0014_oldusername.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-28 18:56 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0015_auto_20171129_1537.py b/accounts/migrations/0015_auto_20171129_1537.py index 57d432d5f0..cb8a5d9c59 100644 --- a/accounts/migrations/0015_auto_20171129_1537.py +++ b/accounts/migrations/0015_auto_20171129_1537.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-29 15:37 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0016_oldusername_created.py b/accounts/migrations/0016_oldusername_created.py index cbe1660df2..c0db6995e5 100644 --- a/accounts/migrations/0016_oldusername_created.py +++ b/accounts/migrations/0016_oldusername_created.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-18 17:06 -from __future__ import unicode_literals from django.db import migrations, models import django.utils.timezone diff --git a/accounts/migrations/0017_auto_20180124_1150.py b/accounts/migrations/0017_auto_20180124_1150.py index 71a458f0f8..eedbd590a4 100644 --- a/accounts/migrations/0017_auto_20180124_1150.py +++ b/accounts/migrations/0017_auto_20180124_1150.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-24 11:50 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0018_sameuser_case_insensitive_emails.py b/accounts/migrations/0018_sameuser_case_insensitive_emails.py index 84204dbf03..111983be47 100644 --- a/accounts/migrations/0018_sameuser_case_insensitive_emails.py +++ b/accounts/migrations/0018_sameuser_case_insensitive_emails.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - from django.conf import settings from django.db import migrations from django.db.models import Count diff --git a/accounts/migrations/0019_emailbounce.py b/accounts/migrations/0019_emailbounce.py index dbfe846c32..7226090c6f 100644 --- a/accounts/migrations/0019_emailbounce.py +++ b/accounts/migrations/0019_emailbounce.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-25 14:38 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -30,6 +28,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='emailbounce', - unique_together=set([('user', 'type', 'timestamp')]), + unique_together={('user', 'type', 'timestamp')}, ), ] diff --git a/accounts/migrations/0019_gdpracceptance.py b/accounts/migrations/0019_gdpracceptance.py index 108eae544d..ef17e4562d 100644 --- a/accounts/migrations/0019_gdpracceptance.py +++ b/accounts/migrations/0019_gdpracceptance.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-29 09:37 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0020_deleted_unusuable_password.py b/accounts/migrations/0020_deleted_unusuable_password.py index ddd7e5e1de..2b800104fb 100644 --- a/accounts/migrations/0020_deleted_unusuable_password.py +++ b/accounts/migrations/0020_deleted_unusuable_password.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-07-09 16:44 -from __future__ import unicode_literals from django.db import migrations from django.contrib.auth.hashers import make_password diff --git a/accounts/migrations/0020_merge_20180710_1458.py b/accounts/migrations/0020_merge_20180710_1458.py index ef8988fad4..a9f3e57f23 100644 --- a/accounts/migrations/0020_merge_20180710_1458.py +++ b/accounts/migrations/0020_merge_20180710_1458.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-07-10 14:58 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0021_auto_20190222_1105.py b/accounts/migrations/0021_auto_20190222_1105.py index 21d56ebeaa..88e9d0f357 100644 --- a/accounts/migrations/0021_auto_20190222_1105.py +++ b/accounts/migrations/0021_auto_20190222_1105.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-02-22 11:05 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0021_merge_20180712_1536.py b/accounts/migrations/0021_merge_20180712_1536.py index c845135890..152e213f35 100644 --- a/accounts/migrations/0021_merge_20180712_1536.py +++ b/accounts/migrations/0021_merge_20180712_1536.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-07-12 15:36 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0022_auto_20190611_1647.py b/accounts/migrations/0022_auto_20190611_1647.py index 99e148d94b..53db805cef 100644 --- a/accounts/migrations/0022_auto_20190611_1647.py +++ b/accounts/migrations/0022_auto_20190611_1647.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-06-11 16:47 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0023_deleteduser.py b/accounts/migrations/0023_deleteduser.py index 145c6b559b..4129c33a5c 100644 --- a/accounts/migrations/0023_deleteduser.py +++ b/accounts/migrations/0023_deleteduser.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-09-27 16:51 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0024_auto_20190927_1658.py b/accounts/migrations/0024_auto_20190927_1658.py index 39bf605926..87ca2f2985 100644 --- a/accounts/migrations/0024_auto_20190927_1658.py +++ b/accounts/migrations/0024_auto_20190927_1658.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-09-27 16:58 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0025_deleteduser_user.py b/accounts/migrations/0025_deleteduser_user.py index 1fd5c4e469..2aedd34051 100644 --- a/accounts/migrations/0025_deleteduser_user.py +++ b/accounts/migrations/0025_deleteduser_user.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-10 14:27 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0026_auto_20191010_1437.py b/accounts/migrations/0026_auto_20191010_1437.py index b78afedfd5..c776e62176 100644 --- a/accounts/migrations/0026_auto_20191010_1437.py +++ b/accounts/migrations/0026_auto_20191010_1437.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-10 14:37 -from __future__ import unicode_literals import datetime from django.db import migrations, models diff --git a/accounts/migrations/0027_deleteduser_last_login.py b/accounts/migrations/0027_deleteduser_last_login.py index 60f746a5dd..4909976118 100644 --- a/accounts/migrations/0027_deleteduser_last_login.py +++ b/accounts/migrations/0027_deleteduser_last_login.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-10 14:40 -from __future__ import unicode_literals import datetime from django.db import migrations, models diff --git a/accounts/migrations/0028_auto_20191010_1448.py b/accounts/migrations/0028_auto_20191010_1448.py index de16983900..b460a97d69 100644 --- a/accounts/migrations/0028_auto_20191010_1448.py +++ b/accounts/migrations/0028_auto_20191010_1448.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-10 14:48 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0029_auto_20191010_1509.py b/accounts/migrations/0029_auto_20191010_1509.py index 3e904981a5..1eb7f65887 100644 --- a/accounts/migrations/0029_auto_20191010_1509.py +++ b/accounts/migrations/0029_auto_20191010_1509.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-10 15:09 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0030_auto_20191016_1457.py b/accounts/migrations/0030_auto_20191016_1457.py index 2f7ac646d5..6131e8d112 100644 --- a/accounts/migrations/0030_auto_20191016_1457.py +++ b/accounts/migrations/0030_auto_20191016_1457.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-10-16 14:57 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/accounts/migrations/0031_auto_20201113_1132.py b/accounts/migrations/0031_auto_20201113_1132.py index 2cac437dcf..90e8d6a144 100644 --- a/accounts/migrations/0031_auto_20201113_1132.py +++ b/accounts/migrations/0031_auto_20201113_1132.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-11-13 11:32 -from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields diff --git a/accounts/migrations/0032_auto_20210409_1344.py b/accounts/migrations/0032_auto_20210409_1344.py index e44db88e77..ecdeccd805 100644 --- a/accounts/migrations/0032_auto_20210409_1344.py +++ b/accounts/migrations/0032_auto_20210409_1344.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-04-09 13:44 -from __future__ import unicode_literals from django.db import migrations, models from django.db.models import Count diff --git a/accounts/migrations/0033_auto_20210412_0742.py b/accounts/migrations/0033_auto_20210412_0742.py index dd7fd4344f..ab5fafefc0 100644 --- a/accounts/migrations/0033_auto_20210412_0742.py +++ b/accounts/migrations/0033_auto_20210412_0742.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-04-12 07:42 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0034_auto_20210412_1738.py b/accounts/migrations/0034_auto_20210412_1738.py index ee943ad2f5..8bb9c7f1c4 100644 --- a/accounts/migrations/0034_auto_20210412_1738.py +++ b/accounts/migrations/0034_auto_20210412_1738.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-04-12 17:38 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/accounts/migrations/0035_merge_20220317_1204.py b/accounts/migrations/0035_merge_20220317_1204.py index 28073d85c1..0a678cfa54 100644 --- a/accounts/migrations/0035_merge_20220317_1204.py +++ b/accounts/migrations/0035_merge_20220317_1204.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-03-17 12:04 -from __future__ import unicode_literals from django.db import migrations diff --git a/accounts/migrations/0036_auto_20230201_1102.py b/accounts/migrations/0036_auto_20230201_1102.py index 4b12c719a4..14feadb135 100644 --- a/accounts/migrations/0036_auto_20230201_1102.py +++ b/accounts/migrations/0036_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals import datetime from django.conf import settings diff --git a/accounts/models.py b/accounts/models.py index 1d582cfe84..35008d94d7 100644 --- a/accounts/models.py +++ b/accounts/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,9 +18,6 @@ # See AUTHORS file. # -from __future__ import division -from builtins import str -from builtins import object from past.utils import old_div import datetime import os @@ -87,7 +82,7 @@ class DeletedUser(models.Model): reason = models.CharField(max_length=2, choices=DELETION_REASON_CHOICES) def __str__(self): - return 'Deleted user object for: {0}'.format(self.username) + return 'Deleted user object for: {}'.format(self.username) class ProfileManager(models.Manager): @@ -615,9 +610,9 @@ class UserFlag(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"Flag %s: %s" % (self.content_type, self.object_id) + return "Flag %s: %s" % (self.content_type, self.object_id) - class Meta(object): + class Meta: ordering = ("-user__username",) @@ -707,7 +702,7 @@ class OldUsername(models.Model): created = models.DateTimeField(auto_now_add=True) def __str__(self): - return '{0} > {1}'.format(self.username, self.user.username) + return '{} > {}'.format(self.username, self.user.username) class EmailBounce(models.Model): @@ -728,7 +723,7 @@ class EmailBounce(models.Model): timestamp = models.DateTimeField(default=now) - class Meta(object): + class Meta: ordering = ("-timestamp",) unique_together = ('user', 'type', 'timestamp') @@ -810,7 +805,7 @@ def update_status_history(sender, instance, **kwargs): should_update_status_history = True if should_update_status_history: - instance.status_history += ['{0}: {1} ({2})'.format(pytz.utc.localize(datetime.datetime.utcnow()), + instance.status_history += ['{}: {} ({})'.format(pytz.utc.localize(datetime.datetime.utcnow()), instance.get_status_display(), instance.status)] diff --git a/accounts/templatetags/display_user.py b/accounts/templatetags/display_user.py index 12a0473256..f37b410bef 100644 --- a/accounts/templatetags/display_user.py +++ b/accounts/templatetags/display_user.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django import template from django.contrib.auth.models import User diff --git a/accounts/tests/test_profile.py b/accounts/tests/test_profile.py index ec90274643..909879af39 100644 --- a/accounts/tests/test_profile.py +++ b/accounts/tests/test_profile.py @@ -17,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import range import datetime import os from unittest import mock @@ -68,8 +67,8 @@ def test_user_tagcloud_solr(self): mock_search_engine.return_value.configure_mock(**conf) accounts.models.get_search_engine = mock_search_engine tag_names = [item['name'] for item in user.profile.get_user_tags()] - used_tag_names = list(set([item.tag.name for item in TaggedItem.objects.filter(user=user)])) - non_used_tag_names = list(set([item.tag.name for item in TaggedItem.objects.exclude(user=user)])) + used_tag_names = list({item.tag.name for item in TaggedItem.objects.filter(user=user)}) + non_used_tag_names = list({item.tag.name for item in TaggedItem.objects.exclude(user=user)}) # Test that tags retrieved with get_user_tags are those found in db self.assertEqual(len(set(tag_names).intersection(used_tag_names)), len(tag_names)) @@ -306,8 +305,8 @@ def test_populate_bounce(self): self.assertFalse(user.profile.email_is_valid()) def test_idna_email(self): - encoded_email = u'user@xn--eb-tbv.de' - decoded_email = u'user@\u2211eb.de' + encoded_email = 'user@xn--eb-tbv.de' + decoded_email = 'user@\u2211eb.de' self.assertEqual(decoded_email, decode_idna_email(encoded_email)) def test_email_email_bounce_removed_when_resetting_email(self): @@ -318,7 +317,7 @@ def test_email_email_bounce_removed_when_resetting_email(self): # User fills in email reset form self.client.force_login(user) resp = self.client.post(reverse('accounts-email-reset'), { - 'email': u'new_email@freesound.org', + 'email': 'new_email@freesound.org', 'password': '12345', }) self.assertRedirects(resp, reverse('accounts-email-reset-done')) @@ -342,12 +341,12 @@ def test_email_email_bounce_removed_when_resetting_email_via_admin(self): self.client.force_login(admin_user) resp = self.client.post(reverse('admin:auth_user_change', args=[user.id]), data={ 'username': user.username, - 'email': u'new_email@freesound.org', + 'email': 'new_email@freesound.org', 'date_joined_0': "2015-10-06", 'date_joined_1': "16:42:00" }) user.refresh_from_db() - self.assertEqual(user.email, u'new_email@freesound.org') + self.assertEqual(user.email, 'new_email@freesound.org') # Now asses no EmailBounce still exist self.assertEqual(EmailBounce.objects.filter(user=user).count(), 0) diff --git a/accounts/tests/test_spam.py b/accounts/tests/test_spam.py index 3ba2415156..99a681f5fc 100644 --- a/accounts/tests/test_spam.py +++ b/accounts/tests/test_spam.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import range from django.conf import settings from django.contrib.auth.models import User from django.core import mail @@ -43,8 +42,8 @@ def setUp(self): # Create users reporting spam self.reporters = [] for i in range(0, settings.USERFLAG_THRESHOLD_FOR_AUTOMATIC_BLOCKING + 1): - reporter = User.objects.create_user(username='reporter_{0}'.format(i), - email='reporter_{0}@example.com'.format(i)) + reporter = User.objects.create_user(username='reporter_{}'.format(i), + email='reporter_{}@example.com'.format(i)) self.reporters.append(reporter) # Create user posting spam diff --git a/accounts/tests/test_upload.py b/accounts/tests/test_upload.py index 6c04c74959..3b4bf4ad71 100644 --- a/accounts/tests/test_upload.py +++ b/accounts/tests/test_upload.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import os from unittest import mock @@ -80,8 +77,8 @@ def test_select_uploaded_files_to_describe(self): # Selecting one file redirects to /home/describe/sounds/ sounds_to_describe_idx = [0] resp = self.client.post('/home/describe/', { - 'describe': [u'Describe selected files'], - 'sound-files': [u'file{}'.format(idx) for idx in sounds_to_describe_idx], # Note this is not the filename but the value of the "select" option + 'describe': ['Describe selected files'], + 'sound-files': ['file{}'.format(idx) for idx in sounds_to_describe_idx], # Note this is not the filename but the value of the "select" option }) self.assertRedirects(resp, '/home/describe/sounds/') self.assertEqual(self.client.session['len_original_describe_edit_sounds'], len(sounds_to_describe_idx)) @@ -90,8 +87,8 @@ def test_select_uploaded_files_to_describe(self): # Selecting multiple file redirects to /home/describe/license/ sounds_to_describe_idx = [1, 2, 3] resp = self.client.post('/home/describe/', { - 'describe': [u'Describe selected files'], - 'sound-files': [u'file{}'.format(idx) for idx in sounds_to_describe_idx], # Note this is not the filename but the value of the "select" option + 'describe': ['Describe selected files'], + 'sound-files': ['file{}'.format(idx) for idx in sounds_to_describe_idx], # Note this is not the filename but the value of the "select" option }) self.assertRedirects(resp, '/home/describe/license/') self.assertEqual(self.client.session['len_original_describe_edit_sounds'], len(sounds_to_describe_idx)) @@ -100,16 +97,16 @@ def test_select_uploaded_files_to_describe(self): # Selecting files to delete, redirect to delete confirmation sounds_to_delete_idx = [1, 2, 3] resp = self.client.post('/home/describe/', { - 'delete': [u'Delete selected files'], - 'sound-files': [u'file{}'.format(idx) for idx in sounds_to_delete_idx], # Note this is not the filename but the value of the "select" option, + 'delete': ['Delete selected files'], + 'sound-files': ['file{}'.format(idx) for idx in sounds_to_delete_idx], # Note this is not the filename but the value of the "select" option, }) self.assertEqual(resp.status_code, 200) self.assertListEqual(sorted(resp.context['filenames']), sorted([filenames[idx] for idx in sounds_to_describe_idx])) # Selecting confirmation of files to delete resp = self.client.post('/home/describe/', { - 'delete_confirm': [u'delete_confirm'], - 'sound-files': [u'file{}'.format(idx) for idx in sounds_to_delete_idx], # Note this is not the filename but the value of the "select" option, + 'delete_confirm': ['delete_confirm'], + 'sound-files': ['file{}'.format(idx) for idx in sounds_to_delete_idx], # Note this is not the filename but the value of the "select" option, }) self.assertRedirects(resp, '/home/describe/') self.assertEqual(len(os.listdir(user_upload_path)), len(filenames) - len(sounds_to_delete_idx)) @@ -139,25 +136,25 @@ def test_describe_selected_files(self): # Post description information resp = self.client.post('/home/describe/sounds/', { - 'submit': [u'Submit and continue'], - '0-lat': [u'46.31658418182218'], - '0-lon': [u'3.515625'], - '0-zoom': [u'16'], - '0-tags': [u'testtag1 testtag2 testtag3'], - '0-pack': [u'{}'.format(existing_pack.id)], - '0-license': [u'3'], - '0-description': [u'a test description for the sound file'], - '0-new_pack': [u''], + 'submit': ['Submit and continue'], + '0-lat': ['46.31658418182218'], + '0-lon': ['3.515625'], + '0-zoom': ['16'], + '0-tags': ['testtag1 testtag2 testtag3'], + '0-pack': ['{}'.format(existing_pack.id)], + '0-license': ['3'], + '0-description': ['a test description for the sound file'], + '0-new_pack': [''], '0-name': [filenames[0]], - '1-license': [u'3'], - '1-description': [u'another test description'], - '1-lat': [u''], - '1-pack': [u''], - '1-lon': [u''], + '1-license': ['3'], + '1-description': ['another test description'], + '1-lat': [''], + '1-pack': [''], + '1-lon': [''], '1-name': [filenames[1]], - '1-new_pack': [u'Name of a new pack'], - '1-zoom': [u''], - '1-tags': [u'testtag1 testtag4 testtag5'], + '1-new_pack': ['Name of a new pack'], + '1-zoom': [''], + '1-tags': ['testtag1 testtag4 testtag5'], }) # Check that post redirected to first describe page with confirmation message on sounds described @@ -203,25 +200,25 @@ def test_describe_selected_files_bw(self): # Post description information resp = self.client.post('/home/describe/sounds/', { - '0-lat': [u'46.31658418182218'], - '0-lon': [u'3.515625'], - '0-zoom': [u'16'], - '0-tags': [u'testtag1 testtag2 testtag3'], - '0-pack': [u''], - '0-license': [u'3'], - '0-description': [u'a test description for the sound file'], - '0-new_pack': [u''], + '0-lat': ['46.31658418182218'], + '0-lon': ['3.515625'], + '0-zoom': ['16'], + '0-tags': ['testtag1 testtag2 testtag3'], + '0-pack': [''], + '0-license': ['3'], + '0-description': ['a test description for the sound file'], + '0-new_pack': [''], '0-name': [filenames[0]], - '1-license': [u'3'], - '1-description': [u'another test description'], - '1-lat': [u''], - '1-pack': [u''], - '1-lon': [u''], + '1-license': ['3'], + '1-description': ['another test description'], + '1-lat': [''], + '1-pack': [''], + '1-lon': [''], '1-name': [filenames[1]], - '1-new_pack': [u'Name of a new pack'], - '1-zoom': [u''], - '1-tags': [u'testtag1 testtag4 testtag5'], - '1-sources': u','.join([u'{}'.format(s.id) for s in sound_sources]), + '1-new_pack': ['Name of a new pack'], + '1-zoom': [''], + '1-tags': ['testtag1 testtag4 testtag5'], + '1-sources': ','.join(['{}'.format(s.id) for s in sound_sources]), }) # Check that post redirected to first describe page with confirmation message on sounds described @@ -237,7 +234,7 @@ def test_describe_selected_files_bw(self): self.assertEqual(Tag.objects.filter(name__contains="testtag").count(), 5) self.assertNotEqual(user.sounds.get(original_filename=filenames[0]).geotag, None) sound_with_sources = user.sounds.get(original_filename=filenames[1]) - self.assertEquals(sound_with_sources.sources.all().count(), len(sound_sources)) + self.assertEqual(sound_with_sources.sources.all().count(), len(sound_sources)) class BulkDescribe(TestCase): @@ -279,7 +276,7 @@ def test_upload_csv(self, submit_job): # Test successful file upload and redirect filename = "file.csv" f = SimpleUploadedFile(filename, b"file_content") - resp = self.client.post(reverse('accounts-describe'), {u'bulk-csv_file': f}) + resp = self.client.post(reverse('accounts-describe'), {'bulk-csv_file': f}) bulk = BulkUploadProgress.objects.get(user=user) self.assertRedirects(resp, reverse('accounts-bulk-describe', args=[bulk.id])) diff --git a/accounts/tests/test_user.py b/accounts/tests/test_user.py index 66aed61aa1..581967a265 100644 --- a/accounts/tests/test_user.py +++ b/accounts/tests/test_user.py @@ -22,8 +22,6 @@ import re from unittest import skipIf, mock -from builtins import range -from builtins import str from django import forms from django.conf import settings from django.contrib.auth.forms import PasswordResetForm @@ -60,11 +58,11 @@ def test_user_registration(self, magic_mock_function): # Try registration without accepting tos resp = self.client.post(reverse('accounts-register'), data={ - u'username': [username], - u'password1': [u'123456'], - u'accepted_tos': [u''], - u'email1': [u'example@email.com'], - u'email2': [u'example@email.com'] + 'username': [username], + 'password1': ['123456'], + 'accepted_tos': [''], + 'email1': ['example@email.com'], + 'email2': ['example@email.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'You must accept the terms of use') @@ -73,11 +71,11 @@ def test_user_registration(self, magic_mock_function): # Try registration with bad email resp = self.client.post(reverse('accounts-register'), data={ - u'username': [username], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'exampleemail.com'], - u'email2': [u'exampleemail.com'] + 'username': [username], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['exampleemail.com'], + 'email2': ['exampleemail.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Enter a valid email') @@ -86,11 +84,11 @@ def test_user_registration(self, magic_mock_function): # Try registration with no username resp = self.client.post(reverse('accounts-register'), data={ - u'username': [''], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'example@email.com'], - u'email2': [u'example@email.com'] + 'username': [''], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['example@email.com'], + 'email2': ['example@email.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'This field is required') @@ -99,11 +97,11 @@ def test_user_registration(self, magic_mock_function): # Try registration with different email addresses resp = self.client.post(reverse('accounts-register'), data={ - u'username': [''], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'example@email.com'], - u'email2': [u'exampl@email.net'] + 'username': [''], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['example@email.com'], + 'email2': ['exampl@email.net'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Please confirm that your email address is the same') @@ -112,11 +110,11 @@ def test_user_registration(self, magic_mock_function): # Try successful registration resp = self.client.post(reverse('accounts-register'), data={ - u'username': [username], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'example@email.com'], - u'email2': [u'example@email.com'] + 'username': [username], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['example@email.com'], + 'email2': ['example@email.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Registration done, activate your account') @@ -127,11 +125,11 @@ def test_user_registration(self, magic_mock_function): # Try register again with same username resp = self.client.post(reverse('accounts-register'), data={ - u'username': [username], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'example@email.com'], - u'email2': [u'example@email.com'] + 'username': [username], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['example@email.com'], + 'email2': ['example@email.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'You cannot use this username to create an account') @@ -140,11 +138,11 @@ def test_user_registration(self, magic_mock_function): # Try with repeated email address resp = self.client.post(reverse('accounts-register'), data={ - u'username': ['a_different_username'], - u'password1': [u'123456'], - u'accepted_tos': [u'on'], - u'email1': [u'example@email.com'], - u'email2': [u'example@email.com'] + 'username': ['a_different_username'], + 'password1': ['123456'], + 'accepted_tos': ['on'], + 'email1': ['example@email.com'], + 'email2': ['example@email.com'] }) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'You cannot use this email address to create an account') @@ -184,7 +182,7 @@ def create_user_and_content(self, username="testuser", is_index_dirty=True): # Create comments target_sound = Sound.objects.all()[0] for i in range(0, 3): - target_sound.add_comment(user, "{0} comment {1}".format(username, i)) + target_sound.add_comment(user, "{} comment {}".format(username, i)) # Create threads and posts forum, _ = Forum.objects.get_or_create(name="Test forum") self.forum = forum @@ -195,11 +193,11 @@ def create_user_and_content(self, username="testuser", is_index_dirty=True): pack = Pack.objects.create(user=user, name="Test pack by {}".format(username)) for i in range(0, 3): Sound.objects.create(user=user, - original_filename="Test sound {0} by {1}".format(i, username), + original_filename="Test sound {} by {}".format(i, username), pack=pack, is_index_dirty=is_index_dirty, license=License.objects.all()[0], - md5="fake_unique_md5_{0}_{1}".format(i, username), + md5="fake_unique_md5_{}_{}".format(i, username), moderation_state="OK", processing_state="OK") return user @@ -810,7 +808,7 @@ def test_reset_email_form(self): user.save() self.client.force_login(user) resp = self.client.post(reverse('accounts-email-reset'), { - 'email': u'new_email@freesound.org', + 'email': 'new_email@freesound.org', 'password': '12345', }) self.assertRedirects(resp, reverse('accounts-email-reset-done')) @@ -824,7 +822,7 @@ def test_reset_email_form_existing_email(self): user.save() self.client.force_login(user) resp = self.client.post(reverse('accounts-email-reset'), { - 'email': u'new_email@freesound.org', + 'email': 'new_email@freesound.org', 'password': '12345', }) self.assertRedirects(resp, reverse('accounts-email-reset-done')) @@ -852,7 +850,7 @@ def test_resend_activation_code_from_email(self): """ user = User.objects.create_user("testuser", email="testuser@freesound.org", is_active=False) resp = self.client.post(reverse('accounts-resend-activation'), { - 'user': u'testuser@freesound.org', + 'user': 'testuser@freesound.org', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check email was sent @@ -860,7 +858,7 @@ def test_resend_activation_code_from_email(self): self.assertTrue(settings.EMAIL_SUBJECT_ACTIVATION_LINK in mail.outbox[0].subject) resp = self.client.post(reverse('accounts-resend-activation'), { - 'user': u'new_email@freesound.org', + 'user': 'new_email@freesound.org', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check no new email was sent (len() is same as before) @@ -871,7 +869,7 @@ def test_resend_activation_code_from_username(self): """ user = User.objects.create_user("testuser", email="testuser@freesound.org", is_active=False) resp = self.client.post(reverse('accounts-resend-activation'), { - 'user': u'testuser', + 'user': 'testuser', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check email was sent @@ -879,7 +877,7 @@ def test_resend_activation_code_from_username(self): self.assertTrue(settings.EMAIL_SUBJECT_ACTIVATION_LINK in mail.outbox[0].subject) resp = self.client.post(reverse('accounts-resend-activation'), { - 'user': u'testuser_does_not_exist', + 'user': 'testuser_does_not_exist', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check no new email was sent (len() is same as before) @@ -901,7 +899,7 @@ def test_username_reminder(self): """ Check that send username reminder doesn't return an error with post request """ user = User.objects.create_user("testuser", email="testuser@freesound.org") resp = self.client.post(reverse('accounts-username-reminder'), { - 'user': u'testuser@freesound.org', + 'user': 'testuser@freesound.org', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check email was sent @@ -909,7 +907,7 @@ def test_username_reminder(self): self.assertTrue(settings.EMAIL_SUBJECT_USERNAME_REMINDER in mail.outbox[0].subject) resp = self.client.post(reverse('accounts-username-reminder'), { - 'user': u'new_email@freesound.org', + 'user': 'new_email@freesound.org', }) self.assertEqual(resp.status_code, 200) self.assertEqual(len(mail.outbox), 1) # Check no new email was sent (len() is same as before) @@ -966,13 +964,13 @@ def test_change_username_form_profile_page(self): self.client.login(username='userA', password='testpass') # Test save profile without changing username - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'userA']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userA']}) self.assertRedirects(resp, reverse('accounts-home')) # Successful edit redirects to home self.assertEqual(OldUsername.objects.filter(user=userA).count(), 0) # Try rename user with an existing username from another user userB = User.objects.create_user('userB', email='userB@freesound.org') - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [userB.username]}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': [userB.username]}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.context['profile_form'].has_error('username'), True) # Error in username field self.assertIn('This username is already taken or has been in used in the past', @@ -982,14 +980,14 @@ def test_change_username_form_profile_page(self): self.assertEqual(OldUsername.objects.filter(user=userA).count(), 0) # Now rename user for the first time - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'userANewName']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userANewName']}) self.assertRedirects(resp, reverse('accounts-home')) # Successful edit redirects to home userA.refresh_from_db() self.assertEqual(userA.username, 'userANewName') self.assertEqual(OldUsername.objects.filter(user=userA).count(), 1) # Try rename again user with a username that was already used by the same user in the past - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'userA']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userA']}) self.assertEqual(resp.status_code, 200) self.assertEqual(resp.context['profile_form'].has_error('username'), True) # Error in username field self.assertIn('This username is already taken or has been in used in the past', @@ -999,7 +997,7 @@ def test_change_username_form_profile_page(self): self.assertEqual(OldUsername.objects.filter(user=userA).count(), 1) # Now rename user for the second time - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'userANewNewName']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userANewNewName']}) self.assertRedirects(resp, reverse('accounts-home')) # Successful edit redirects to home userA.refresh_from_db() self.assertEqual(userA.username, 'userANewNewName') @@ -1010,7 +1008,7 @@ def test_change_username_form_profile_page(self): # NOTE: when USERNAME_CHANGE_MAX_TIMES is reached, the form renders the "username" field as "disabled" and # therefore the username can't be changed. Other than that the form behaves normally, therefore no # form errors will be raised because the field is ignored - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'userANewNewNewName']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['userANewNewNewName']}) self.assertRedirects(resp, reverse('accounts-home')) # Successful edit redirects to home but... userA.refresh_from_db() self.assertEqual(userA.username, 'userANewNewName') # ...username has not changed... @@ -1025,7 +1023,7 @@ def test_change_username_form_admin(self): userA = User.objects.create_user('userA', email='userA@freesound.org', password='testpass') admin_change_url = reverse('admin:auth_user_change', args=[userA.id]) - post_data = {'username': u'userA', + post_data = {'username': 'userA', 'email': userA.email, # Required to avoid breaking unique constraint with empty email 'date_joined_0': "2015-10-06", 'date_joined_1': "16:42:00"} # date_joined required @@ -1035,13 +1033,13 @@ def test_change_username_form_admin(self): self.assertEqual(OldUsername.objects.filter(user=userA).count(), 0) # Now rename user for the first time - post_data.update({'username': u'userANewName'}) + post_data.update({'username': 'userANewName'}) resp = self.client.post(admin_change_url, data=post_data) self.assertRedirects(resp, reverse('admin:auth_user_changelist')) # Successful edit redirects to users list self.assertEqual(OldUsername.objects.filter(username='userA', user=userA).count(), 1) # Now rename user for the second time - post_data.update({'username': u'userANewNewName'}) + post_data.update({'username': 'userANewNewName'}) resp = self.client.post(admin_change_url, data=post_data) self.assertRedirects(resp, reverse('admin:auth_user_changelist')) # Successful edit redirects to users list self.assertEqual(OldUsername.objects.filter(username='userANewName', user=userA).count(), 1) @@ -1060,7 +1058,7 @@ def test_change_username_form_admin(self): self.assertEqual(OldUsername.objects.filter(user=userA).count(), 2) # Try rename user with a username that was already used by the same user in the past - post_data.update({'username': u'userA'}) + post_data.update({'username': 'userA'}) resp = self.client.post(admin_change_url, data=post_data) self.assertEqual(resp.status_code, 200) self.assertEqual(bool(resp.context['adminform'].errors), True) # Error in username field @@ -1072,7 +1070,7 @@ def test_change_username_form_admin(self): # Try rename user with a username that was already used by the same user in the past, but using different # case for some characters - post_data.update({'username': u'uSeRA'}) + post_data.update({'username': 'uSeRA'}) resp = self.client.post(admin_change_url, data=post_data) self.assertEqual(resp.status_code, 200) self.assertEqual(bool(resp.context['adminform'].errors), True) # Error in username field @@ -1084,7 +1082,7 @@ def test_change_username_form_admin(self): # Try to rename for a third time to a valid username. Because we are in admin now, the USERNAME_CHANGE_MAX_TIMES # restriction does not apply so rename should work correctly - post_data.update({'username': u'userANewNewNewName'}) + post_data.update({'username': 'userANewNewNewName'}) resp = self.client.post(admin_change_url, data=post_data) self.assertRedirects(resp, reverse('admin:auth_user_changelist')) # Successful edit redirects to users list self.assertEqual(OldUsername.objects.filter(username='userANewNewName', user=userA).count(), 1) @@ -1100,7 +1098,7 @@ def test_change_username_case_insensitiveness(self): self.client.login(username='userA', password='testpass') # Rename "userA" to "UserA", should not create OldUsername object - resp = self.client.post(reverse('accounts-edit'), data={u'profile-username': [u'UserA']}) + resp = self.client.post(reverse('accounts-edit'), data={'profile-username': ['UserA']}) self.assertRedirects(resp, reverse('accounts-home')) userA.refresh_from_db() self.assertEqual(userA.username, 'UserA') # Username capitalization was changed ... diff --git a/accounts/tests/test_views.py b/accounts/tests/test_views.py index cad8241a15..f5e1733e98 100644 --- a/accounts/tests/test_views.py +++ b/accounts/tests/test_views.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/accounts/urls.py b/accounts/urls.py index 42276fe3e8..4c4e46f09a 100644 --- a/accounts/urls.py +++ b/accounts/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/accounts/views.py b/accounts/views.py index a1154e57b3..f3a6437e51 100644 --- a/accounts/views.py +++ b/accounts/views.py @@ -20,8 +20,6 @@ from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import range import io import csv import datetime @@ -952,8 +950,8 @@ def download_attribution(request): response['Content-Disposition'] = 'attachment; filename="%s"' % filename output = io.StringIO() if download == 'csv': - output.write(u'Download Type,File Name,User,License\r\n') - csv_writer = csv.writer(output, delimiter=u',', quotechar=u'"', quoting=csv.QUOTE_MINIMAL) + output.write('Download Type,File Name,User,License\r\n') + csv_writer = csv.writer(output, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL) for row in qs: csv_writer.writerow( [row['download_type'][0].upper(), row['sound__original_filename'], @@ -962,7 +960,7 @@ def download_attribution(request): row['license__deed_url'] or row['sound__license__deed_url'])]) elif download == 'txt': for row in qs: - output.write(u"{0}: {1} by {2} | License: {3}\n".format(row['download_type'][0].upper(), + output.write("{}: {} by {} | License: {}\n".format(row['download_type'][0].upper(), row['sound__original_filename'], row['sound__user__username'], license_with_version(row['license__name'] or row['sound__license__name'], row['license__deed_url'] or row['sound__license__deed_url']))) @@ -1413,7 +1411,7 @@ def delete(request): delete_action = DELETE_USER_DELETE_SOUNDS_ACTION_NAME if delete_sounds \ else DELETE_USER_KEEP_SOUNDS_ACTION_NAME delete_reason = DeletedUser.DELETION_REASON_SELF_DELETED - web_logger.info('Requested async deletion of user {0} - {1}'.format(request.user.id, delete_action)) + web_logger.info('Requested async deletion of user {} - {}'.format(request.user.id, delete_action)) # Create a UserDeletionRequest with a status of 'Deletion action was triggered' UserDeletionRequest.objects.create(user_from=request.user, @@ -1563,8 +1561,8 @@ def problems_logging_in(request): if form.is_valid(): username_or_email = form.cleaned_data['username_or_email'] try: - user = User.objects.get((Q(email__iexact=username_or_email)\ - | Q(username__iexact=username_or_email))) + user = User.objects.get(Q(email__iexact=username_or_email)\ + | Q(username__iexact=username_or_email)) if not user.is_active: # If user is not activated, send instructions to re-activate the user send_activation(user) diff --git a/apiv2/admin.py b/apiv2/admin.py index 76826f8f73..5b39b346a6 100644 --- a/apiv2/admin.py +++ b/apiv2/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/apiv2/apiv2_utils.py b/apiv2/apiv2_utils.py index 2620e2cd75..8b2d05ab6e 100644 --- a/apiv2/apiv2_utils.py +++ b/apiv2/apiv2_utils.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,15 +18,9 @@ # See AUTHORS file. # -from __future__ import print_function -from __future__ import absolute_import -from __future__ import division from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import range from past.utils import old_div -from builtins import object import collections import datetime import json @@ -108,7 +100,7 @@ def get_view_description(cls, html=False): ############################# -class FreesoundAPIViewMixin(object): +class FreesoundAPIViewMixin: end_user_ip = None auth_method_name = None developer = None @@ -135,7 +127,7 @@ def store_monitor_usage(self): """ if self.client_id is not None: now = datetime.datetime.now().date() - monitoring_key = '{0}-{1}-{2}_{3}'.format(now.year, now.month, now.day, self.client_id) + monitoring_key = '{}-{}-{}_{}'.format(now.year, now.month, now.day, self.client_id) current_value = cache_api_monitoring.get(monitoring_key, 0) cache_api_monitoring.set(monitoring_key, current_value + 1, 60 * 60 * 24 * 3) # Expire in 3 days @@ -181,7 +173,7 @@ class GenericAPIView(RestFrameworkGenericAPIView, FreesoundAPIViewMixin): queryset = False def initial(self, request, *args, **kwargs): - super(GenericAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.store_monitor_usage() @@ -191,7 +183,7 @@ def finalize_response(self, request, response, *args, **kwargs): inside the 'initial' method because it raises an exception when the user is not logged in, that exception is handled by 'finalize_response' method of APIView. """ - response = super(GenericAPIView, self).finalize_response(request, response, *args, **kwargs) + response = super().finalize_response(request, response, *args, **kwargs) response = self.redirect_if_needed(request, response) return response @@ -201,14 +193,14 @@ class OauthRequiredAPIView(RestFrameworkGenericAPIView, FreesoundAPIViewMixin): authentication_classes = (OAuth2Authentication, SessionAuthentication) def initial(self, request, *args, **kwargs): - super(OauthRequiredAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.throw_exception_if_not_https(request) self.store_monitor_usage() def finalize_response(self, request, response, *args, **kwargs): # See comment in GenericAPIView.finalize_response - response = super(OauthRequiredAPIView, self).finalize_response(request, response, *args, **kwargs) + response = super().finalize_response(request, response, *args, **kwargs) response = self.redirect_if_needed(request, response) return response @@ -218,7 +210,7 @@ class DownloadAPIView(RestFrameworkGenericAPIView, FreesoundAPIViewMixin): authentication_classes = (OAuth2Authentication, SessionAuthentication) def initial(self, request, *args, **kwargs): - super(DownloadAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.throw_exception_if_not_https(request) self.store_monitor_usage() @@ -232,7 +224,7 @@ class WriteRequiredGenericAPIView(RestFrameworkGenericAPIView, FreesoundAPIViewM authentication_classes = (OAuth2Authentication, SessionAuthentication) def initial(self, request, *args, **kwargs): - super(WriteRequiredGenericAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.throw_exception_if_not_https(request) self.store_monitor_usage() @@ -244,7 +236,7 @@ def initial(self, request, *args, **kwargs): def finalize_response(self, request, response, *args, **kwargs): # See comment in GenericAPIView.finalize_response - response = super(WriteRequiredGenericAPIView, self).finalize_response(request, response, *args, **kwargs) + response = super().finalize_response(request, response, *args, **kwargs) response = self.redirect_if_needed(request, response) return response @@ -254,7 +246,7 @@ class ListAPIView(RestFrameworkListAPIView, FreesoundAPIViewMixin): authentication_classes = (OAuth2Authentication, TokenAuthentication, SessionAuthentication) def initial(self, request, *args, **kwargs): - super(ListAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.store_monitor_usage() @@ -264,7 +256,7 @@ def get_serializer(self, *args, **kwargs): kwargs['context'] = self.get_serializer_context() if 'SoundListSerializer' in str(serializer_class): # If we are trying to serialize sounds, check if we should and sound analysis data to them and add it - if isinstance(args[0], collections.Iterable): + if isinstance(args[0], collections.abc.Iterable): sound_analysis_data = get_analysis_data_for_sound_ids(kwargs['context']['request'], sound_ids=[s.id for s in args[0]]) if sound_analysis_data: kwargs['sound_analysis_data'] = sound_analysis_data @@ -272,7 +264,7 @@ def get_serializer(self, *args, **kwargs): def finalize_response(self, request, response, *args, **kwargs): # See comment in GenericAPIView.finalize_response - response = super(ListAPIView, self).finalize_response(request, response, *args, **kwargs) + response = super().finalize_response(request, response, *args, **kwargs) response = self.redirect_if_needed(request, response) return response @@ -282,13 +274,13 @@ class RetrieveAPIView(RestFrameworkRetrieveAPIView, FreesoundAPIViewMixin): authentication_classes = (OAuth2Authentication, TokenAuthentication, SessionAuthentication) def initial(self, request, *args, **kwargs): - super(RetrieveAPIView, self).initial(request, *args, **kwargs) + super().initial(request, *args, **kwargs) self.get_request_information(request) self.store_monitor_usage() def finalize_response(self, request, response, *args, **kwargs): # See comment in GenericAPIView.finalize_response - response = super(RetrieveAPIView, self).finalize_response(request, response, *args, **kwargs) + response = super().finalize_response(request, response, *args, **kwargs) response = self.redirect_if_needed(request, response) return response @@ -364,9 +356,9 @@ def api_search( more_from_pack_data = None if search_form.cleaned_data['group_by_pack']: # If grouping option is on, store grouping info in a dictionary that we can add when serializing sounds - more_from_pack_data = dict([ - (int(group['id']), [group['n_more_in_group'], group['group_name']]) for group in result.docs - ]) + more_from_pack_data = { + int(group['id']): [group['n_more_in_group'], group['group_name']] for group in result.docs + } return ids_score, num_found, None, more_from_pack_data, None, None, None @@ -507,7 +499,7 @@ def request_parameters_info_for_log_message(get_parameters): return ','.join(['%s=%s' % (key, value) for key, value in get_parameters.items()]) -class ApiSearchPaginator(object): +class ApiSearchPaginator: def __init__(self, results, count, num_per_page): self.num_per_page = num_per_page self.count = count diff --git a/apiv2/authentication.py b/apiv2/authentication.py index 31302a91e5..759813c62f 100644 --- a/apiv2/authentication.py +++ b/apiv2/authentication.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -46,7 +44,7 @@ def authenticate(self, request): Check that ApiV2Client associatied to the given acess_token has not been disabled. """ try: - super_response = super(OAuth2Authentication, self).authenticate(request) + super_response = super().authenticate(request) except ValueError: # If the request contains html entities that don't decode to valid UTF8, # an exception is raised during oauth validation, even if it's on a field/parameter unrelated to oauth (#793) diff --git a/apiv2/combined_search_strategies.py b/apiv2/combined_search_strategies.py index 3a5a8bc696..26f033f2e6 100644 --- a/apiv2/combined_search_strategies.py +++ b/apiv2/combined_search_strategies.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,12 +17,8 @@ # Authors: # See AUTHORS file. # -from __future__ import absolute_import -from __future__ import division from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import range from past.utils import old_div from apiv2.forms import API_SORT_OPTIONS_MAP from utils.similarity_utilities import api_search as similarity_api_search diff --git a/apiv2/examples.py b/apiv2/examples.py index 7433b9deca..2171037dae 100644 --- a/apiv2/examples.py +++ b/apiv2/examples.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/apiv2/exceptions.py b/apiv2/exceptions.py index 7648a733ef..58a4ad8cf8 100644 --- a/apiv2/exceptions.py +++ b/apiv2/exceptions.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import import logging diff --git a/apiv2/forms.py b/apiv2/forms.py index c545c51210..213107487c 100644 --- a/apiv2/forms.py +++ b/apiv2/forms.py @@ -18,12 +18,10 @@ # See AUTHORS file. # -from __future__ import absolute_import from future import standard_library standard_library.install_aliases() -from builtins import str import django.forms as forms from django.conf import settings from urllib.parse import quote, unquote diff --git a/apiv2/management/commands/basic_api_tests.py b/apiv2/management/commands/basic_api_tests.py index cab92bdd63..e730ca412a 100644 --- a/apiv2/management/commands/basic_api_tests.py +++ b/apiv2/management/commands/basic_api_tests.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,8 +18,6 @@ # See AUTHORS file. # -from __future__ import print_function -from builtins import str try: import requests except: diff --git a/apiv2/management/commands/consolidate_api_usage_data.py b/apiv2/management/commands/consolidate_api_usage_data.py index 78dbe96ac3..b3fbc6a0be 100644 --- a/apiv2/management/commands/consolidate_api_usage_data.py +++ b/apiv2/management/commands/consolidate_api_usage_data.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import datetime import logging @@ -48,7 +45,7 @@ def handle(self, *args, **options): now = datetime.datetime.now().date() for i in range(0, n_days_back): date_filter = now - datetime.timedelta(days=i) - monitoring_key_pattern = '{0}-{1}-{2}_*'.format(date_filter.year, date_filter.month, date_filter.day) + monitoring_key_pattern = '{}-{}-{}_*'.format(date_filter.year, date_filter.month, date_filter.day) for key, count in cache_api_monitoring.get_many(cache_api_monitoring.keys(monitoring_key_pattern)).items(): try: apiv2_client = ApiV2Client.objects.get(oauth_client__client_id=key.split('_')[1]) diff --git a/apiv2/migrations/0001_initial.py b/apiv2/migrations/0001_initial.py index a7de94178b..9f98788ce2 100644 --- a/apiv2/migrations/0001_initial.py +++ b/apiv2/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/apiv2/migrations/0002_apiv2client_oauth_client.py b/apiv2/migrations/0002_apiv2client_oauth_client.py index 6651af3c6b..b4c3bbe5db 100644 --- a/apiv2/migrations/0002_apiv2client_oauth_client.py +++ b/apiv2/migrations/0002_apiv2client_oauth_client.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:45 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/apiv2/migrations/0003_remove_apiv2client_scope.py b/apiv2/migrations/0003_remove_apiv2client_scope.py index a294220b32..a19d99abe9 100644 --- a/apiv2/migrations/0003_remove_apiv2client_scope.py +++ b/apiv2/migrations/0003_remove_apiv2client_scope.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-22 17:36 -from __future__ import unicode_literals from django.db import migrations diff --git a/apiv2/migrations/0004_auto_20161019_1114.py b/apiv2/migrations/0004_auto_20161019_1114.py index e82b7d526f..d07f14cf16 100644 --- a/apiv2/migrations/0004_auto_20161019_1114.py +++ b/apiv2/migrations/0004_auto_20161019_1114.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-19 11:14 -from __future__ import unicode_literals from django.db import migrations diff --git a/apiv2/migrations/0005_auto_20190222_1105.py b/apiv2/migrations/0005_auto_20190222_1105.py index eb4dfaf769..bf23587379 100644 --- a/apiv2/migrations/0005_auto_20190222_1105.py +++ b/apiv2/migrations/0005_auto_20190222_1105.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-02-22 11:05 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/apiv2/migrations/0006_auto_20201230_1530.py b/apiv2/migrations/0006_auto_20201230_1530.py index 7a2b3037c6..84b4be51d9 100644 --- a/apiv2/migrations/0006_auto_20201230_1530.py +++ b/apiv2/migrations/0006_auto_20201230_1530.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2020-12-30 15:30 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion @@ -27,6 +25,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='apiclientdailyusagehistory', - unique_together=set([('apiv2_client', 'date')]), + unique_together={('apiv2_client', 'date')}, ), ] diff --git a/apiv2/migrations/0007_auto_20230201_1102.py b/apiv2/migrations/0007_auto_20230201_1102.py index 609820dc0f..346034ab36 100644 --- a/apiv2/migrations/0007_auto_20230201_1102.py +++ b/apiv2/migrations/0007_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/apiv2/models.py b/apiv2/models.py index 5e5395a93e..59102debd0 100755 --- a/apiv2/models.py +++ b/apiv2/models.py @@ -18,8 +18,6 @@ # See AUTHORS file. # -from builtins import range -from builtins import object import datetime from django.db import models @@ -87,12 +85,12 @@ def save(self, *args, **kwargs): self.oauth_client.redirect_uris = self.redirect_uri self.oauth_client.save() - return super(ApiV2Client, self).save(*args, **kwargs) + return super().save(*args, **kwargs) def delete(self, *args, **kwargs): # On delete, delete also oauth client self.oauth_client.delete() - super(ApiV2Client, self).delete(*args, **kwargs) + super().delete(*args, **kwargs) def get_usage_history(self, n_days_back=30, year=None): """Returns the total number of daily requests made per day for the current API client during the last @@ -147,6 +145,6 @@ class APIClientDailyUsageHistory(models.Model): number_of_requests = models.PositiveIntegerField(default=0) date = models.DateField() - class Meta(object): + class Meta: ordering = ("-date",) unique_together = ('apiv2_client', 'date') diff --git a/apiv2/oauth2_urls.py b/apiv2/oauth2_urls.py index c368dc1b41..614ebd086f 100644 --- a/apiv2/oauth2_urls.py +++ b/apiv2/oauth2_urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/apiv2/serializers.py b/apiv2/serializers.py index e1d0aa2ea2..6aa0aebdd1 100644 --- a/apiv2/serializers.py +++ b/apiv2/serializers.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,11 +18,7 @@ # See AUTHORS file. # -from __future__ import absolute_import -from __future__ import division -from builtins import str from past.utils import old_div -from builtins import object from django.conf import settings from django.contrib.auth.models import User from django.urls import reverse @@ -59,7 +53,7 @@ class AbstractSoundSerializer(serializers.HyperlinkedModelSerializer): def __init__(self, *args, **kwargs): self.score_map = kwargs.pop('score_map', {}) self.sound_analysis_data = kwargs.pop('sound_analysis_data', {}) - super(AbstractSoundSerializer, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) requested_fields = self.context['request'].GET.get("fields", self.default_fields) if not requested_fields: # If parameter is in url but parameter is empty, set to default requested_fields = self.default_fields @@ -73,7 +67,7 @@ def __init__(self, *args, **kwargs): for field_name in existing - allowed: self.fields.pop(field_name) - class Meta(object): + class Meta: model = Sound fields = ('id', 'url', @@ -293,7 +287,7 @@ class SoundListSerializer(AbstractSoundSerializer): def __init__(self, *args, **kwargs): self.default_fields = DEFAULT_FIELDS_IN_SOUND_LIST - super(SoundListSerializer, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def get_analysis(self, obj): if not self.get_or_compute_analysis_state_essentia_exists(obj): @@ -327,7 +321,7 @@ class SoundSerializer(AbstractSoundSerializer): def __init__(self, *args, **kwargs): self.default_fields = DEFAULT_FIELDS_IN_SOUND_DETAIL - super(SoundSerializer, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def get_analysis(self, obj): if not self.get_or_compute_analysis_state_essentia_exists(obj): @@ -392,7 +386,7 @@ def get_analyzers_output(self, obj): class UserSerializer(serializers.HyperlinkedModelSerializer): - class Meta(object): + class Meta: model = User fields = ('url', 'username', @@ -472,7 +466,7 @@ def get_num_comments(self, obj): class PackSerializer(serializers.HyperlinkedModelSerializer): - class Meta(object): + class Meta: model = Pack fields = ('id', 'url', @@ -514,7 +508,7 @@ def get_created(self, obj): class BookmarkCategorySerializer(serializers.HyperlinkedModelSerializer): - class Meta(object): + class Meta: model = BookmarkCategory fields = ('id', 'url', @@ -586,7 +580,7 @@ def validate_rating(self, value): class SoundCommentsSerializer(serializers.HyperlinkedModelSerializer): - class Meta(object): + class Meta: model = Comment fields = ('username', 'comment', diff --git a/apiv2/tests.py b/apiv2/tests.py index a49abed7bc..9b6743278f 100755 --- a/apiv2/tests.py +++ b/apiv2/tests.py @@ -17,8 +17,6 @@ # Authors: # See AUTHORS file. # -from __future__ import absolute_import -import six from django.test import TestCase, SimpleTestCase, RequestFactory from django.urls import reverse from django.conf import settings @@ -383,19 +381,19 @@ def test_num_fields(self): # When 'fields' parameter is not used, return default ones dummy_request = self.factory.get(reverse('apiv2-sound-text-search'), {'fields': ''}) serialized_sound = SoundListSerializer(list(sounds_dict.values())[0], context={'request': dummy_request}).data - six.assertCountEqual(self, list(serialized_sound.keys()), DEFAULT_FIELDS_IN_SOUND_LIST.split(',')) + self.assertCountEqual(list(serialized_sound.keys()), DEFAULT_FIELDS_IN_SOUND_LIST.split(',')) # When only some parameters are specified fields_parameter = 'id,username' dummy_request = self.factory.get(reverse('apiv2-sound-text-search'), {'fields': fields_parameter}) serialized_sound = SoundListSerializer(list(sounds_dict.values())[0], context={'request': dummy_request}).data - six.assertCountEqual(self, list(serialized_sound.keys()), fields_parameter.split(',')) + self.assertCountEqual(list(serialized_sound.keys()), fields_parameter.split(',')) # When all parameters are specified fields_parameter = ','.join(SoundListSerializer.Meta.fields) dummy_request = self.factory.get(reverse('apiv2-sound-text-search'), {'fields': fields_parameter}) serialized_sound = SoundListSerializer(list(sounds_dict.values())[0], context={'request': dummy_request}).data - six.assertCountEqual(self, list(serialized_sound.keys()), fields_parameter.split(',')) + self.assertCountEqual(list(serialized_sound.keys()), fields_parameter.split(',')) def test_num_queries(self): # Test that the serializer does not perform any extra query when serializing sounds regardless of the number @@ -449,7 +447,7 @@ def test_num_fields_and_num_queries(self): with self.assertNumQueries(0): dummy_request = self.factory.get(reverse('apiv2-sound-instance', args=[self.sound.id])) serialized_sound = SoundSerializer(self.sound, context={'request': dummy_request}).data - six.assertCountEqual(self, list(serialized_sound.keys()), SoundSerializer.Meta.fields) + self.assertCountEqual(list(serialized_sound.keys()), SoundSerializer.Meta.fields) class TestApiV2Client(TestCase): diff --git a/apiv2/throttling.py b/apiv2/throttling.py index 01a21383eb..702b551c0b 100644 --- a/apiv2/throttling.py +++ b/apiv2/throttling.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django.conf import settings from rest_framework.throttling import SimpleRateThrottle @@ -67,7 +64,7 @@ def allow_request(self, request, view): rate = limit_rates[0] # Get burst limit self.rate = rate self.num_requests, self.duration = self.parse_rate(rate) - passes_throttle = super(ClientBasedThrottlingBurst, self).allow_request(request, view) + passes_throttle = super().allow_request(request, view) if not passes_throttle: msg = "Request was throttled because of exceeding a request limit rate (%s)" % rate if client_throttle_level == 0: @@ -127,7 +124,7 @@ def allow_request(self, request, view): rate = limit_rates[1] # Get sustained limit self.rate = rate self.num_requests, self.duration = self.parse_rate(rate) - passes_throttle = super(ClientBasedThrottlingSustained, self).allow_request(request, view) + passes_throttle = super().allow_request(request, view) if not passes_throttle: msg = "Request was throttled because of exceeding a request limit rate (%s)" % rate if client_throttle_level == 0: diff --git a/apiv2/urls.py b/apiv2/urls.py index 7072a39ac7..6f8d5d1fcd 100644 --- a/apiv2/urls.py +++ b/apiv2/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/apiv2/views.py b/apiv2/views.py index d664d117a5..f973ebfd6e 100755 --- a/apiv2/views.py +++ b/apiv2/views.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -21,11 +19,8 @@ # -from __future__ import absolute_import -from __future__ import division from future import standard_library standard_library.install_aliases() -from builtins import str from past.utils import old_div import datetime import json @@ -407,7 +402,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('sound:%i instance' % (int(kwargs['pk'])))) - return super(SoundInstance, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) class SoundAnalysisView(GenericAPIView): # Needs to be named SoundAnalysisView so it does not overlap with SoundAnalysis @@ -516,7 +511,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('sound:%i comments' % (int(self.kwargs['pk'])))) - return super(SoundComments, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): return Comment.objects.filter(sound_id=self.kwargs['pk']) @@ -589,7 +584,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('user:%s instance' % (self.kwargs['username']))) - return super(UserInstance, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) class UserSounds(ListAPIView): @@ -605,7 +600,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('user:%s sounds' % (self.kwargs['username']))) - return super(UserSounds, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): try: @@ -632,7 +627,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('user:%s packs' % (self.kwargs['username']))) - return super(UserPacks, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): try: @@ -657,7 +652,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('user:%s bookmark_categories' % (self.kwargs['username']))) - return super(UserBookmarkCategories, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): categories = BookmarkCategory.objects.filter(user__username=self.kwargs['username']) @@ -688,7 +683,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('user:%s sounds_for_bookmark_category:%s' % (self.kwargs['username'], str(self.kwargs.get('category_id', None))))) - return super(UserBookmarkCategorySounds, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): @@ -728,7 +723,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('pack:%i instance' % (int(kwargs['pk'])))) - return super(PackInstance, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) class PackSounds(ListAPIView): @@ -743,7 +738,7 @@ def get_description(cls): def get(self, request, *args, **kwargs): api_logger.info(self.log_message('pack:%i sounds' % (int(kwargs['pk'])))) - return super(PackSounds, self).get(request, *args, **kwargs) + return super().get(request, *args, **kwargs) def get_queryset(self): try: @@ -1312,7 +1307,7 @@ def get(self, request, *args, **kwargs): ] # Yaml format can not represent ordered dicts, so turn ordered dict to dict if these formats are requested - if request.accepted_renderer.format in [u'yaml']: + if request.accepted_renderer.format in ['yaml']: for element in api_index: for key, ordered_dict in element.items(): element[key] = dict(ordered_dict) @@ -1322,7 +1317,7 @@ def key_to_valid_xml(key): # Remove white spaces, parenthesis, and add underscore in the beggining return '_' + key.replace(' ', '_').replace('(', '').replace(')', '') - if request.accepted_renderer.format == u'xml': + if request.accepted_renderer.format == 'xml': aux_api_index = list() for element in api_index: aux_dict_a = dict() diff --git a/bookmarks/admin.py b/bookmarks/admin.py index fede74926a..05b27d8c31 100644 --- a/bookmarks/admin.py +++ b/bookmarks/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/bookmarks/forms.py b/bookmarks/forms.py index b1227a1a9a..cf6ebb924f 100644 --- a/bookmarks/forms.py +++ b/bookmarks/forms.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django import forms from bookmarks.models import BookmarkCategory, Bookmark @@ -26,7 +25,7 @@ class BookmarkCategoryForm(forms.ModelForm): - class Meta(object): + class Meta: model = BookmarkCategory fields = ('name',) widgets = { @@ -40,7 +39,7 @@ class BookmarkForm(forms.ModelForm): required=False) use_last_category = forms.BooleanField(widget=forms.HiddenInput(), required=False, initial=False) - class Meta(object): + class Meta: model = Bookmark fields = ('name','category') widgets = { @@ -81,7 +80,7 @@ def save(self, *args, **kwargs): class BwBookmarkForm(BookmarkForm): def __init__(self, *args, **kwargs): - super(BwBookmarkForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['name'].widget = forms.HiddenInput() # In BW we removed the concept of bookmark name self.fields['new_category_name'].label = False self.fields['new_category_name'].widget.attrs['placeholder'] = \ diff --git a/bookmarks/migrations/0001_initial.py b/bookmarks/migrations/0001_initial.py index b13e3c2142..39e5da6683 100644 --- a/bookmarks/migrations/0001_initial.py +++ b/bookmarks/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/bookmarks/migrations/0002_auto_20211214_2013.py b/bookmarks/migrations/0002_auto_20211214_2013.py index 47da2b1930..729b1ae473 100644 --- a/bookmarks/migrations/0002_auto_20211214_2013.py +++ b/bookmarks/migrations/0002_auto_20211214_2013.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-12-14 20:13 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/bookmarks/migrations/0003_auto_20230201_1102.py b/bookmarks/migrations/0003_auto_20230201_1102.py index cc44330dcf..8b4c1dd5a4 100644 --- a/bookmarks/migrations/0003_auto_20230201_1102.py +++ b/bookmarks/migrations/0003_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/bookmarks/models.py b/bookmarks/models.py index 2f7ff92634..33e28d5da4 100755 --- a/bookmarks/models.py +++ b/bookmarks/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.db import models @@ -32,7 +29,7 @@ class BookmarkCategory(models.Model): name = models.CharField(max_length=128, default="") def __str__(self): - return u"%s" % self.name + return "%s" % self.name class Bookmark(models.Model): @@ -43,7 +40,7 @@ class Bookmark(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"Bookmark: %s" % self.name + return "Bookmark: %s" % self.name @property def category_name_or_uncategorized(self): @@ -60,5 +57,5 @@ def name_or_sound_name(self): else: return self.sound.original_filename - class Meta(object): + class Meta: ordering = ("-created", ) diff --git a/bookmarks/tests.py b/bookmarks/tests.py index d9817531de..9fcb03e725 100644 --- a/bookmarks/tests.py +++ b/bookmarks/tests.py @@ -86,7 +86,7 @@ def test_your_bookmarks(self): response = self.client.get(reverse('bookmarks')) self.assertEqual(200, response.status_code) - self.assertEquals(3, len(response.context['page'].object_list)) + self.assertEqual(3, len(response.context['page'].object_list)) @override_settings(BW_BOOKMARK_PAGES_PUBLIC=True) # Need that to make test pass (and make BW behave same as old UI) def test_others_bookmarks(self): @@ -126,7 +126,7 @@ def test_bookmark_category(self): kwargs={'username': user.username, 'category_id': category.id})) self.assertEqual(200, response.status_code) - self.assertEquals(2, len(response.context['page'].object_list)) + self.assertEqual(2, len(response.context['page'].object_list)) self.assertContains(response, 'Your bookmarks') self.assertContains(response, 'Bookmarks in "Category1"') self.assertContains(response, 'Uncategorized (1 bookmark)') @@ -155,7 +155,7 @@ def test_bookmark_category_oldusername(self): # The response is a 200 self.assertEqual(200, response.status_code) - self.assertEquals(2, len(response.context['page'].object_list)) + self.assertEqual(2, len(response.context['page'].object_list)) self.assertContains(response, 'Your bookmarks') self.assertContains(response, 'Bookmarks in "Category1"') self.assertContains(response, 'Uncategorized (1 bookmark)') diff --git a/bookmarks/views.py b/bookmarks/views.py index 60dadb0472..42e7868232 100755 --- a/bookmarks/views.py +++ b/bookmarks/views.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str from django.conf import settings from django.contrib import messages from django.contrib.auth.decorators import login_required @@ -103,9 +102,9 @@ def add_bookmark(request, sound_id): form.fields['category'].queryset = BookmarkCategory.objects.filter(user=request.user) if form.is_valid(): saved_bookmark = form.save() - msg_to_return = u'Bookmark created with name "{}"'.format(saved_bookmark.name_or_sound_name) + msg_to_return = 'Bookmark created with name "{}"'.format(saved_bookmark.name_or_sound_name) if saved_bookmark.category: - msg_to_return += u' under category "{}".'.format(saved_bookmark.category.name) + msg_to_return += ' under category "{}".'.format(saved_bookmark.category.name) else: msg_to_return += '.' diff --git a/comments/admin.py b/comments/admin.py index dfc8f9d23a..3be17b99db 100644 --- a/comments/admin.py +++ b/comments/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/comments/forms.py b/comments/forms.py index a56d2a7432..c6fb4194f6 100644 --- a/comments/forms.py +++ b/comments/forms.py @@ -27,7 +27,7 @@ class CommentForm(forms.Form): def __init__(self, request, *args, **kwargs): self.request = request - super(CommentForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_comment(self): comment = self.cleaned_data['comment'] @@ -42,7 +42,7 @@ class BwCommentForm(CommentForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwCommentForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['comment'].widget.attrs['placeholder'] = 'Write your comment here...' self.fields['comment'].widget.attrs['rows'] = False diff --git a/comments/migrations/0001_initial.py b/comments/migrations/0001_initial.py index 5144a53b87..f3a30a9103 100644 --- a/comments/migrations/0001_initial.py +++ b/comments/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/comments/migrations/0002_comment_sound.py b/comments/migrations/0002_comment_sound.py index c16de864e6..ef60728cfb 100644 --- a/comments/migrations/0002_comment_sound.py +++ b/comments/migrations/0002_comment_sound.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-27 16:57 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/comments/migrations/0004_auto_20170627_1721.py b/comments/migrations/0004_auto_20170627_1721.py index c09a876dd5..0603b043f7 100644 --- a/comments/migrations/0004_auto_20170627_1721.py +++ b/comments/migrations/0004_auto_20170627_1721.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-27 17:21 -from __future__ import unicode_literals from django.db import migrations diff --git a/comments/migrations/0005_auto_20170710_1642.py b/comments/migrations/0005_auto_20170710_1642.py index cff7c87a17..c0ba2d290c 100644 --- a/comments/migrations/0005_auto_20170710_1642.py +++ b/comments/migrations/0005_auto_20170710_1642.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-10 16:42 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/comments/models.py b/comments/models.py index 59a51ee618..6e8f9adfda 100644 --- a/comments/models.py +++ b/comments/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object import sounds from django.contrib.auth.models import User from django.db import models @@ -35,9 +32,9 @@ class Comment(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"%s comment on %s" % (self.user, self.sound) + return "%s comment on %s" % (self.user, self.sound) - class Meta(object): + class Meta: ordering = ('-created', ) diff --git a/comments/urls.py b/comments/urls.py index 3e1c2ba807..261a84a4cb 100644 --- a/comments/urls.py +++ b/comments/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/donations/admin.py b/donations/admin.py index 7f28dfbb5c..52e695bdc3 100644 --- a/donations/admin.py +++ b/donations/admin.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import from django.contrib import admin from .models import DonationCampaign, DonationsModalSettings, DonationsEmailSettings, Donation diff --git a/donations/forms.py b/donations/forms.py index 00a7ff873f..4c9505027f 100644 --- a/donations/forms.py +++ b/donations/forms.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import json import base64 from django import forms @@ -22,7 +21,7 @@ class DonateForm(forms.Form): def __init__(self, *args, **kwargs): user = kwargs.pop('user', None) default_donation_amount = kwargs.pop('default_donation_amount', None) - super(DonateForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) choices = [ ('1', "Anonymous"), ('2', "Other... "), @@ -41,7 +40,7 @@ def __init__(self, *args, **kwargs): self.initial['amount'] = float(default_donation_amount) def clean(self): - cleaned_data = super(DonateForm, self).clean() + cleaned_data = super().clean() amount = cleaned_data.get('amount') try: if not amount or float(amount) < 1: @@ -77,7 +76,7 @@ class BwDonateForm(DonateForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwDonateForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['donation_type'].label = \ mark_safe('Please choose the name that will appear with the donation:') diff --git a/donations/management/commands/check_missing_donations.py b/donations/management/commands/check_missing_donations.py index 2c27102904..777b1ee6a2 100644 --- a/donations/management/commands/check_missing_donations.py +++ b/donations/management/commands/check_missing_donations.py @@ -20,7 +20,6 @@ from future import standard_library standard_library.install_aliases() -from builtins import range import datetime import logging import requests @@ -76,7 +75,7 @@ def handle(self, **options): # TODO: explore the other types of entries like "transfer" max_range = len([key for key in raw_rsp.keys() if key.startswith("L_TYPE")]) for i in range(max_range): - if raw_rsp['L_TYPE%d' % i][0] in [u'Donation', u'Payment']: + if raw_rsp['L_TYPE%d' % i][0] in ['Donation', 'Payment']: amount = raw_rsp['L_AMT%d' % i][0] if float(amount) < 0: continue # Don't create objects for donations with negative amounts diff --git a/donations/management/commands/send_donation_request_emails.py b/donations/management/commands/send_donation_request_emails.py index fc9b6fae9a..8b36c30424 100644 --- a/donations/management/commands/send_donation_request_emails.py +++ b/donations/management/commands/send_donation_request_emails.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import datetime import json import logging diff --git a/donations/migrations/0001_initial.py b/donations/migrations/0001_initial.py index 8f3c00be66..3771d7f4ff 100644 --- a/donations/migrations/0001_initial.py +++ b/donations/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-01-05 14:00 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/donations/migrations/0002_auto_20170116_1704.py b/donations/migrations/0002_auto_20170116_1704.py index ca33010331..0c081e8a86 100644 --- a/donations/migrations/0002_auto_20170116_1704.py +++ b/donations/migrations/0002_auto_20170116_1704.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2017-01-16 17:04 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0003_donationsmodalsettings.py b/donations/migrations/0003_donationsmodalsettings.py index a5b64252a1..0683f1b3e9 100644 --- a/donations/migrations/0003_donationsmodalsettings.py +++ b/donations/migrations/0003_donationsmodalsettings.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-07 10:56 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0004_donationsmodalsettings_never_show_modal_to_uploaders.py b/donations/migrations/0004_donationsmodalsettings_never_show_modal_to_uploaders.py index b32e2eefbe..954961f058 100644 --- a/donations/migrations/0004_donationsmodalsettings_never_show_modal_to_uploaders.py +++ b/donations/migrations/0004_donationsmodalsettings_never_show_modal_to_uploaders.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-07 14:25 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0005_donationsemailsettings.py b/donations/migrations/0005_donationsemailsettings.py index f5d1a06b01..e29c2a2496 100644 --- a/donations/migrations/0005_donationsemailsettings.py +++ b/donations/migrations/0005_donationsemailsettings.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-10 11:39 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0006_auto_20170710_1524.py b/donations/migrations/0006_auto_20170710_1524.py index 60d34d0d28..54d5f2560d 100644 --- a/donations/migrations/0006_auto_20170710_1524.py +++ b/donations/migrations/0006_auto_20170710_1524.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-10 15:24 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0007_donationsemailsettings_enabled.py b/donations/migrations/0007_donationsemailsettings_enabled.py index 79a112d18e..1e8bce45cc 100644 --- a/donations/migrations/0007_donationsemailsettings_enabled.py +++ b/donations/migrations/0007_donationsemailsettings_enabled.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-10 16:42 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0008_donation_source.py b/donations/migrations/0008_donation_source.py index 2bb5bf1441..cf9053df2f 100644 --- a/donations/migrations/0008_donation_source.py +++ b/donations/migrations/0008_donation_source.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-26 14:07 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0009_auto_20171002_1710.py b/donations/migrations/0009_auto_20171002_1710.py index 3e3709e7ee..93da8186d0 100644 --- a/donations/migrations/0009_auto_20171002_1710.py +++ b/donations/migrations/0009_auto_20171002_1710.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-10-02 17:10 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/migrations/0010_auto_20171222_1352.py b/donations/migrations/0010_auto_20171222_1352.py index 8bb2ca9418..2012764722 100644 --- a/donations/migrations/0010_auto_20171222_1352.py +++ b/donations/migrations/0010_auto_20171222_1352.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-22 13:52 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/donations/models.py b/donations/models.py index f49b73e34e..d65ba84195 100644 --- a/donations/models.py +++ b/donations/models.py @@ -1,4 +1,3 @@ -from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.core.cache import cache diff --git a/donations/tests.py b/donations/tests.py index 91b4157399..5033620faa 100644 --- a/donations/tests.py +++ b/donations/tests.py @@ -1,4 +1,3 @@ -from builtins import range import datetime from unittest import mock import base64 @@ -26,7 +25,7 @@ def test_non_annon_donation_with_name_paypal(self): goal=200, date_start=datetime.datetime.now(), id=1) self.user = User.objects.create_user( username='jacob', email='j@test.com', password='top', id='46280') - custom = base64.b64encode(json.dumps({u'display_amount': True, u'user_id': 46280, u'campaign_id': 1, u'name': u'test'}).encode()).decode() + custom = base64.b64encode(json.dumps({'display_amount': True, 'user_id': 46280, 'campaign_id': 1, 'name': 'test'}).encode()).decode() params = {'txn_id': '8B703020T00352816', 'payer_email': 'fs@freesound.org', 'custom': custom, @@ -52,7 +51,7 @@ def test_non_annon_donation_paypal(self): goal=200, date_start=datetime.datetime.now(), id=1) self.user = User.objects.create_user( username='jacob', email='j@test.com', password='top', id='46280') - custom = base64.b64encode(json.dumps({u'campaign_id': 1, u'user_id': 46280, u'display_amount': True}).encode()).decode() + custom = base64.b64encode(json.dumps({'campaign_id': 1, 'user_id': 46280, 'display_amount': True}).encode()).decode() params = {'txn_id': '8B703020T00352816', 'payer_email': 'fs@freesound.org', 'custom': custom, @@ -77,7 +76,7 @@ def test_annon_donation_paypal(self): donations.models.DonationCampaign.objects.create( goal=200, date_start=datetime.datetime.now(), id=1) - custom = base64.b64encode(json.dumps({u'campaign_id': 1, u'name': u'Anonymous', u'display_amount': True}).encode()).decode() + custom = base64.b64encode(json.dumps({'campaign_id': 1, 'name': 'Anonymous', 'display_amount': True}).encode()).decode() params = {'txn_id': '8B703020T00352816', 'payer_email': 'fs@freesound.org', 'custom': custom, @@ -101,7 +100,7 @@ def test_non_annon_donation_with_name_stripe(self): self.user = User.objects.create_user( username='fsuser', email='j@test.com', password='top', id='46280') self.client.force_login(self.user) - custom = base64.b64encode(json.dumps({u'display_amount': True, u'user_id': 46280, u'campaign_id': 1, u'name': u'test'}).encode()).decode() + custom = base64.b64encode(json.dumps({'display_amount': True, 'user_id': 46280, 'campaign_id': 1, 'name': 'test'}).encode()).decode() params = {"data": {"object" :{"id": "txn123", "customer_email": "donor@freesound.org", "display_items": [{ @@ -131,7 +130,7 @@ def test_non_annon_donation_stripe(self): self.user = User.objects.create_user( username='fsuser', email='j@test.com', password='top', id='46280') self.client.force_login(self.user) - custom = base64.b64encode(json.dumps({u'campaign_id': 1, u'user_id': 46280, u'display_amount': True}).encode()).decode() + custom = base64.b64encode(json.dumps({'campaign_id': 1, 'user_id': 46280, 'display_amount': True}).encode()).decode() params = {"data": {"object" :{"id": "txn123", "customer_email": "donor@freesound.org", "display_items": [{ @@ -158,7 +157,7 @@ def test_non_annon_donation_stripe(self): def test_annon_donation_stripe(self): donations.models.DonationCampaign.objects.create( goal=200, date_start=datetime.datetime.now(), id=1) - custom = base64.b64encode(json.dumps({u'campaign_id': 1, u'name': u'Anonymous', u'display_amount': True}).encode()).decode() + custom = base64.b64encode(json.dumps({'campaign_id': 1, 'name': 'Anonymous', 'display_amount': True}).encode()).decode() params = {"data": {"object" :{"id": "txn123", "customer_email": "donor@freesound.org", "display_items": [{ diff --git a/donations/urls.py b/donations/urls.py index 7a4ee7f8ba..34a3d751f3 100644 --- a/donations/urls.py +++ b/donations/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/donations/views.py b/donations/views.py index 1c8d681958..ea3829b8a5 100644 --- a/donations/views.py +++ b/donations/views.py @@ -1,7 +1,5 @@ -from __future__ import absolute_import from future import standard_library standard_library.install_aliases() -from builtins import str import base64 import json import logging diff --git a/favorites/admin.py b/favorites/admin.py index 0ebb1f2a70..c7483e5646 100644 --- a/favorites/admin.py +++ b/favorites/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/favorites/migrations/0001_initial.py b/favorites/migrations/0001_initial.py index 4ca91b1efe..d166364dcf 100644 --- a/favorites/migrations/0001_initial.py +++ b/favorites/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -32,6 +30,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='favorite', - unique_together=set([('user', 'content_type', 'object_id')]), + unique_together={('user', 'content_type', 'object_id')}, ), ] diff --git a/favorites/models.py b/favorites/models.py index b6b0cc0d2a..3a9f57793c 100644 --- a/favorites/models.py +++ b/favorites/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.contrib.contenttypes import fields from django.contrib.contenttypes.models import ContentType @@ -36,8 +33,8 @@ class Favorite(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"%s favorites %s - %s" % (self.user, self.content_type, self.content_type) + return "%s favorites %s - %s" % (self.user, self.content_type, self.content_type) - class Meta(object): + class Meta: unique_together = (('user', 'content_type', 'object_id'),) ordering = ("-created", ) diff --git a/follow/admin.py b/follow/admin.py index 4cc051f535..c535cd8aff 100644 --- a/follow/admin.py +++ b/follow/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/follow/follow_utils.py b/follow/follow_utils.py index 195a6a721f..973ee7a833 100644 --- a/follow/follow_utils.py +++ b/follow/follow_utils.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -94,7 +92,7 @@ def get_stream_sounds(user, time_lapse, num_results_per_grup=3): more_url_params = [urllib.parse.quote(filter_str), urllib.parse.quote(settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST)] # this is the same link but for the email has to be "quoted" - more_url = u"?f=" + filter_str + u"&s=" + settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST + more_url = "?f=" + filter_str + "&s=" + settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST # more_url_quoted = urllib.quote(more_url) sound_ids = [element['id'] for element in result.docs] @@ -135,7 +133,7 @@ def get_stream_sounds(user, time_lapse, num_results_per_grup=3): more_url_params = [urllib.parse.quote(tag_filter_str), urllib.parse.quote(settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST)] # this is the same link but for the email has to be "quoted" - more_url = u"?f=" + tag_filter_str + u"&s=" + settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST + more_url = "?f=" + tag_filter_str + "&s=" + settings.SEARCH_SOUNDS_SORT_OPTION_DATE_NEW_FIRST # more_url_quoted = urllib.quote(more_url) sound_ids = [element['id'] for element in result.docs] diff --git a/follow/management/commands/send_stream_emails.py b/follow/management/commands/send_stream_emails.py index aa1c2c6d2c..de6b419892 100644 --- a/follow/management/commands/send_stream_emails.py +++ b/follow/management/commands/send_stream_emails.py @@ -17,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import str import datetime import json import logging @@ -73,7 +72,7 @@ def handle(self, *args, **options): week_first_day_str = week_first_day.strftime("%d %b").lstrip("0") week_last_day_str = week_last_day.strftime("%d %b").lstrip("0") - extra_email_subject = str(week_first_day_str) + u' to ' + str(week_last_day_str) + extra_email_subject = str(week_first_day_str) + ' to ' + str(week_last_day_str) # Set date range from which to get upload notifications time_lapse = follow_utils.build_time_lapse(week_first_day, week_last_day) @@ -84,12 +83,12 @@ def handle(self, *args, **options): users_sounds, tags_sounds = follow_utils.get_stream_sounds(user, time_lapse) except Exception as e: # If error occur do not send the email - console_logger.info("could not get new sounds data for {0}".format(username.encode('utf-8'))) + console_logger.info("could not get new sounds data for {}".format(username.encode('utf-8'))) profile.save() # Save last_attempt_of_sending_stream_email continue if not users_sounds and not tags_sounds: - console_logger.info("no news sounds for {0}".format(username.encode('utf-8'))) + console_logger.info("no news sounds for {}".format(username.encode('utf-8'))) profile.save() # Save last_attempt_of_sending_stream_email continue diff --git a/follow/migrations/0001_initial.py b/follow/migrations/0001_initial.py index 907a3c464b..a111917ade 100644 --- a/follow/migrations/0001_initial.py +++ b/follow/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -42,10 +40,10 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='followinguseritem', - unique_together=set([('user_from', 'user_to')]), + unique_together={('user_from', 'user_to')}, ), migrations.AlterUniqueTogether( name='followingqueryitem', - unique_together=set([('user', 'query')]), + unique_together={('user', 'query')}, ), ] diff --git a/follow/migrations/0002_auto_20190506_1459.py b/follow/migrations/0002_auto_20190506_1459.py index 644bb727f9..3ab2152970 100644 --- a/follow/migrations/0002_auto_20190506_1459.py +++ b/follow/migrations/0002_auto_20190506_1459.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-06 14:59 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/follow/models.py b/follow/models.py index bdc6afffb1..1c3203a242 100644 --- a/follow/models.py +++ b/follow/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.db import models @@ -31,9 +28,9 @@ class FollowingUserItem(models.Model): created = models.DateTimeField(auto_now_add=True) def __str__(self): - return u"%s following %s" % (self.user_from, self.user_to) + return "%s following %s" % (self.user_from, self.user_to) - class Meta(object): + class Meta: verbose_name_plural = "Users" unique_together = ("user_from", "user_to") @@ -45,7 +42,7 @@ class FollowingQueryItem(models.Model): created = models.DateTimeField(auto_now_add=True) def __str__(self): - return u"%s following tag '%s'" % (self.user, self.query) + return "%s following tag '%s'" % (self.user, self.query) def get_slash_tags(self): return self.query.replace(" ", "/") @@ -56,6 +53,6 @@ def get_split_tags(self): def get_space_tags(self): return self.query - class Meta(object): + class Meta: verbose_name_plural = 'Tags' unique_together = ("user", "query") diff --git a/follow/tests.py b/follow/tests.py index f024377466..4a45d45ab7 100644 --- a/follow/tests.py +++ b/follow/tests.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/follow/urls.py b/follow/urls.py index d1da91fbfb..362a7c0b0e 100644 --- a/follow/urls.py +++ b/follow/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/follow/views.py b/follow/views.py index 616173dda4..7b89ec8371 100644 --- a/follow/views.py +++ b/follow/views.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/forum/admin.py b/forum/admin.py index 038be1b7de..191e4eb2f5 100644 --- a/forum/admin.py +++ b/forum/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/forum/forms.py b/forum/forms.py index 13723283f1..9d394d5ccd 100644 --- a/forum/forms.py +++ b/forum/forms.py @@ -32,7 +32,7 @@ class PostReplyForm(forms.Form): def __init__(self, request, quote, *args, **kwargs): self.request = request self.quote = quote - super(PostReplyForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_body(self): body = self.cleaned_data['body'] @@ -50,7 +50,7 @@ class BwPostReplyForm(PostReplyForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwPostReplyForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) html_tags_help_text = """Allowed HTML tags: a, img, strong, b, em, li, u, p, br, @@ -80,7 +80,7 @@ class BwNewThreadForm(NewThreadForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwNewThreadForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) html_tags_help_text = """Allowed HTML tags: a, img, strong, b, em, li, u, p, br, diff --git a/forum/migrations/0001_initial.py b/forum/migrations/0001_initial.py index 737a112a0f..49a2658cda 100644 --- a/forum/migrations/0001_initial.py +++ b/forum/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -89,6 +87,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='subscription', - unique_together=set([('subscriber', 'thread')]), + unique_together={('subscriber', 'thread')}, ), ] diff --git a/forum/migrations/0002_auto_20171127_1627.py b/forum/migrations/0002_auto_20171127_1627.py index 4ad2a465bb..8166b74da9 100644 --- a/forum/migrations/0002_auto_20171127_1627.py +++ b/forum/migrations/0002_auto_20171127_1627.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-27 16:27 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/forum/migrations/0003_auto_20230201_1102.py b/forum/migrations/0003_auto_20230201_1102.py index 383327758d..984eb38daf 100644 --- a/forum/migrations/0003_auto_20230201_1102.py +++ b/forum/migrations/0003_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/forum/models.py b/forum/models.py index 655b32ef62..c53ea47a66 100644 --- a/forum/models.py +++ b/forum/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -22,7 +20,6 @@ from future import standard_library standard_library.install_aliases() -from builtins import object import logging from collections import Counter @@ -149,7 +146,7 @@ def get_most_relevant_commenters_info_for_avatars(self): } return info_to_return - class Meta(object): + class Meta: ordering = ('-status', '-last_post__created') def __str__(self): @@ -222,14 +219,14 @@ class Post(models.Model): ) moderation_state = models.CharField(db_index=True, max_length=2, choices=MODERATION_STATE_CHOICES, default="OK") - class Meta(object): + class Meta: ordering = ('created',) permissions = ( ("can_moderate_forum", "Can moderate posts."), ) def __str__(self): - return u"Post by %s in %s" % (self.author, self.thread) + return "Post by %s in %s" % (self.author, self.thread) def get_absolute_url(self): return reverse("forums-post", args=[smart_text(self.thread.forum.name_slug), self.thread.id, self.id]) @@ -348,8 +345,8 @@ class Subscription(models.Model): thread = models.ForeignKey(Thread) is_active = models.BooleanField(db_index=True, default=True) - class Meta(object): + class Meta: unique_together = ("subscriber", "thread") def __str__(self): - return u"%s subscribed to %s" % (self.subscriber, self.thread) + return "%s subscribed to %s" % (self.subscriber, self.thread) diff --git a/forum/templatetags/display_forum_objects.py b/forum/templatetags/display_forum_objects.py index 0f47a48b3f..4809cf48b2 100644 --- a/forum/templatetags/display_forum_objects.py +++ b/forum/templatetags/display_forum_objects.py @@ -18,9 +18,7 @@ # See AUTHORS file. # -from __future__ import absolute_import -from builtins import str from django import template register = template.Library() diff --git a/forum/templatetags/display_forum_search_results.py b/forum/templatetags/display_forum_search_results.py index 405d4e0ae3..eba7a1bfd4 100644 --- a/forum/templatetags/display_forum_search_results.py +++ b/forum/templatetags/display_forum_search_results.py @@ -3,8 +3,6 @@ @author: stelios ''' -from __future__ import absolute_import -from builtins import str from django import template register = template.Library() diff --git a/forum/templatetags/smileys.py b/forum/templatetags/smileys.py index 97003aa8cd..227a7be65a 100644 --- a/forum/templatetags/smileys.py +++ b/forum/templatetags/smileys.py @@ -30,7 +30,7 @@ def smiley_replace(matchobj): except KeyError: return matchobj.group(0) -smiley_replacer = re.compile("=\)|;\-?\)|8\-?\)|:'\(|:\-?[OoPpSsDd\)\(\|]") +smiley_replacer = re.compile(r"=\)|;\-?\)|8\-?\)|:'\(|:\-?[OoPpSsDd\)\(\|]") @register.filter(is_safe=True) def smileys(string): diff --git a/forum/tests.py b/forum/tests.py index d129691593..6a27c76fcf 100644 --- a/forum/tests.py +++ b/forum/tests.py @@ -19,8 +19,6 @@ # from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import range from django.conf import settings from django.contrib.auth.models import User, Group from django.core import mail @@ -343,7 +341,7 @@ def test_new_thread_response_ok(self): # Assert non-logged in user is redirected to login page resp = self.client.post(reverse('forums-new-thread', args=[forum.name_slug]), data={ - u'body': [u'New thread body (first post)'], u'subscribe': [u'on'], u'title': [u'New thread title'] + 'body': ['New thread body (first post)'], 'subscribe': ['on'], 'title': ['New thread title'] }) self.assertRedirects(resp, '%s?next=%s' % ( reverse('login'), reverse('forums-new-thread', args=[forum.name_slug]))) @@ -351,9 +349,9 @@ def test_new_thread_response_ok(self): # Assert logged in user can create new thread self.client.force_login(self.user) resp = self.client.post(reverse('forums-new-thread', args=[forum.name_slug]), data={ - u'body': [u'New thread body (first post)'], u'subscribe': [u'on'], u'title': [u'New thread title'] + 'body': ['New thread body (first post)'], 'subscribe': ['on'], 'title': ['New thread title'] }) - post = Post.objects.get(body=u'New thread body (first post)') + post = Post.objects.get(body='New thread body (first post)') self.assertRedirects(resp, post.get_absolute_url(), target_status_code=302) @override_settings(LAST_FORUM_POST_MINIMUM_TIME=0) @@ -364,7 +362,7 @@ def test_new_thread_title_length(self): long_title = 255 * '1' self.client.force_login(self.user) resp = self.client.post(reverse('forums-new-thread', args=[forum.name_slug]), data={ - u'body': [u'New thread body (first post)'], u'subscribe': [u'on'], u'title': [long_title] + 'body': ['New thread body (first post)'], 'subscribe': ['on'], 'title': [long_title] }) self.assertNotEqual(resp.context['form'].errors, None) @@ -390,7 +388,7 @@ def test_thread_reply_response_ok(self): # Assert non-logged in user is redirected to login page resp = self.client.post(reverse('forums-reply', args=[forum.name_slug, thread.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) self.assertRedirects(resp, '%s?next=%s' % ( reverse('login'), reverse('forums-reply', args=[forum.name_slug, thread.id]))) @@ -398,9 +396,9 @@ def test_thread_reply_response_ok(self): # Assert logged in user can reply self.client.force_login(self.user) resp = self.client.post(reverse('forums-reply', args=[forum.name_slug, thread.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) - post = Post.objects.get(body=u'Reply post body') + post = Post.objects.get(body='Reply post body') self.assertRedirects(resp, post.get_absolute_url(), target_status_code=302) @override_settings(LAST_FORUM_POST_MINIMUM_TIME=0) @@ -411,7 +409,7 @@ def test_thread_reply_quote_post_response_ok(self): # Assert non-logged in user is redirected to login page resp = self.client.post(reverse('forums-reply-quote', args=[forum.name_slug, thread.id, post.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) self.assertRedirects(resp, '%s?next=%s' % ( reverse('login'), reverse('forums-reply-quote', args=[forum.name_slug, thread.id, post.id]))) @@ -419,9 +417,9 @@ def test_thread_reply_quote_post_response_ok(self): # Assert logged in user can reply self.client.force_login(self.user) resp = self.client.post(reverse('forums-reply-quote', args=[forum.name_slug, thread.id, post.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) - post = Post.objects.get(body=u'Reply post body') + post = Post.objects.get(body='Reply post body') self.assertRedirects(resp, post.get_absolute_url(), target_status_code=302) def test_edit_post_response_ok(self): @@ -431,7 +429,7 @@ def test_edit_post_response_ok(self): # Assert non-logged in user can't edit post resp = self.client.post(reverse('forums-post-edit', args=[post.id]), data={ - u'body': [u'Edited post body'] + 'body': ['Edited post body'] }) self.assertRedirects(resp, '%s?next=%s' % (reverse('login'), reverse('forums-post-edit', args=[post.id]))) @@ -439,18 +437,18 @@ def test_edit_post_response_ok(self): user2 = User.objects.create_user(username='testuser2', email='email2@example.com', password='12345') self.client.force_login(user2) resp = self.client.post(reverse('forums-post-edit', args=[post.id]), data={ - u'body': [u'Edited post body'] + 'body': ['Edited post body'] }) self.assertEqual(resp.status_code, 404) # Assert logged in user can edit post self.client.force_login(self.user) resp = self.client.post(reverse('forums-post-edit', args=[post.id]), data={ - u'body': [u'Edited post body'] + 'body': ['Edited post body'] }) self.assertRedirects(resp, post.get_absolute_url(), target_status_code=302) edited_post = Post.objects.get(id=post.id) - self.assertEqual(edited_post.body, u'Edited post body') + self.assertEqual(edited_post.body, 'Edited post body') def test_delete_post_response_ok(self): forum = Forum.objects.first() @@ -572,9 +570,9 @@ def test_emails_sent_for_subscription_to_thread(self): self.assertEqual(Subscription.objects.filter(thread=thread, subscriber=user2).count(), 1) resp = self.client.post(reverse('forums-reply-quote', args=[forum.name_slug, thread.id, post.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) - post = Post.objects.get(body=u'Reply post body') + post = Post.objects.get(body='Reply post body') self.assertRedirects(resp, post.get_absolute_url(), target_status_code=302) # Both users are subscribed but the email is not sent to the user that is sending the post @@ -601,7 +599,7 @@ def test_emails_not_sent_for_subscription_to_thread_if_preference_disabled(self) user2 = User.objects.create_user(username='testuser2', email='email2@example.com', password='12345') self.client.force_login(user2) self.client.post(reverse('forums-reply-quote', args=[forum.name_slug, thread.id, post.id]), data={ - u'body': [u'Reply post body'], u'subscribe': [u'on'], + 'body': ['Reply post body'], 'subscribe': ['on'], }) # No emails sent @@ -627,7 +625,7 @@ def test_user_no_permissions(self): """If the user doesn't have forum.can_moderate_forum permission, they're redirected to login screen""" self.client.force_login(self.regular_user) resp = self.client.post(reverse('forums-moderate'), data={ - u'action': [u'Delete'], u'post': [u'1'], + 'action': ['Delete'], 'post': ['1'], }) self.assertEqual(resp.status_code, 302) @@ -636,7 +634,7 @@ def test_approve_post(self): self.client.force_login(self.admin_user) resp = self.client.post(reverse('forums-moderate'), data={ - u'action': [u'Approve'], u'post': [str(self.post.id)], + 'action': ['Approve'], 'post': [str(self.post.id)], }) self.assertEqual(resp.status_code, 200) self.post.refresh_from_db() @@ -647,7 +645,7 @@ def test_delete_user(self): self.client.force_login(self.admin_user) resp = self.client.post(reverse('forums-moderate'), data={ - u'action': [u'Delete User'], u'post': [str(self.post.id)], + 'action': ['Delete User'], 'post': [str(self.post.id)], }) self.assertEqual(resp.status_code, 200) with self.assertRaises(Post.DoesNotExist): @@ -662,7 +660,7 @@ def test_delete_post(self): self.client.force_login(self.admin_user) resp = self.client.post(reverse('forums-moderate'), data={ - u'action': [u'Delete Post'], u'post': [str(self.post.id)], + 'action': ['Delete Post'], 'post': [str(self.post.id)], }) self.assertEqual(resp.status_code, 200) with self.assertRaises(Post.DoesNotExist): @@ -677,7 +675,7 @@ def test_no_such_post(self): self.client.force_login(self.admin_user) resp = self.client.post(reverse('forums-moderate'), data={ - u'action': [u'Delete Post'], u'post': [str(self.post.id+1)], + 'action': ['Delete Post'], 'post': [str(self.post.id+1)], }) self.assertEqual(resp.status_code, 200) diff --git a/forum/urls.py b/forum/urls.py index 6492d0cbda..9027f07a8a 100644 --- a/forum/urls.py +++ b/forum/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/forum/views.py b/forum/views.py index f9f93da693..992ca77fc7 100644 --- a/forum/views.py +++ b/forum/views.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import division from future import standard_library standard_library.install_aliases() @@ -262,7 +261,7 @@ def reply(request, forum_name_slug, thread_id, post_id=None): subscription.is_active = False subscription.save() - if users_to_notify and post.thread.get_status_display() != u'Sunk': + if users_to_notify and post.thread.get_status_display() != 'Sunk': send_mail_template( settings.EMAIL_SUBJECT_TOPIC_REPLY, "forum/email_new_post_notification.txt", @@ -380,7 +379,7 @@ def subscribe_to_thread(request, forum_name_slug, thread_id): def old_topic_link_redirect(request): post_id = request.GET.get("p", False) if post_id: - post_id = re.sub("\D", "", post_id) + post_id = re.sub(r"\D", "", post_id) try: post = get_object_or_404(Post, id=post_id) except ValueError: @@ -390,7 +389,7 @@ def old_topic_link_redirect(request): thread_id = request.GET.get("t", False) if thread_id: - thread_id = re.sub("\D", "", thread_id) + thread_id = re.sub(r"\D", "", thread_id) try: thread = get_object_or_404(Thread, id=thread_id) except ValueError: diff --git a/freesound/__init__.py b/freesound/__init__.py index ff99efb2cd..1a6c551dd5 100644 --- a/freesound/__init__.py +++ b/freesound/__init__.py @@ -1,5 +1,3 @@ -from __future__ import absolute_import - # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app diff --git a/freesound/celery.py b/freesound/celery.py index d494155c0f..6e97c49437 100644 --- a/freesound/celery.py +++ b/freesound/celery.py @@ -1,4 +1,3 @@ -from __future__ import absolute_import import os import requests from django.conf import settings diff --git a/freesound/local_settings.example.py b/freesound/local_settings.example.py index 220153986b..72f4e41683 100644 --- a/freesound/local_settings.example.py +++ b/freesound/local_settings.example.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import os DEBUG = True diff --git a/freesound/middleware.py b/freesound/middleware.py index cb8b462f77..3d9e753406 100644 --- a/freesound/middleware.py +++ b/freesound/middleware.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import object import json import logging @@ -46,7 +45,7 @@ def dont_redirect(path): and not path.startswith(settings.MEDIA_URL) -class OnlineUsersHandler(object): +class OnlineUsersHandler: def __init__(self, get_response): self.get_response = get_response @@ -56,7 +55,7 @@ def __call__(self, request): return response -class BulkChangeLicenseHandler(object): +class BulkChangeLicenseHandler: def __init__(self, get_response): self.get_response = get_response @@ -77,7 +76,7 @@ def __call__(self, request): return response -class FrontendPreferenceHandler(object): +class FrontendPreferenceHandler: def __init__(self, get_response): self.get_response = get_response @@ -97,7 +96,7 @@ def __call__(self, request): return response -class TosAcceptanceHandler(object): +class TosAcceptanceHandler: """Checks if the user has accepted the updates to the Terms of Service in 2022. This replaces the agreement to the original ToS (2013, 2fd543f3a). When users agree with the new terms of service, they also agree on updating the @@ -120,7 +119,7 @@ def __call__(self, request): return response -class UpdateEmailHandler(object): +class UpdateEmailHandler: message = "We have identified that some emails that we have sent to you didn't go through, thus it appears that " \ "your email address is not valid. Please update your email address to a working one to continue using " \ "Freesound" diff --git a/freesound/settings.py b/freesound/settings.py index 47a5bcae4e..eb1ba88164 100644 --- a/freesound/settings.py +++ b/freesound/settings.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - import datetime import os import re @@ -113,13 +111,13 @@ 'oauth2_provider.RefreshToken', 'oauth2_provider.Grant', )}, - str('forum'), # str() should be replaced when moving to Py3 + 'forum', {'app': 'donations', 'models': ( 'donations.Donation', 'donations.DonationsEmailSettings', 'donations.DonationsModalSettings', )}, - str('sites'), # str() should be replaced when moving to Py3 + 'sites', ) # Silk is the Request/SQL logging platform. We install it but leave it disabled @@ -273,23 +271,23 @@ ALLOWED_EMAILS = [] # Email subjects -EMAIL_SUBJECT_PREFIX = u'[freesound]' -EMAIL_SUBJECT_ACTIVATION_LINK = u'Your activation link' -EMAIL_SUBJECT_USERNAME_REMINDER = u'Username reminder' -EMAIL_SUBJECT_EMAIL_CHANGED = u'Email address changed' -EMAIL_SUBJECT_USER_SPAM_REPORT = u'Spam/offensive report for user' -EMAIL_SUBJECT_DONATION_THANK_YOU = u'Thanks for your donation!' -EMAIL_SUBJECT_DONATION_REMINDER = u'Thanks for contributing to Freesound' -EMAIL_SUBJECT_DONATION_REQUEST = u'Have you considered making a donation?' -EMAIL_SUBJECT_STREAM_EMAILS = u'New sounds from users and tags you are following' -EMAIL_SUBJECT_TOPIC_REPLY = u'Topic reply notification' -EMAIL_SUBJECT_PRIVATE_MESSAGE = u'You have a private message' -EMAIL_SUBJECT_SOUND_ADDED_AS_REMIX = u'Sound added as remix source' -EMAIL_SUBJECT_RANDOM_SOUND_OF_THE_SAY_CHOOSEN = u'One of your sounds has been chosen as random sound of the day!' -EMAIL_SUBJECT_NEW_COMMENT = u'You have a new comment' -EMAIL_SUBJECT_SOUND_FLAG = u'Sound flag' -EMAIL_SUBJECT_SUPPORT_EMAIL = u'[support]' -EMAIL_SUBJECT_MODERATION_HANDLED = u'A Freesound moderator handled your upload' +EMAIL_SUBJECT_PREFIX = '[freesound]' +EMAIL_SUBJECT_ACTIVATION_LINK = 'Your activation link' +EMAIL_SUBJECT_USERNAME_REMINDER = 'Username reminder' +EMAIL_SUBJECT_EMAIL_CHANGED = 'Email address changed' +EMAIL_SUBJECT_USER_SPAM_REPORT = 'Spam/offensive report for user' +EMAIL_SUBJECT_DONATION_THANK_YOU = 'Thanks for your donation!' +EMAIL_SUBJECT_DONATION_REMINDER = 'Thanks for contributing to Freesound' +EMAIL_SUBJECT_DONATION_REQUEST = 'Have you considered making a donation?' +EMAIL_SUBJECT_STREAM_EMAILS = 'New sounds from users and tags you are following' +EMAIL_SUBJECT_TOPIC_REPLY = 'Topic reply notification' +EMAIL_SUBJECT_PRIVATE_MESSAGE = 'You have a private message' +EMAIL_SUBJECT_SOUND_ADDED_AS_REMIX = 'Sound added as remix source' +EMAIL_SUBJECT_RANDOM_SOUND_OF_THE_SAY_CHOOSEN = 'One of your sounds has been chosen as random sound of the day!' +EMAIL_SUBJECT_NEW_COMMENT = 'You have a new comment' +EMAIL_SUBJECT_SOUND_FLAG = 'Sound flag' +EMAIL_SUBJECT_SUPPORT_EMAIL = '[support]' +EMAIL_SUBJECT_MODERATION_HANDLED = 'A Freesound moderator handled your upload' # ------------------------------------------------------------------------------- # Media paths, URLS and static settings diff --git a/freesound/urls.py b/freesound/urls.py index 77fbd21952..2512d18f09 100644 --- a/freesound/urls.py +++ b/freesound/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/general/admin.py b/general/admin.py index 0a79add1d7..dadcf09702 100644 --- a/general/admin.py +++ b/general/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/general/management/commands/build_static.py b/general/management/commands/build_static.py index 1baf342318..83059a1760 100644 --- a/general/management/commands/build_static.py +++ b/general/management/commands/build_static.py @@ -38,7 +38,7 @@ def handle(self, **options): the functionality of passing Django settings as env variables below might not be used. """ variables = {} - variables_for_command = ' '.join(['{0}={1}'.format(key, value) for key, value in variables.items()]) + variables_for_command = ' '.join(['{}={}'.format(key, value) for key, value in variables.items()]) build_static_command = variables_for_command + ' npm run build' console_logger.info('Building static files with command:\n' + build_static_command) os.system(build_static_command) diff --git a/general/management/commands/clean_data_volume.py b/general/management/commands/clean_data_volume.py index 32228bd3d1..7a7e71370f 100644 --- a/general/management/commands/clean_data_volume.py +++ b/general/management/commands/clean_data_volume.py @@ -99,8 +99,7 @@ def handle(self, **options): if not files_in_folder: should_delete = True else: - # NOTE: add u''.format(x) below to avoid issues with filenames with non-ascii characters. This can probably be removed when fully migrating to py3 - if all([datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(folderpath, u''.format(sound_filename)))) < one_year_ago for sound_filename in files_in_folder]): + if all([datetime.datetime.fromtimestamp(os.path.getmtime(os.path.join(folderpath, sound_filename))) < one_year_ago for sound_filename in files_in_folder]): should_delete = True if should_delete: # Delete directory and contents diff --git a/general/management/commands/post_sounds_to_tagrecommendation.py b/general/management/commands/post_sounds_to_tagrecommendation.py index 42d0be3525..b3f4856d70 100644 --- a/general/management/commands/post_sounds_to_tagrecommendation.py +++ b/general/management/commands/post_sounds_to_tagrecommendation.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import print_function from django.core.management.base import BaseCommand diff --git a/general/management/commands/prune_database.py b/general/management/commands/prune_database.py index 493b3c3003..3cf7cc9d72 100644 --- a/general/management/commands/prune_database.py +++ b/general/management/commands/prune_database.py @@ -18,9 +18,7 @@ # See AUTHORS file. # -from __future__ import print_function -from builtins import range import logging import random diff --git a/general/management/commands/similarity_update.py b/general/management/commands/similarity_update.py index a8aab2194f..962431af67 100644 --- a/general/management/commands/similarity_update.py +++ b/general/management/commands/similarity_update.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import logging from django.conf import settings diff --git a/general/migrations/0001_initial.py b/general/migrations/0001_initial.py index 1e72c491f5..c839b21c34 100644 --- a/general/migrations/0001_initial.py +++ b/general/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/general/models.py b/general/models.py index 6df8e8e8ee..b3a67b8122 100644 --- a/general/models.py +++ b/general/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from comments.models import Comment from django.contrib.auth.models import User from django.contrib.contenttypes import fields @@ -35,7 +32,7 @@ class SocialModel(models.Model): tags = fields.GenericRelation(TaggedItem) fans = fields.GenericRelation(Favorite) - class Meta(object): + class Meta: abstract = True class AkismetSpam(SocialModel): @@ -52,7 +49,7 @@ def save(self, *args, **kwargs): self.order = self.__class__.objects.all().order_by("-order")[0].order + 1 except IndexError: self.order = 0 - super(OrderedModel, self).save(*args, **kwargs) + super().save(*args, **kwargs) def change_order(self): model_type_id = ContentType.objects.get_for_model(self.__class__).id @@ -87,6 +84,6 @@ def move(direction, model_type_id, model_id): except ModelClass.DoesNotExist: pass - class Meta(object): + class Meta: ordering = ["order"] abstract = True diff --git a/general/tasks.py b/general/tasks.py index ca6a487daf..3e61f0cd26 100644 --- a/general/tasks.py +++ b/general/tasks.py @@ -17,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import str import datetime import hashlib import json diff --git a/general/templatetags/absurl.py b/general/templatetags/absurl.py index 88dfdf7104..6fcc167b54 100644 --- a/general/templatetags/absurl.py +++ b/general/templatetags/absurl.py @@ -29,7 +29,7 @@ class AbsoluteURLNode(URLNode): def render(self, context): - path = super(AbsoluteURLNode, self).render(context) + path = super().render(context) domain = "https://%s" % Site.objects.get_current().domain return urllib.parse.urljoin(domain, path) diff --git a/general/templatetags/bw_templatetags.py b/general/templatetags/bw_templatetags.py index 37a82605b6..b99f31455e 100644 --- a/general/templatetags/bw_templatetags.py +++ b/general/templatetags/bw_templatetags.py @@ -18,9 +18,6 @@ # See AUTHORS file. # -from builtins import str -from builtins import zip -from builtins import range import math from django import template diff --git a/general/templatetags/filter_img.py b/general/templatetags/filter_img.py index 656ada0f03..bbec36ecd6 100644 --- a/general/templatetags/filter_img.py +++ b/general/templatetags/filter_img.py @@ -1,4 +1,3 @@ -from builtins import str from django import template from bs4 import BeautifulSoup diff --git a/general/templatetags/paginator.py b/general/templatetags/paginator.py index d8ee47746b..af0d5b48e5 100644 --- a/general/templatetags/paginator.py +++ b/general/templatetags/paginator.py @@ -20,8 +20,6 @@ from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import range import urllib.request, urllib.parse, urllib.error from django import template @@ -57,14 +55,14 @@ def show_paginator( min_page_num -= min(total_wanted - num_items, paginator.num_pages - num_items) # although paginator objects are 0-based, we use 1-based paging - page_numbers = [n for n in range(min_page_num, max_page_num) if n > 0 and n <= paginator.num_pages] + page_numbers = [n for n in range(min_page_num, max_page_num) if 0 < n <= paginator.num_pages] params = urllib.parse.urlencode([(key.encode('utf-8'), value.encode('utf-8')) for (key, value) in request.GET.items() - if key.lower() != u"page"]) + if key.lower() != "page"]) if params == "": - url = request.path + u"?page=" + url = request.path + "?page=" else: - url = request.path + u"?" + params + u"&page=" + url = request.path + "?" + params + "&page=" # The pagination could be over a queryset or over the result of a query to solr, so 'page' could be an object # if it's the case a query to the DB or a dict if it's the case of a query to solr diff --git a/general/templatetags/util.py b/general/templatetags/util.py index 3950ec8eee..7ac82c851b 100644 --- a/general/templatetags/util.py +++ b/general/templatetags/util.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,7 +18,6 @@ # See AUTHORS file. # -from builtins import range from past.utils import old_div import datetime import time @@ -39,7 +37,7 @@ def tuple_to_time(t): @stringfilter def truncate_string(value, length): if len(value) > length: - return value[:length-3] + u"..." + return value[:length-3] + "..." else: return value diff --git a/general/tests.py b/general/tests.py index bae1633c34..1337716d5f 100644 --- a/general/tests.py +++ b/general/tests.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -142,7 +140,7 @@ def test_url_with_non_ascii_characters(self): or values, paginator does not break. """ context = {'media_url': 'fake URL'} - text_with_non_ascii = u'�textèé' + text_with_non_ascii = '�textèé' dummy_request = RequestFactory().get(reverse('sounds'), { text_with_non_ascii: '1', 'param_name': text_with_non_ascii, diff --git a/geotags/admin.py b/geotags/admin.py index d5032ac7da..77486a7cb3 100644 --- a/geotags/admin.py +++ b/geotags/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/geotags/migrations/0001_initial.py b/geotags/migrations/0001_initial.py index c5ee6c3063..fe46a8daf4 100644 --- a/geotags/migrations/0001_initial.py +++ b/geotags/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/geotags/migrations/0002_auto_20220111_1251.py b/geotags/migrations/0002_auto_20220111_1251.py index 7a4f5c007f..75493ad653 100644 --- a/geotags/migrations/0002_auto_20220111_1251.py +++ b/geotags/migrations/0002_auto_20220111_1251.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-01-11 12:51 -from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models diff --git a/geotags/migrations/0003_geotag_location_name.py b/geotags/migrations/0003_geotag_location_name.py index 42df150655..560d82ab1b 100644 --- a/geotags/migrations/0003_geotag_location_name.py +++ b/geotags/migrations/0003_geotag_location_name.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-01-11 13:01 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/geotags/migrations/0004_auto_20230201_1102.py b/geotags/migrations/0004_auto_20230201_1102.py index 3228e18472..ea110b96a0 100644 --- a/geotags/migrations/0004_auto_20230201_1102.py +++ b/geotags/migrations/0004_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/geotags/models.py b/geotags/models.py index 62c015b5af..ca4636aeb5 100644 --- a/geotags/models.py +++ b/geotags/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -43,7 +41,7 @@ class GeoTag(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"%s (%f,%f)" % (self.user, self.lat, self.lon) + return "%s (%f,%f)" % (self.user, self.lat, self.lon) def get_absolute_url(self): return reverse('geotag', args=[smart_text(self.id)]) diff --git a/geotags/tests.py b/geotags/tests.py index 77ed65b6a4..911ad3f49f 100644 --- a/geotags/tests.py +++ b/geotags/tests.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -79,7 +78,7 @@ def test_geotags_infowindow(self): sound.save() resp = self.client.get(reverse('geotags-infowindow', kwargs={'sound_id': sound.id})) self.check_context(resp.context, {'sound': sound}) - self.assertContains(resp, 'href="/people/{0}/sounds/{1}/"'.format(sound.user.username, sound.id)) + self.assertContains(resp, 'href="/people/{}/sounds/{}/"'.format(sound.user.username, sound.id)) def test_browse_geotags_case_insensitive(self): user = User.objects.get(username='Anton') diff --git a/geotags/urls.py b/geotags/urls.py index ab5825b359..59a946a7e0 100644 --- a/geotags/urls.py +++ b/geotags/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/messages/admin.py b/messages/admin.py index 131b2f16ce..3125ffcff7 100644 --- a/messages/admin.py +++ b/messages/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/messages/forms.py b/messages/forms.py index 81cf4cfd26..dc1eca1e17 100644 --- a/messages/forms.py +++ b/messages/forms.py @@ -44,7 +44,7 @@ class MessageReplyForm(forms.Form): def __init__(self, request, *args, **kwargs): self.request = request # This is used by MessageReplyFormWithCaptcha to be able to call is_spam function - super(MessageReplyForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class MessageReplyFormWithCaptcha(MessageReplyForm): @@ -62,7 +62,7 @@ class BwMessageReplyForm(MessageReplyForm): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwMessageReplyForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) html_tags_help_text = """Allowed HTML tags: a, img, strong, b, em, li, u, p, br, @@ -84,7 +84,7 @@ class BwMessageReplyFormWithCaptcha(MessageReplyFormWithCaptcha): def __init__(self, *args, **kwargs): kwargs.update(dict(label_suffix='')) - super(BwMessageReplyFormWithCaptcha, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) html_tags_help_text = """Allowed HTML tags: a, img, strong, b, em, li, u, p, br, diff --git a/messages/migrations/0001_initial.py b/messages/migrations/0001_initial.py index 1af7809bed..6b333d380b 100644 --- a/messages/migrations/0001_initial.py +++ b/messages/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/messages/models.py b/messages/models.py index 43f82e6f1c..c1a8582f05 100644 --- a/messages/models.py +++ b/messages/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.db import models from django.utils.encoding import smart_text @@ -30,7 +27,7 @@ class MessageBody(models.Model): body = models.TextField() def __str__(self): - return self.body[0:30] + u"[...]" + return self.body[0:30] + "[...]" class Message(models.Model): @@ -102,7 +99,7 @@ def get_absolute_url(self): return "message", (smart_text(self.id),) def __str__(self): - return u"from: [%s] to: [%s]" % (self.user_from, self.user_to) + return "from: [%s] to: [%s]" % (self.user_from, self.user_to) - class Meta(object): + class Meta: ordering = ('-created',) diff --git a/messages/templatetags/display_message.py b/messages/templatetags/display_message.py index a12557fce1..9d71506f22 100644 --- a/messages/templatetags/display_message.py +++ b/messages/templatetags/display_message.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django import template @@ -35,4 +34,3 @@ def display_message(context, message): 'hide_archive_unarchive': context.get('hide_archive_unarchive', False), 'list_type': context['list_type'] } - \ No newline at end of file diff --git a/messages/tests/test_message_notifications.py b/messages/tests/test_message_notifications.py index 684f271919..bdc8baeb9f 100644 --- a/messages/tests/test_message_notifications.py +++ b/messages/tests/test_message_notifications.py @@ -43,9 +43,9 @@ def setUp(self): def test_message_email_preference_enabled(self, magic_mock): self.client.force_login(user=self.sender) resp = self.client.post(reverse('messages-new'), data={ - u'body': [u'test message body'], - u'to': [u'receiver'], - u'subject': [u'test message'], + 'body': ['test message body'], + 'to': ['receiver'], + 'subject': ['test message'], }) self.assertRedirects(resp, reverse('messages')) self.assertEqual(len(mail.outbox), 1) @@ -61,9 +61,9 @@ def test_message_email_preference_disabled(self, magic_mock): self.client.force_login(user=self.sender) resp = self.client.post(reverse('messages-new'), data={ - u'body': [u'test message body'], - u'to': [u'receiver'], - u'subject': [u'test message'], + 'body': ['test message body'], + 'to': ['receiver'], + 'subject': ['test message'], }) self.assertRedirects(resp, reverse('messages')) self.assertEqual(len(mail.outbox), 0) diff --git a/messages/tests/test_message_write.py b/messages/tests/test_message_write.py index 161fc2de82..9d340f20dd 100644 --- a/messages/tests/test_message_write.py +++ b/messages/tests/test_message_write.py @@ -17,10 +17,8 @@ # Authors: # See AUTHORS file. # -from builtins import range import json -import six from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse @@ -113,7 +111,7 @@ def test_username_lookup_num_queries(self): def test_get_previously_contacted_usernames(self): # Check get_previously_contacted_usernames helper function returns userames of users previously contacted by # the sender or users who previously contacted the sender - six.assertCountEqual(self, [self.receiver3.username, self.receiver2.username, self.receiver1.username, + self.assertCountEqual([self.receiver3.username, self.receiver2.username, self.receiver1.username, self.sender2.username, self.sender.username], get_previously_contacted_usernames(self.sender)) @@ -124,7 +122,7 @@ def test_username_lookup_response(self): resp = self.client.get(reverse('messages-username_lookup')) response_json = json.loads(resp.content) self.assertEqual(resp.status_code, 200) - six.assertCountEqual(self, [self.receiver3.username, self.receiver2.username, self.receiver1.username, + self.assertCountEqual([self.receiver3.username, self.receiver2.username, self.receiver1.username, self.sender2.username, self.sender.username], response_json) diff --git a/messages/views.py b/messages/views.py index 7212c106e0..8d13afefab 100644 --- a/messages/views.py +++ b/messages/views.py @@ -225,7 +225,7 @@ def get_previously_contacted_usernames(user): usernames = list(Message.objects.select_related('user_from', 'user_to') .filter(Q(user_from=user) | Q(user_to=user)) .values_list('user_to__username', 'user_from__username')) - return list(set([item for sublist in usernames for item in sublist])) + return list({item for sublist in usernames for item in sublist}) @login_required diff --git a/monitor/management/commands/generate_stats.py b/monitor/management/commands/generate_stats.py index 43b7cf88a5..0c3de82f79 100644 --- a/monitor/management/commands/generate_stats.py +++ b/monitor/management/commands/generate_stats.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import datetime from django.contrib.auth.models import User diff --git a/monitor/models.py b/monitor/models.py index bd4b2abe9e..71a8362390 100644 --- a/monitor/models.py +++ b/monitor/models.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - from django.db import models # Create your models here. diff --git a/monitor/views.py b/monitor/views.py index f0bf19d24a..e5fe0e7237 100644 --- a/monitor/views.py +++ b/monitor/views.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/ratings/admin.py b/ratings/admin.py index c59bf0593a..f7a848ec9a 100644 --- a/ratings/admin.py +++ b/ratings/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/ratings/migrations/0001_initial.py b/ratings/migrations/0001_initial.py index 53e987b784..701567dc9d 100644 --- a/ratings/migrations/0001_initial.py +++ b/ratings/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -33,6 +31,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='rating', - unique_together=set([('user', 'content_type', 'object_id')]), + unique_together={('user', 'content_type', 'object_id')}, ), ] diff --git a/ratings/migrations/0002_rating_sound.py b/ratings/migrations/0002_rating_sound.py index 0d9792489b..eb2e22d3d0 100644 --- a/ratings/migrations/0002_rating_sound.py +++ b/ratings/migrations/0002_rating_sound.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals from django.db import migrations, models from django.conf import settings import django.db.models.deletion diff --git a/ratings/models.py b/ratings/models.py index 2c84351696..862b605cc6 100644 --- a/ratings/models.py +++ b/ratings/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.contrib.contenttypes.models import ContentType @@ -40,9 +37,9 @@ class SoundRating(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"%s rated %s: %d" % (self.user, self.sound, self.rating) + return "%s rated %s: %d" % (self.user, self.sound, self.rating) - class Meta(object): + class Meta: unique_together = (('user', 'sound'),) ordering = ('-created',) diff --git a/ratings/urls.py b/ratings/urls.py index e2063c9211..dc664715d0 100644 --- a/ratings/urls.py +++ b/ratings/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/ratings/views.py b/ratings/views.py index 0961fc358c..0fc084b3f2 100644 --- a/ratings/views.py +++ b/ratings/views.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str from django.contrib.auth.decorators import login_required from django.db import transaction from django.http import Http404 diff --git a/search/forms.py b/search/forms.py index 34547deb24..f8084af02c 100644 --- a/search/forms.py +++ b/search/forms.py @@ -51,5 +51,5 @@ def clean_s(self): return settings.SEARCH_SOUNDS_SORT_DEFAULT def __init__(self, sort_options, *args, **kargs): - super(SoundSearchForm, self).__init__(*args, **kargs) + super().__init__(*args, **kargs) self.sort_options = sort_options \ No newline at end of file diff --git a/search/management/commands/post_dirty_sounds_to_search_engine.py b/search/management/commands/post_dirty_sounds_to_search_engine.py index 07bfa50b24..fa5ba2f156 100644 --- a/search/management/commands/post_dirty_sounds_to_search_engine.py +++ b/search/management/commands/post_dirty_sounds_to_search_engine.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import logging from sounds.models import Sound diff --git a/search/management/commands/reindex_search_engine_forum.py b/search/management/commands/reindex_search_engine_forum.py index d46b0f8cc7..ac2de25754 100644 --- a/search/management/commands/reindex_search_engine_forum.py +++ b/search/management/commands/reindex_search_engine_forum.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import logging from django.core.management.base import BaseCommand diff --git a/search/templatetags/search.py b/search/templatetags/search.py index 5571e4f912..97631e62f8 100644 --- a/search/templatetags/search.py +++ b/search/templatetags/search.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -48,7 +47,7 @@ def display_facet(context, flt, facet, facet_type, title=""): if element['name'].count("_") > 0: # We also modify the display name to remove the id element['display_name'] = element['name'][element['name'].find("_")+1:] - element['params'] = u'{0} {1}:"{2}"'.format(filter_query, flt, urlquote_plus(element['name'])) + element['params'] = '{} {}:"{}"'.format(filter_query, flt, urlquote_plus(element['name'])) else: # If facet element belongs to "grouping pack" filter but does not have the "_" character in it, it # means this corresponds to the "no pack" grouping which we don't want to show as a facet element. @@ -56,9 +55,9 @@ def display_facet(context, flt, facet, facet_type, title=""): else: element['display_name'] = element['name'] - element['params'] = u'{0} {1}:"{2}"'.format(filter_query, flt, urlquote_plus(element['name'])) - element['id'] = u'{0}--{1}'.format(flt, urlquote_plus(element['name'])) - element['add_filter_url'] = u'.?g={0}&only_p={1}&q={2}&f={3}&s={4}&w={5}'.format( + element['params'] = '{} {}:"{}"'.format(filter_query, flt, urlquote_plus(element['name'])) + element['id'] = '{}--{}'.format(flt, urlquote_plus(element['name'])) + element['add_filter_url'] = '.?g={}&only_p={}&q={}&f={}&s={}&w={}'.format( context['group_by_pack_in_request'], context['only_sounds_with_pack'], context['search_query'], diff --git a/search/tests.py b/search/tests.py index 5fb9a0b0cc..24201a3715 100644 --- a/search/tests.py +++ b/search/tests.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str from django.test import TestCase from django.urls import reverse from sounds.models import Sound @@ -196,8 +195,8 @@ def test_successful_search_result_clustering_view(self, cluster_sound_results): # 3 most used tags in the cluster 'tag1 tag2 tag3' # context variable cluster_id_num_results_tags_sound_examples: [(, , , ), ...] self.assertEqual(resp.context['cluster_id_num_results_tags_sound_examples'], [ - (0, 2, u'tag1 tag2 tag3', self.sound_id_preview_urls[:2]), - (1, 2, u'tag1 tag2 tag3', self.sound_id_preview_urls[2:]) + (0, 2, 'tag1 tag2 tag3', self.sound_id_preview_urls[:2]), + (1, 2, 'tag1 tag2 tag3', self.sound_id_preview_urls[2:]) ]) @mock.patch('search.views.cluster_sound_results') diff --git a/search/views.py b/search/views.py index d1eaef2c9d..731b6f6475 100644 --- a/search/views.py +++ b/search/views.py @@ -1,4 +1,3 @@ - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,10 +18,6 @@ # See AUTHORS file. # -from builtins import map -from builtins import str -from builtins import zip -from builtins import range import datetime import json import logging @@ -160,7 +155,7 @@ def search_view_helper(request, tags_mode=False): for d in docs: d["sound"] = allsounds[d["id"]] - search_logger.info(u'Search (%s)' % json.dumps({ + search_logger.info('Search (%s)' % json.dumps({ 'ip': get_client_ip(request), 'query': query_params['textual_query'], 'filter': query_params['query_filter'], @@ -488,5 +483,5 @@ def query_suggestions(request): 'rain', 'swoosh' ]): - suggestions.append({'id': count, 'label': '

{0}

'.format(suggestion), 'value': suggestion}) + suggestions.append({'id': count, 'label': '

{}

'.format(suggestion), 'value': suggestion}) return JsonResponse({'suggestions': suggestions}) diff --git a/sounds/admin.py b/sounds/admin.py index 9fe2d19793..88b4808e59 100644 --- a/sounds/admin.py +++ b/sounds/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -57,16 +55,16 @@ class SoundAdmin(DjangoObjectActions, admin.ModelAdmin): change_actions = ('reprocess_sound', ) def get_processing_state(self, obj): - processing_state = u'{}'.format(obj.get_processing_state_display()) + processing_state = '{}'.format(obj.get_processing_state_display()) ongoing_state_display = obj.get_processing_ongoing_state_display() if ongoing_state_display == 'Processing' or ongoing_state_display == 'Queued': - processing_state += u' ({})'.format(ongoing_state_display) + processing_state += ' ({})'.format(ongoing_state_display) return processing_state get_processing_state.short_description = 'Processing state' def get_sound_name(self, obj): max_len = 15 - return u'{0}{1}'.format(obj.original_filename[:max_len], '...' if len(obj.original_filename) > max_len else '') + return '{}{}'.format(obj.original_filename[:max_len], '...' if len(obj.original_filename) > max_len else '') get_sound_name.short_description = 'Name' def reprocess_sound(self, request, queryset_or_object): @@ -95,16 +93,16 @@ class DeletedSoundAdmin(admin.ModelAdmin): def get_queryset(self, request): # Override 'get_queryset' to optimize query by using select_related on appropriate fields - qs = super(DeletedSoundAdmin, self).get_queryset(request) + qs = super().get_queryset(request) qs = qs.select_related('user') return qs def user_link(self, obj): if obj.user is None: return '-' - return '{1}'.format( + return '{}'.format( reverse('admin:auth_user_change', args=[obj.user.id]), - '{0}'.format(obj.user.username)) + '{}'.format(obj.user.username)) user_link.allow_tags = True user_link.admin_order_field = 'user' @@ -127,12 +125,12 @@ class FlagAdmin(admin.ModelAdmin): def get_queryset(self, request): # overrride 'get_queryset' to optimize query by using select_related on 'sound' and 'reporting_user' - qs = super(FlagAdmin, self).get_queryset(request) + qs = super().get_queryset(request) qs = qs.select_related('sound', 'reporting_user') return qs def reporting_user_link(self, obj): - return '{1}'.format( + return '{}'.format( reverse('account', args=[obj.reporting_user.username]), obj.reporting_user.username) \ if obj.reporting_user else '-' reporting_user_link.allow_tags = True @@ -140,21 +138,21 @@ def reporting_user_link(self, obj): reporting_user_link.short_description = 'Reporting User' def email_link(self, obj): - return '{1}'.format(obj.email, obj.email) \ + return '{}'.format(obj.email, obj.email) \ if obj.email else '-' email_link.allow_tags = True email_link.admin_order_field = 'email' email_link.short_description = 'Email' def sound_uploader_link(self, obj): - return '{1}'.format(reverse('account', args=[obj.sound.user.username]), + return '{}'.format(reverse('account', args=[obj.sound.user.username]), obj.sound.user.username) sound_uploader_link.allow_tags = True sound_uploader_link.admin_order_field = 'sound__user__username' sound_uploader_link.short_description = 'Uploader' def sound_link(self, obj): - return '{1}'.format(reverse('short-sound-link', args=[obj.sound_id]), + return '{}'.format(reverse('short-sound-link', args=[obj.sound_id]), truncatechars(obj.sound.base_filename_slug, 50)) sound_link.allow_tags = True sound_link.admin_order_field = 'sound__original_filename' @@ -179,7 +177,7 @@ class SoundOfTheDayAdmin(admin.ModelAdmin): ordering = ('-date_display', ) def get_urls(self): - urls = super(SoundOfTheDayAdmin, self).get_urls() + urls = super().get_urls() my_urls = [ url('generate_new_sounds/', self.generate_new_sounds), url('clear_sound_of_the_day_cache/', self.clear_sound_of_the_day_cache), diff --git a/sounds/forms.py b/sounds/forms.py index a10a3b9afd..f9e50838e2 100644 --- a/sounds/forms.py +++ b/sounds/forms.py @@ -18,11 +18,9 @@ # See AUTHORS file. # -from __future__ import print_function import re -from builtins import object from captcha.fields import ReCaptchaField from django import forms from django.conf import settings @@ -86,7 +84,7 @@ def __init__(self, *args, **kwargs): explicit_disable = kwargs.get('explicit_disable') del kwargs['explicit_disable'] - super(SoundDescriptionForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) # Disable is_explicit field if is already marked self.initial['is_explicit'] = explicit_disable self.fields['is_explicit'].disabled = explicit_disable @@ -97,7 +95,7 @@ class RemixForm(forms.Form): def __init__(self, sound, *args, **kwargs): self.sound = sound - super(RemixForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) def clean_sources(self): sources = re.sub("[^0-9,]", "", self.cleaned_data['sources']) @@ -105,7 +103,7 @@ def clean_sources(self): sources = re.sub("^,+", "", sources) sources = re.sub(",+$", "", sources) if len(sources) > 0: - sources = set([int(source) for source in sources.split(",")]) + sources = {int(source) for source in sources.split(",")} else: sources = set() @@ -126,7 +124,7 @@ class PackForm(forms.Form): label="Or fill in the name of a new pack:", required=False, min_length=5) def __init__(self, pack_choices, *args, **kwargs): - super(PackForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['pack'].queryset = pack_choices.extra(select={'lower_name': 'lower(name)'}).order_by('lower_name') @@ -142,13 +140,13 @@ def clean_pack_sounds(self): pack_sounds = re.sub("^,+", "", pack_sounds) pack_sounds = re.sub(",+$", "", pack_sounds) if len(pack_sounds) > 0: - pack_sounds = set([int(sound) for sound in pack_sounds.split(",")]) + pack_sounds = {int(sound) for sound in pack_sounds.split(",")} else: pack_sounds = set() return pack_sounds def save(self, force_insert=False, force_update=False, commit=True): - pack = super(PackEditForm, self).save(commit=False) + pack = super().save(commit=False) affected_packs = list() affected_packs.append(pack) new_sounds = self.cleaned_data['pack_sounds'] @@ -171,7 +169,7 @@ def save(self, force_insert=False, force_update=False, commit=True): affected_pack.process() return pack - class Meta(object): + class Meta: model = Pack fields = ('name', 'description',) widgets = { @@ -186,7 +184,7 @@ class NewLicenseForm(forms.Form): def __init__(self, *args, **kwargs): hide_old_versions = kwargs.pop('hide_old_versions', False) - super(NewLicenseForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) if hide_old_versions: new_qs = License.objects.filter(Q(name__startswith='Attribution') | Q(name__startswith='Creative')).exclude(deed_url__contains="3.0") self.fields['license'].queryset = new_qs @@ -240,7 +238,7 @@ def __init__(self, *args, **kwargs): kwargs['initial'] = { 'encrypted_link': encrypted_link } - super(DeleteSoundForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) class SoundCSVDescriptionForm(SoundDescriptionForm, GeotaggingForm, NewLicenseForm): @@ -254,7 +252,7 @@ class SoundCSVDescriptionForm(SoundDescriptionForm, GeotaggingForm, NewLicenseFo pack_name = forms.CharField(min_length=5, required=False) def __init__(self, *args, **kwargs): - super(SoundCSVDescriptionForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['name'].required = False # Make sound name not required def clean(self): @@ -304,7 +302,7 @@ def __init__(self, *args, **kwargs): explicit_disable = kwargs.pop('explicit_disable', False) hide_old_license_versions = kwargs.pop('hide_old_license_versions', False) user_packs = kwargs.pop('user_packs', False) - super(BWSoundEditAndDescribeForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['is_explicit'].widget.attrs['class'] = 'bw-checkbox' self.fields['remove_geotag'].widget.attrs['class'] = 'bw-checkbox' self.fields['license'].widget.attrs['class'] = 'bw-radio' @@ -354,7 +352,7 @@ def clean_sources(self): sources = re.sub("^,+", "", sources) sources = re.sub(",+$", "", sources) if len(sources) > 0: - sources = set([int(source) for source in sources.split(",")]) + sources = {int(source) for source in sources.split(",")} else: sources = set() return sources \ No newline at end of file diff --git a/sounds/management.py b/sounds/management.py index fbbda4d0f2..edbdb09f9a 100644 --- a/sounds/management.py +++ b/sounds/management.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import print_function import os diff --git a/sounds/management/commands/check_sound_paths.py b/sounds/management/commands/check_sound_paths.py index 75b1ca67b8..91270f6640 100644 --- a/sounds/management/commands/check_sound_paths.py +++ b/sounds/management/commands/check_sound_paths.py @@ -45,8 +45,8 @@ def handle(self, *args, **options): if not os.path.exists(sound.locations('path')): missing_sound_ids += [sound.id] - console_logger.info('Found {0} sounds with missing audio files'.format(len(missing_sound_ids))) + console_logger.info('Found {} sounds with missing audio files'.format(len(missing_sound_ids))) if missing_sound_ids and options['outfile'] is not None: json.dump(missing_sound_ids, open(options['outfile'], 'w')) - console_logger.info('List of sound IDs with missing files saved in "{0}"'.format(options['outfile'])) + console_logger.info('List of sound IDs with missing files saved in "{}"'.format(options['outfile'])) diff --git a/sounds/management/commands/create_random_sounds.py b/sounds/management/commands/create_random_sounds.py index 70f8e59073..88812d32b6 100644 --- a/sounds/management/commands/create_random_sounds.py +++ b/sounds/management/commands/create_random_sounds.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import datetime from django.conf import settings diff --git a/sounds/management/commands/create_remix_groups.py b/sounds/management/commands/create_remix_groups.py index f63095b1f9..d04579ab07 100644 --- a/sounds/management/commands/create_remix_groups.py +++ b/sounds/management/commands/create_remix_groups.py @@ -18,9 +18,7 @@ # See AUTHORS file. # -from __future__ import division -from builtins import str import json import logging @@ -106,7 +104,7 @@ def _create_and_save_remixgroup(sg, remixgroup): # dict with key=sound_id, value=index, nodeName=original_filname # in the previous sorted by date list # FIXME: no need for all this data, can be simple dict, key=value - container = dict((val[0], {'index': idx, 'nodeName': val[1]['nodeName']}) for (idx, val) in enumerate(node_list)) + container = {val[0]: {'index': idx, 'nodeName': val[1]['nodeName']} for (idx, val) in enumerate(node_list)} # print ' ========== CONTAINER ========= ' # pp(container) diff --git a/sounds/management/commands/orchestrate_analysis.py b/sounds/management/commands/orchestrate_analysis.py index 7fdf9cf5c1..8badd93780 100644 --- a/sounds/management/commands/orchestrate_analysis.py +++ b/sounds/management/commands/orchestrate_analysis.py @@ -17,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import str import datetime import logging import json @@ -79,8 +78,8 @@ def handle(self, *args, **options): percentage_done = (ok + sk + fa) * 100.0/n_sounds # print one row per analyzer console_logger.info("{: >44} {: >11} {: >11} {: >11} {: >11} {: >11}".format( - *[analyzer_name + ' |', '{0} |'.format(ok), '{0} |'.format(sk), - '{0} |'.format(fa), '{0} |'.format(qu), missing])) + *[analyzer_name + ' |', '{} |'.format(ok), '{} |'.format(sk), + '{} |'.format(fa), '{} |'.format(qu), missing])) data_to_log[analyzer_name] = { 'OK': ok, @@ -174,7 +173,7 @@ def handle(self, *args, **options): 'analyzer': analyzer_name, 'percentage_completed': analyzer_data_to_log['Percentage'] }) - commands_logger.info('Orchestrate analysis analyzer update ({0})'.format(json.dumps(analyzer_data_to_log))) + commands_logger.info('Orchestrate analysis analyzer update ({})'.format(json.dumps(analyzer_data_to_log))) console_logger.info('') # Now revise SoundAnalysis objects that have been stuck in QU status for some time and set them to Failed diff --git a/sounds/management/commands/update_cdn_sounds.py b/sounds/management/commands/update_cdn_sounds.py index 00a45e589a..0670f53528 100644 --- a/sounds/management/commands/update_cdn_sounds.py +++ b/sounds/management/commands/update_cdn_sounds.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import json import logging import os diff --git a/sounds/migrations/0001_initial.py b/sounds/migrations/0001_initial.py index 70d056026e..772992c680 100644 --- a/sounds/migrations/0001_initial.py +++ b/sounds/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -167,6 +165,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='pack', - unique_together=set([('user', 'name')]), + unique_together={('user', 'name')}, ), ] diff --git a/sounds/migrations/0002_auto_20160728_1516.py b/sounds/migrations/0002_auto_20160728_1516.py index a7db8e17e7..3afcc91df4 100644 --- a/sounds/migrations/0002_auto_20160728_1516.py +++ b/sounds/migrations/0002_auto_20160728_1516.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-28 15:16 -from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models diff --git a/sounds/migrations/0003_auto_20160914_1100.py b/sounds/migrations/0003_auto_20160914_1100.py index ea8a79efd6..ed0748a723 100644 --- a/sounds/migrations/0003_auto_20160914_1100.py +++ b/sounds/migrations/0003_auto_20160914_1100.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-14 11:00 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0004_deletedsound_created.py b/sounds/migrations/0004_deletedsound_created.py index 369cdafae3..5b93352a1b 100644 --- a/sounds/migrations/0004_deletedsound_created.py +++ b/sounds/migrations/0004_deletedsound_created.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-09-19 09:52 -from __future__ import unicode_literals import datetime from django.db import migrations, models diff --git a/sounds/migrations/0005_auto_20161004_1500.py b/sounds/migrations/0005_auto_20161004_1500.py index dde5a382b3..e901196e98 100644 --- a/sounds/migrations/0005_auto_20161004_1500.py +++ b/sounds/migrations/0005_auto_20161004_1500.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-04 15:00 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0006_auto_20161005_1533.py b/sounds/migrations/0006_auto_20161005_1533.py index 0f6eb1e5f8..0ae6804c89 100644 --- a/sounds/migrations/0006_auto_20161005_1533.py +++ b/sounds/migrations/0006_auto_20161005_1533.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-05 15:33 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0007_auto_20161018_1809.py b/sounds/migrations/0007_auto_20161018_1809.py index efa1bfdd82..72d8f90f32 100644 --- a/sounds/migrations/0007_auto_20161018_1809.py +++ b/sounds/migrations/0007_auto_20161018_1809.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-10-18 18:09 -from __future__ import unicode_literals from django.db import migrations, models @@ -19,6 +17,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='pack', - unique_together=set([('user', 'name', 'is_deleted')]), + unique_together={('user', 'name', 'is_deleted')}, ), ] diff --git a/sounds/migrations/0008_soundoftheday.py b/sounds/migrations/0008_soundoftheday.py index 55db688763..6632c3abff 100644 --- a/sounds/migrations/0008_soundoftheday.py +++ b/sounds/migrations/0008_soundoftheday.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-20 16:47 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0009_download_license.py b/sounds/migrations/0009_download_license.py index fdcd0c6b38..4bf5671067 100644 --- a/sounds/migrations/0009_download_license.py +++ b/sounds/migrations/0009_download_license.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-12 12:53 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0010_auto_20170712_1537.py b/sounds/migrations/0010_auto_20170712_1537.py index 96ba3f3071..b54ec5a68f 100644 --- a/sounds/migrations/0010_auto_20170712_1537.py +++ b/sounds/migrations/0010_auto_20170712_1537.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-07-12 15:37 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0011_auto_20170928_1441.py b/sounds/migrations/0011_auto_20170928_1441.py index 1880db87b4..c369c5343b 100644 --- a/sounds/migrations/0011_auto_20170928_1441.py +++ b/sounds/migrations/0011_auto_20170928_1441.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-09-28 14:41 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0012_auto_20171002_1710.py b/sounds/migrations/0012_auto_20171002_1710.py index 345364f095..9221b9e8a8 100644 --- a/sounds/migrations/0012_auto_20171002_1710.py +++ b/sounds/migrations/0012_auto_20171002_1710.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-10-02 17:10 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0013_remove_triggers.py b/sounds/migrations/0013_remove_triggers.py index b1bd3ffbbd..08765b487f 100644 --- a/sounds/migrations/0013_remove_triggers.py +++ b/sounds/migrations/0013_remove_triggers.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-10-05 12:53 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0014_auto_20171124_1628.py b/sounds/migrations/0014_auto_20171124_1628.py index d2211ce82f..ea257fcc47 100644 --- a/sounds/migrations/0014_auto_20171124_1628.py +++ b/sounds/migrations/0014_auto_20171124_1628.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-24 16:28 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0014_packdownload_packdownloadjson_packdownloadsound.py b/sounds/migrations/0014_packdownload_packdownloadjson_packdownloadsound.py index 45be80c4fa..c0478e01ab 100644 --- a/sounds/migrations/0014_packdownload_packdownloadjson_packdownloadsound.py +++ b/sounds/migrations/0014_packdownload_packdownloadjson_packdownloadsound.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-22 12:38 -from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb diff --git a/sounds/migrations/0015_auto_20171124_1651.py b/sounds/migrations/0015_auto_20171124_1651.py index c17e4f4674..fa34831908 100644 --- a/sounds/migrations/0015_auto_20171124_1651.py +++ b/sounds/migrations/0015_auto_20171124_1651.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-11-24 16:51 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0016_merge_20171201_1822.py b/sounds/migrations/0016_merge_20171201_1822.py index 891e92fd1f..64ad6a8baf 100644 --- a/sounds/migrations/0016_merge_20171201_1822.py +++ b/sounds/migrations/0016_merge_20171201_1822.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-12-01 18:22 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0017_auto_20180117_1553.py b/sounds/migrations/0017_auto_20180117_1553.py index 0db9a65a59..407decd147 100644 --- a/sounds/migrations/0017_auto_20180117_1553.py +++ b/sounds/migrations/0017_auto_20180117_1553.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-17 15:53 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0018_auto_20180209_1540.py b/sounds/migrations/0018_auto_20180209_1540.py index 13f6368bf0..f64c27c192 100644 --- a/sounds/migrations/0018_auto_20180209_1540.py +++ b/sounds/migrations/0018_auto_20180209_1540.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-09 15:40 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0019_bulkuploadprogress.py b/sounds/migrations/0019_bulkuploadprogress.py index 5a694d2350..86aa40431c 100644 --- a/sounds/migrations/0019_bulkuploadprogress.py +++ b/sounds/migrations/0019_bulkuploadprogress.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-01-03 15:06 -from __future__ import unicode_literals from django.conf import settings import django.contrib.postgres.fields.jsonb diff --git a/sounds/migrations/0019_remove_download_pack.py b/sounds/migrations/0019_remove_download_pack.py index f884b03707..13706c9c10 100644 --- a/sounds/migrations/0019_remove_download_pack.py +++ b/sounds/migrations/0019_remove_download_pack.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-02-09 15:52 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0020_update_download_indexes.py b/sounds/migrations/0020_update_download_indexes.py index 1cde3a10ed..4d43d71b2d 100644 --- a/sounds/migrations/0020_update_download_indexes.py +++ b/sounds/migrations/0020_update_download_indexes.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-20 15:16 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0021_auto_20180320_1554.py b/sounds/migrations/0021_auto_20180320_1554.py index 36135f7adb..eeea4761b3 100644 --- a/sounds/migrations/0021_auto_20180320_1554.py +++ b/sounds/migrations/0021_auto_20180320_1554.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-20 15:54 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0022_auto_20180321_1048.py b/sounds/migrations/0022_auto_20180321_1048.py index 23e142092e..a11c7fd12d 100644 --- a/sounds/migrations/0022_auto_20180321_1048.py +++ b/sounds/migrations/0022_auto_20180321_1048.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-21 10:48 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0023_auto_20180322_1129.py b/sounds/migrations/0023_auto_20180322_1129.py index 748fd7b11c..288855c2e4 100644 --- a/sounds/migrations/0023_auto_20180322_1129.py +++ b/sounds/migrations/0023_auto_20180322_1129.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-03-22 11:29 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0024_auto_20180503_1326.py b/sounds/migrations/0024_auto_20180503_1326.py index d408d02913..ba1d1c4d64 100644 --- a/sounds/migrations/0024_auto_20180503_1326.py +++ b/sounds/migrations/0024_auto_20180503_1326.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-03 13:26 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/sounds/migrations/0024_merge_20180403_1616.py b/sounds/migrations/0024_merge_20180403_1616.py index 82860f89ae..06b91adf42 100644 --- a/sounds/migrations/0024_merge_20180403_1616.py +++ b/sounds/migrations/0024_merge_20180403_1616.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-03 16:16 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0025_bulkuploadprogress_original_csv_filename.py b/sounds/migrations/0025_bulkuploadprogress_original_csv_filename.py index ed37ff5258..2881ac7e25 100644 --- a/sounds/migrations/0025_bulkuploadprogress_original_csv_filename.py +++ b/sounds/migrations/0025_bulkuploadprogress_original_csv_filename.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-04 16:14 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0026_auto_20180404_1652.py b/sounds/migrations/0026_auto_20180404_1652.py index 5654b30538..042837d8e8 100644 --- a/sounds/migrations/0026_auto_20180404_1652.py +++ b/sounds/migrations/0026_auto_20180404_1652.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-04 16:52 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0027_auto_20180406_1208.py b/sounds/migrations/0027_auto_20180406_1208.py index 24a0dacb8a..d5460a1fc6 100644 --- a/sounds/migrations/0027_auto_20180406_1208.py +++ b/sounds/migrations/0027_auto_20180406_1208.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-06 12:08 -from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models diff --git a/sounds/migrations/0028_auto_20180411_1634.py b/sounds/migrations/0028_auto_20180411_1634.py index 97ad390600..427764ea4a 100644 --- a/sounds/migrations/0028_auto_20180411_1634.py +++ b/sounds/migrations/0028_auto_20180411_1634.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-04-11 16:34 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0029_merge_20180510_1627.py b/sounds/migrations/0029_merge_20180510_1627.py index 490b0ab594..b0fea04051 100644 --- a/sounds/migrations/0029_merge_20180510_1627.py +++ b/sounds/migrations/0029_merge_20180510_1627.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-05-10 16:27 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0030_auto_20180618_1305.py b/sounds/migrations/0030_auto_20180618_1305.py index 16c55e532a..26ef1b0b9f 100644 --- a/sounds/migrations/0030_auto_20180618_1305.py +++ b/sounds/migrations/0030_auto_20180618_1305.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-06-18 13:05 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0031_soundanalysis.py b/sounds/migrations/0031_soundanalysis.py index 2b6dd35d2f..ac2ca149f2 100644 --- a/sounds/migrations/0031_soundanalysis.py +++ b/sounds/migrations/0031_soundanalysis.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-09-05 11:53 -from __future__ import unicode_literals import django.contrib.postgres.fields.jsonb from django.db import migrations, models diff --git a/sounds/migrations/0032_auto_20180905_1301.py b/sounds/migrations/0032_auto_20180905_1301.py index f474dac3ac..45b7df3b7b 100644 --- a/sounds/migrations/0032_auto_20180905_1301.py +++ b/sounds/migrations/0032_auto_20180905_1301.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2018-09-05 13:01 -from __future__ import unicode_literals from django.db import migrations @@ -14,6 +12,6 @@ class Migration(migrations.Migration): operations = [ migrations.AlterUniqueTogether( name='soundanalysis', - unique_together=set([('sound', 'extractor')]), + unique_together={('sound', 'extractor')}, ), ] diff --git a/sounds/migrations/0033_auto_20190528_1554.py b/sounds/migrations/0033_auto_20190528_1554.py index 17b6596a6c..72aa47d533 100644 --- a/sounds/migrations/0033_auto_20190528_1554.py +++ b/sounds/migrations/0033_auto_20190528_1554.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-28 15:54 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0034_make_latest_index_20190712_1616.py b/sounds/migrations/0034_make_latest_index_20190712_1616.py index 7658856452..8baae8dfff 100644 --- a/sounds/migrations/0034_make_latest_index_20190712_1616.py +++ b/sounds/migrations/0034_make_latest_index_20190712_1616.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-07-12 16:16 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0035_auto_20190724_1509.py b/sounds/migrations/0035_auto_20190724_1509.py index 1c89ee808e..cf297f2932 100644 --- a/sounds/migrations/0035_auto_20190724_1509.py +++ b/sounds/migrations/0035_auto_20190724_1509.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-07-24 15:09 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0036_sound_uploaded_with_bulk_upload_progress.py b/sounds/migrations/0036_sound_uploaded_with_bulk_upload_progress.py index 8b24f2448a..ddc134f4f8 100644 --- a/sounds/migrations/0036_sound_uploaded_with_bulk_upload_progress.py +++ b/sounds/migrations/0036_sound_uploaded_with_bulk_upload_progress.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2020-04-29 15:52 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/sounds/migrations/0037_license_short_summary.py b/sounds/migrations/0037_license_short_summary.py index 79becad118..ba48e04372 100644 --- a/sounds/migrations/0037_license_short_summary.py +++ b/sounds/migrations/0037_license_short_summary.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-02-05 10:15 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0038_auto_20210412_1539.py b/sounds/migrations/0038_auto_20210412_1539.py index f61e7f9e11..664a6f544e 100644 --- a/sounds/migrations/0038_auto_20210412_1539.py +++ b/sounds/migrations/0038_auto_20210412_1539.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-04-12 15:39 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/sounds/migrations/0039_auto_20210607_1404.py b/sounds/migrations/0039_auto_20210607_1404.py index 1acf598e95..ebb41016f7 100644 --- a/sounds/migrations/0039_auto_20210607_1404.py +++ b/sounds/migrations/0039_auto_20210607_1404.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2021-06-07 14:04 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0040_auto_20220207_1627.py b/sounds/migrations/0040_auto_20220207_1627.py index 8528e3ce8d..c409301949 100644 --- a/sounds/migrations/0040_auto_20220207_1627.py +++ b/sounds/migrations/0040_auto_20220207_1627.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-02-07 16:27 -from __future__ import unicode_literals from django.db import migrations, models @@ -43,6 +41,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='soundanalysis', - unique_together=set([('sound', 'analyzer')]), + unique_together={('sound', 'analyzer')}, ), ] diff --git a/sounds/migrations/0041_soundanalysis_analysis_time.py b/sounds/migrations/0041_soundanalysis_analysis_time.py index 86d4456654..fafbb3bdcf 100644 --- a/sounds/migrations/0041_soundanalysis_analysis_time.py +++ b/sounds/migrations/0041_soundanalysis_analysis_time.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-02-08 12:32 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0042_auto_20220209_1027.py b/sounds/migrations/0042_auto_20220209_1027.py index f742971467..2f9e9e3d20 100644 --- a/sounds/migrations/0042_auto_20220209_1027.py +++ b/sounds/migrations/0042_auto_20220209_1027.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-02-09 10:27 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0043_auto_20220209_1027.py b/sounds/migrations/0043_auto_20220209_1027.py index e0fb51efc7..28b1451f55 100644 --- a/sounds/migrations/0043_auto_20220209_1027.py +++ b/sounds/migrations/0043_auto_20220209_1027.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-02-09 10:27 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/migrations/0044_auto_20220209_1136.py b/sounds/migrations/0044_auto_20220209_1136.py index aab8c3a666..c5b112f6d0 100644 --- a/sounds/migrations/0044_auto_20220209_1136.py +++ b/sounds/migrations/0044_auto_20220209_1136.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-02-09 11:36 -from __future__ import unicode_literals from django.db import models, migrations @@ -17,7 +15,7 @@ def update_existing_ac_analysis_objects(apps, schema_editor): if sa.analysis_data: updated_analysis_data = {} for key, value in sa.analysis_data.items(): - updated_analysis_data['ac_{0}'.format(key)] = value + updated_analysis_data['ac_{}'.format(key)] = value sa.analysis_data = updated_analysis_data sa.save() diff --git a/sounds/migrations/0045_add_new_licenses.py b/sounds/migrations/0045_add_new_licenses.py index f5ea13b59d..66165013b7 100644 --- a/sounds/migrations/0045_add_new_licenses.py +++ b/sounds/migrations/0045_add_new_licenses.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2022-03-18 11:39 -from __future__ import unicode_literals from django.db import migrations diff --git a/sounds/migrations/0046_auto_20230201_1102.py b/sounds/migrations/0046_auto_20230201_1102.py index 8521f7da0e..13ff50ece8 100644 --- a/sounds/migrations/0046_auto_20230201_1102.py +++ b/sounds/migrations/0046_auto_20230201_1102.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.29 on 2023-02-01 11:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/sounds/models.py b/sounds/models.py index c71cd911ce..e805aec90d 100644 --- a/sounds/models.py +++ b/sounds/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,12 +18,9 @@ # See AUTHORS file. # -from __future__ import division from future import standard_library standard_library.install_aliases() from future.utils import python_2_unicode_compatible -from builtins import str -from builtins import object from past.utils import old_div import datetime import glob @@ -295,7 +290,7 @@ def has_line_validation_errors(self): return len(self.validation_output['lines_with_errors']) > 0 return False - class Meta(object): + class Meta: permissions = ( ("can_describe_in_bulk", "Can use the Bulk Describe feature."), ) @@ -387,7 +382,7 @@ def get_analyzers_data_left_join_sql(self): def get_analysis_state_essentia_exists_sql(self): """Returns the SQL bits to add analysis_state_essentia_exists to the returned data indicating if thers is a SoundAnalysis objects existing for th given sound_id for the essentia analyzer and with status OK""" - return " exists(select 1 from sounds_soundanalysis where sounds_soundanalysis.sound_id = sound.id AND sounds_soundanalysis.analyzer = '{0}' AND sounds_soundanalysis.analysis_status = 'OK') as analysis_state_essentia_exists,".format(settings.FREESOUND_ESSENTIA_EXTRACTOR_NAME) + return " exists(select 1 from sounds_soundanalysis where sounds_soundanalysis.sound_id = sound.id AND sounds_soundanalysis.analyzer = '{}' AND sounds_soundanalysis.analysis_status = 'OK') as analysis_state_essentia_exists,".format(settings.FREESOUND_ESSENTIA_EXTRACTOR_NAME) def bulk_query_solr(self, sound_ids): """For each sound, get all fields needed to index the sound in Solr. Using this custom query to avoid the need @@ -548,7 +543,7 @@ def ordered_ids(self, sound_ids): class PublicSoundManager(models.Manager): """ a class which only returns public sounds """ def get_queryset(self): - return super(PublicSoundManager, self).get_queryset().filter(moderation_state="OK", processing_state="OK") + return super().get_queryset().filter(moderation_state="OK", processing_state="OK") class Sound(SocialModel): @@ -785,9 +780,9 @@ def get_large_thumbnail_abs_url(self): def get_channels_display(self): if self.channels == 1: - return u"Mono" + return "Mono" elif self.channels == 2: - return u"Stereo" + return "Stereo" else: return self.channels @@ -899,7 +894,7 @@ def get_sound_sources_as_set(self): """ Returns a set object with the integer sound IDs of the current sources of the sound """ - return set(source["id"] for source in self.sources.all().values("id")) + return {source["id"] for source in self.sources.all().values("id")} def set_sources(self, new_sources): """ @@ -1328,7 +1323,7 @@ class SoundOfTheDay(models.Model): objects = SoundOfTheDayManager() def __str__(self): - return u'Random sound of the day {0}'.format(self.date_display) + return 'Random sound of the day {}'.format(self.date_display) def notify_by_email(self): """Notify the user of this sound by email that their sound has been chosen @@ -1674,9 +1669,9 @@ class Flag(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __unicode__(self): - return u"%s: %s" % (self.reason_type, self.reason[:100]) + return "%s: %s" % (self.reason_type, self.reason[:100]) - class Meta(object): + class Meta: ordering = ("-created",) @@ -1686,7 +1681,7 @@ class Download(models.Model): license = models.ForeignKey(License) created = models.DateTimeField(db_index=True, auto_now_add=True) - class Meta(object): + class Meta: ordering = ("-created",) indexes = [ models.Index(fields=['user', 'sound']), @@ -1758,7 +1753,7 @@ class SoundLicenseHistory(models.Model): sound = models.ForeignKey(Sound) created = models.DateTimeField(db_index=True, auto_now_add=True) - class Meta(object): + class Meta: ordering = ("-created",) @@ -1859,7 +1854,7 @@ def get_analysis_logs(self): file_contents = fid.read() fid.close() return file_contents - except IOError: + except OSError: return 'No logs available...' def re_run_analysis(self, verbose=True): @@ -1868,7 +1863,7 @@ def re_run_analysis(self, verbose=True): def __str__(self): return 'Analysis of sound {} with {}'.format(self.sound_id, self.analyzer) - class Meta(object): + class Meta: unique_together = (("sound", "analyzer")) # one sounds.SoundAnalysis object per sound<>analyzer combination def on_delete_sound_analysis(sender, instance, **kwargs): diff --git a/sounds/templatetags/display_pack.py b/sounds/templatetags/display_pack.py index 76f377544e..9bd0051823 100644 --- a/sounds/templatetags/display_pack.py +++ b/sounds/templatetags/display_pack.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django import template diff --git a/sounds/templatetags/display_remix.py b/sounds/templatetags/display_remix.py index 0e9ba8dc58..cdc730837c 100644 --- a/sounds/templatetags/display_remix.py +++ b/sounds/templatetags/display_remix.py @@ -18,9 +18,7 @@ # See AUTHORS file. # -from __future__ import absolute_import, division #avoid namespace clash with 'tags' templatetag -from builtins import str from django import template import json diff --git a/sounds/templatetags/display_sound.py b/sounds/templatetags/display_sound.py index 9ab02221bb..af4873df3d 100644 --- a/sounds/templatetags/display_sound.py +++ b/sounds/templatetags/display_sound.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django import template from django.conf import settings diff --git a/sounds/templatetags/sound_signature.py b/sounds/templatetags/sound_signature.py index 8014ef1252..7ce8206850 100644 --- a/sounds/templatetags/sound_signature.py +++ b/sounds/templatetags/sound_signature.py @@ -1,6 +1,5 @@ from future import standard_library standard_library.install_aliases() -from builtins import str import urllib.parse from django.urls import reverse from django.contrib.sites.models import Site diff --git a/sounds/tests/test_manager.py b/sounds/tests/test_manager.py index 4c8c900b12..d1e667d952 100644 --- a/sounds/tests/test_manager.py +++ b/sounds/tests/test_manager.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -import six from django.conf import settings from django.test import TestCase @@ -70,7 +69,7 @@ def test_bulk_query_id_field_contents(self): self.assertEqual(Sound.objects.get(id=sound.id).original_filename, sound.original_filename) self.assertEqual(Sound.objects.get(id=sound.id).pack_id, sound.pack_id) self.assertEqual(Sound.objects.get(id=sound.id).license_id, sound.license_id) - six.assertCountEqual(self, Sound.objects.get(id=sound.id).get_sound_tags(), sound.tag_array) + self.assertCountEqual(Sound.objects.get(id=sound.id).get_sound_tags(), sound.tag_array) def test_bulk_query_solr_num_queries(self): @@ -89,7 +88,7 @@ def test_bulk_query_solr_field_contents(self): self.assertEqual(Sound.objects.get(id=sound.id).md5, sound.md5) self.assertEqual(Sound.objects.get(id=sound.id).pack_id, sound.pack_id) self.assertEqual(Sound.objects.get(id=sound.id).license_id, sound.license_id) - six.assertCountEqual(self, Sound.objects.get(id=sound.id).get_sound_tags(), sound.tag_array) + self.assertCountEqual(Sound.objects.get(id=sound.id).get_sound_tags(), sound.tag_array) def test_ordered_ids(self): @@ -123,7 +122,7 @@ def test_bulk_sounds_for_user(self): for i, sound in enumerate(Sound.objects.bulk_sounds_for_user(user_id=self.user.id)): self.assertEqual(self.user.id, sound.user_id) user_sound_ids_bulk_query.append(sound.id) - six.assertCountEqual(self, user_sound_ids, user_sound_ids_bulk_query) + self.assertCountEqual(user_sound_ids, user_sound_ids_bulk_query) def test_bulk_sounds_for_pack(self): @@ -148,7 +147,7 @@ def test_bulk_sounds_for_pack(self): for i, sound in enumerate(Sound.objects.bulk_sounds_for_pack(pack_id=self.pack.id)): self.assertEqual(self.user.id, sound.user_id) pack_sound_ids_bulk_query.append(sound.id) - six.assertCountEqual(self, pack_sound_ids, pack_sound_ids_bulk_query) + self.assertCountEqual(pack_sound_ids, pack_sound_ids_bulk_query) class PublicSoundManagerTest(TestCase): diff --git a/sounds/tests/test_sound.py b/sounds/tests/test_sound.py index ed4cef645f..c8e49a3d5e 100644 --- a/sounds/tests/test_sound.py +++ b/sounds/tests/test_sound.py @@ -18,17 +18,13 @@ # See AUTHORS file. # -from __future__ import print_function -from __future__ import division -from builtins import str from past.utils import old_div import json import os import time from unittest import mock -import six from bs4 import BeautifulSoup from django.conf import settings from django.contrib.auth.models import User @@ -70,7 +66,7 @@ def test_email_notificaiton_on_send_email(self): sound = Sound.objects.get(id=19) commenting_user = User.objects.get(id=2) self.client.force_login(commenting_user) - self.client.post(reverse('sound', args=[sound.user.username, sound.id]), {'comment': u'Test comment'}) + self.client.post(reverse('sound', args=[sound.user.username, sound.id]), {'comment': 'Test comment'}) # Check email was sent notifying about comment self.assertEqual(len(mail.outbox), 1) @@ -84,7 +80,7 @@ def test_email_notificaiton_on_send_email(self): accounts.models.UserEmailSetting.objects.create(user=sound.user, email_type=email_pref) # Make the comment again and assert no new email has been sent - self.client.post(reverse('sound', args=[sound.user.username, sound.id]), {'comment': u'Test comment'}) + self.client.post(reverse('sound', args=[sound.user.username, sound.id]), {'comment': 'Test comment'}) self.assertEqual(len(mail.outbox), 1) def test_unsecure_content(self): @@ -178,7 +174,7 @@ def test_change_sound_owner(self, delete_sounds_from_search_engine): # Delete original user and perform further checks userA.profile.delete_user(delete_user_object_from_db=True) sound = Sound.objects.get(id=target_sound_id) - six.assertCountEqual(self, [ti.id for ti in sound.tags.all()], target_sound_tags) + self.assertCountEqual([ti.id for ti in sound.tags.all()], target_sound_tags) delete_sounds_from_search_engine.assert_has_calls([mock.call([i]) for i in remaining_sound_ids], any_order=True) @@ -291,9 +287,9 @@ def test_edit_sound(self): self.client.force_login(user) resp = self.client.post(reverse('sound-edit', args=[sound.user.username, sound.id]), { - 'submit': [u'submit'], - 'pack-new_pack': [u'new pack name'], - 'pack-pack': [u''], + 'submit': ['submit'], + 'pack-new_pack': ['new pack name'], + 'pack-pack': [''], }) self.assertRedirects(resp, reverse('sound', args=[sound.user.username, sound.id])) self.assertEqual(Pack.objects.get(id=pack.id).num_sounds, 0) # Sound changed from pack @@ -314,10 +310,10 @@ def test_edit_pack(self): sound_ids_pack2.append(sound_ids_pack1.pop()) self.client.force_login(user) resp = self.client.post(reverse('pack-edit', args=[pack2.user.username, pack2.id]), { - 'submit': [u'submit'], - 'pack_sounds': u','.join([str(sid) for sid in sound_ids_pack2]), - 'name': [u'Test pack 1 (edited)'], - 'description': [u'A new description'] + 'submit': ['submit'], + 'pack_sounds': ','.join([str(sid) for sid in sound_ids_pack2]), + 'name': ['Test pack 1 (edited)'], + 'description': ['A new description'] }) self.assertRedirects(resp, reverse('pack', args=[pack2.user.username, pack2.id])) self.assertEqual(Pack.objects.get(id=pack1.id).num_sounds, 1) @@ -329,11 +325,11 @@ def test_edit_pack(self): sound.change_processing_state("OK") sound.change_moderation_state("OK") resp = self.client.post(reverse('pack-edit', args=[pack2.user.username, pack2.id]), { - 'submit': [u'submit'], + 'submit': ['submit'], 'pack_sounds': - u','.join([str(snd.id) for snd in Pack.objects.get(id=pack2.id).sounds.all()] + [str(sound.id)]), - 'name': [u'Test pack 1 (edited again)'], - 'description': [u'A new description'] + ','.join([str(snd.id) for snd in Pack.objects.get(id=pack2.id).sounds.all()] + [str(sound.id)]), + 'name': ['Test pack 1 (edited again)'], + 'description': ['A new description'] }) self.assertRedirects(resp, reverse('pack', args=[pack2.user.username, pack2.id])) self.assertEqual(Pack.objects.get(id=pack1.id).num_sounds, 1) @@ -701,12 +697,12 @@ def test_update_description(self): self._assertCachePresent(cache_keys) # Edit sound - new_description = u'New description' - new_name = u'New name' + new_description = 'New description' + new_name = 'New name' resp = self.client.post(self._get_sound_url('sound-edit'), { 'description-description': new_description, 'description-name': new_name, - 'description-tags': u'tag1 tag2 tag3' + 'description-tags': 'tag1 tag2 tag3' }) self.assertEqual(resp.status_code, 302) @@ -733,13 +729,13 @@ def test_update_description_bw(self): self._assertCachePresent(cache_keys) # Edit sound - new_description = u'New description' - new_name = u'New name' + new_description = 'New description' + new_name = 'New name' resp = self.client.post(self._get_sound_url('sound-edit'), { '0-description': new_description, '0-name': new_name, - '0-tags': u'tag1 tag2 tag3', - '0-license': [u'3'], + '0-tags': 'tag1 tag2 tag3', + '0-license': ['3'], }) self.assertEqual(resp.status_code, 302) @@ -769,7 +765,7 @@ def test_add_remove_comment(self): # Add comment resp = self.client.post(self._get_sound_url('sound'), { - 'comment': u'Test comment' + 'comment': 'Test comment' }, follow=True) # we are testing sound-display, rendering sound view is ok delete_url = self._get_delete_comment_url(resp.content) self._assertCacheAbsent(cache_keys) @@ -1205,10 +1201,10 @@ def setUp(self): def test_update_description_bw(self): test_using_bw_ui(self) self.client.force_login(self.user) - new_description = u'New description' - new_name = u'New name' + new_description = 'New description' + new_name = 'New name' new_tags = ['tag1', 'tag2', 'tag3'] - new_pack_name = u'Name of a new pack' + new_pack_name = 'Name of a new pack' new_sound_sources = Sound.objects.exclude(id=self.sound.id) geotag_lat = 46.31658418182218 resp = self.client.post(reverse('sound-edit', args=[self.sound.user.username, self.sound.id]), { @@ -1216,7 +1212,7 @@ def test_update_description_bw(self): '0-name': new_name, '0-tags': ' '.join(new_tags), '0-license': '3', - '0-sources': ','.join([u'{}'.format(s.id) for s in new_sound_sources]), + '0-sources': ','.join(['{}'.format(s.id) for s in new_sound_sources]), '0-pack': '', '0-new_pack': new_pack_name, '0-lat': '{}'.format(geotag_lat), diff --git a/sounds/views.py b/sounds/views.py index d5baf52f86..baa6efff8a 100644 --- a/sounds/views.py +++ b/sounds/views.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,8 +18,6 @@ # See AUTHORS file. # -from builtins import map -from builtins import str from past.utils import old_div import datetime import json @@ -205,7 +202,7 @@ def front_page(request): top_donor_user_id = cache.get("top_donor_user_id", None) top_donor_donation_amount = cache.get("top_donor_donation_amount", None) if popular_searches is not None: - popular_searches = [(query_terms, '{0}?q={1}'.format(reverse('sounds-search'), query_terms)) + popular_searches = [(query_terms, '{}?q={}'.format(reverse('sounds-search'), query_terms)) for query_terms in popular_searches] current_forum_threads = get_hot_threads(n=10) @@ -627,11 +624,11 @@ def create_sounds(request, forms): sounds_to_process.append(sound) if user.profile.is_whitelisted: messages.add_message(request, messages.INFO, - u'File {} has been described and has been added to freesound.'\ + 'File {} has been described and has been added to freesound.'\ .format(sound.get_absolute_url(), sound.original_filename)) else: messages.add_message(request, messages.INFO, - u'File {} has been described and is now awaiting processing and moderation.'\ + 'File {} has been described and is now awaiting processing and moderation.'\ .format(sound.get_absolute_url(), sound.original_filename)) invalidate_user_template_caches(request.user.id) for moderator in Group.objects.get(name='moderators').user_set.all(): @@ -1039,7 +1036,7 @@ def pack(request, username, pack_id): @redirect_if_old_username_or_404 def packs_for_user(request, username): if using_beastwhoosh(request): - return HttpResponseRedirect(u'{0}?f=username:%22{1}%22&s=Date+added+(newest+first)&g=1&only_p=1'.format(reverse('sounds-search'), username)) + return HttpResponseRedirect('{}?f=username:%22{}%22&s=Date+added+(newest+first)&g=1&only_p=1'.format(reverse('sounds-search'), username)) user = request.parameter_user order = request.GET.get("order", "name") @@ -1057,7 +1054,7 @@ def packs_for_user(request, username): @redirect_if_old_username_or_404 def for_user(request, username): if using_beastwhoosh(request): - return HttpResponseRedirect(u'{0}?f=username:%22{1}%22&s=Date+added+(newest+first)&g=1'.format(reverse('sounds-search'), username)) + return HttpResponseRedirect('{}?f=username:%22{}%22&s=Date+added+(newest+first)&g=1'.format(reverse('sounds-search'), username)) sound_user = request.parameter_user paginator = paginate(request, Sound.public.only('id').filter(user=sound_user), settings.SOUNDS_PER_PAGE) diff --git a/support/admin.py b/support/admin.py index 7c68785e9d..e69de29bb2 100644 --- a/support/admin.py +++ b/support/admin.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- \ No newline at end of file diff --git a/support/models.py b/support/models.py index 7c68785e9d..e69de29bb2 100644 --- a/support/models.py +++ b/support/models.py @@ -1 +0,0 @@ -# -*- coding: utf-8 -*- \ No newline at end of file diff --git a/support/tests.py b/support/tests.py index 4c5b311204..1f402a9d49 100644 --- a/support/tests.py +++ b/support/tests.py @@ -35,12 +35,12 @@ def test_send_support_request_email(self): # try with existing email address request_email = 'test.user+1@gmail.com' send_email_to_support(request_email, subject, message) - self.assert_(True) # This call is not really needed, but makes sense to me + self.assertTrue(True) # This call is not really needed, but makes sense to me # try with non-existing email address request_email = 'test.user+1234678235@gmail.com' send_email_to_support(request_email, subject, message) - self.assert_(True) # This call is not really needed, but makes sense to me + self.assertTrue(True) # This call is not really needed, but makes sense to me def test_create_zendesk_ticket(self): subject = 'test subject' diff --git a/support/views.py b/support/views.py index 238cdf966d..0537e06273 100644 --- a/support/views.py +++ b/support/views.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import logging from django.conf import settings diff --git a/tags/admin.py b/tags/admin.py index 20c4e32956..200f8d6272 100644 --- a/tags/admin.py +++ b/tags/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/tags/migrations/0001_initial.py b/tags/migrations/0001_initial.py index 368176d30c..5ffdc34f23 100644 --- a/tags/migrations/0001_initial.py +++ b/tags/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models @@ -55,6 +53,6 @@ class Migration(migrations.Migration): ), migrations.AlterUniqueTogether( name='taggeditem', - unique_together=set([('tag', 'content_type', 'object_id')]), + unique_together={('tag', 'content_type', 'object_id')}, ), ] diff --git a/tags/models.py b/tags/models.py index 5f9cf8a357..e84dbe53e0 100644 --- a/tags/models.py +++ b/tags/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.contrib.contenttypes import fields from django.contrib.contenttypes.models import ContentType @@ -37,7 +34,7 @@ def __str__(self): def get_browse_tag_url(self): return reverse('tags', self.name) - class Meta(object): + class Meta: ordering = ("name",) @@ -54,12 +51,12 @@ class TaggedItem(models.Model): created = models.DateTimeField(db_index=True, auto_now_add=True) def __str__(self): - return u"%s tagged %s - %s: %s" % (self.user, self.content_type, self.content_type, self.tag) + return "%s tagged %s - %s: %s" % (self.user, self.content_type, self.content_type, self.tag) def get_absolute_url(self): return reverse('tag', args=[smart_text(self.tag.id)]) - class Meta(object): + class Meta: ordering = ("-created",) unique_together = (('tag', 'content_type', 'object_id'),) diff --git a/tags/tests.py b/tags/tests.py index 9310005736..8f37f5c989 100644 --- a/tags/tests.py +++ b/tags/tests.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str from django.test import TestCase from django.urls import reverse diff --git a/tickets/admin.py b/tickets/admin.py index a077451175..dca5f75541 100644 --- a/tickets/admin.py +++ b/tickets/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from django.contrib import admin from .models import Queue, Ticket diff --git a/tickets/forms.py b/tickets/forms.py index 82f3941cdc..e6f12369cf 100644 --- a/tickets/forms.py +++ b/tickets/forms.py @@ -38,7 +38,7 @@ class UserContactForm(UserMessageForm): title = HtmlCleaningCharField() def __init__(self, *args, **kwargs): - super(UserContactForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields.keyOrder = ['title', 'message'] @@ -52,7 +52,7 @@ class AnonymousContactForm(AnonymousMessageForm): email = forms.EmailField() def __init__(self, *args, **kwargs): - super(AnonymousContactForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields.keyOrder = ['email', 'title', 'message'] diff --git a/tickets/migrations/0001_initial.py b/tickets/migrations/0001_initial.py index 58d5cb2aeb..31526cf494 100644 --- a/tickets/migrations/0001_initial.py +++ b/tickets/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/tickets/migrations/0002_auto_20160505_1202.py b/tickets/migrations/0002_auto_20160505_1202.py index b3abde94a7..4ec323850c 100644 --- a/tickets/migrations/0002_auto_20160505_1202.py +++ b/tickets/migrations/0002_auto_20160505_1202.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-05-05 12:02 -from __future__ import unicode_literals from django.db import migrations, models diff --git a/tickets/migrations/0003_ticket_sound.py b/tickets/migrations/0003_ticket_sound.py index 446a5bd742..27426e1e95 100644 --- a/tickets/migrations/0003_ticket_sound.py +++ b/tickets/migrations/0003_ticket_sound.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-08 13:07 -from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion diff --git a/tickets/migrations/0004_copy.py b/tickets/migrations/0004_copy.py index 8b000056eb..5e58f65dfd 100644 --- a/tickets/migrations/0004_copy.py +++ b/tickets/migrations/0004_copy.py @@ -1,6 +1,3 @@ -# -*- coding: utf-8 -*- -from __future__ import unicode_literals - from tickets import TICKET_STATUS_CLOSED from django.db import models, migrations from django.contrib.contenttypes.models import ContentType diff --git a/tickets/migrations/0005_auto_20160608_1546.py b/tickets/migrations/0005_auto_20160608_1546.py index 4bd506e68b..41e080d730 100644 --- a/tickets/migrations/0005_auto_20160608_1546.py +++ b/tickets/migrations/0005_auto_20160608_1546.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-06-08 15:46 -from __future__ import unicode_literals from django.db import migrations diff --git a/tickets/migrations/0006_remove_ticket_source.py b/tickets/migrations/0006_remove_ticket_source.py index 4dada83d97..495583b6f3 100644 --- a/tickets/migrations/0006_remove_ticket_source.py +++ b/tickets/migrations/0006_remove_ticket_source.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-07-13 10:36 -from __future__ import unicode_literals from django.db import migrations diff --git a/tickets/migrations/0007_auto_20170626_1755.py b/tickets/migrations/0007_auto_20170626_1755.py index 434ed32290..f4bc56d77a 100644 --- a/tickets/migrations/0007_auto_20170626_1755.py +++ b/tickets/migrations/0007_auto_20170626_1755.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2017-06-26 17:55 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/tickets/migrations/0008_copy_message_to_ticket.py b/tickets/migrations/0008_copy_message_to_ticket.py index 740221b273..d811ca95ac 100644 --- a/tickets/migrations/0008_copy_message_to_ticket.py +++ b/tickets/migrations/0008_copy_message_to_ticket.py @@ -1,5 +1,3 @@ -from __future__ import unicode_literals - from django.db import models, migrations from django.contrib.contenttypes.models import ContentType diff --git a/tickets/migrations/0009_auto_20190528_1554.py b/tickets/migrations/0009_auto_20190528_1554.py index 975e6f3fc1..fef8635142 100644 --- a/tickets/migrations/0009_auto_20190528_1554.py +++ b/tickets/migrations/0009_auto_20190528_1554.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.11.20 on 2019-05-28 15:54 -from __future__ import unicode_literals from django.db import migrations diff --git a/tickets/models.py b/tickets/models.py index e116bca130..794d147acc 100644 --- a/tickets/models.py +++ b/tickets/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,8 +18,6 @@ # See AUTHORS file. # -from builtins import str -from builtins import object from django.conf import settings from django.contrib.auth.models import User, Group from django.contrib.contenttypes.models import ContentType @@ -102,9 +98,9 @@ def get_absolute_url(self): return reverse('ticket', args=[smart_text(self.key)]) def __str__(self): - return u"pk %s, key %s" % (self.id, self.key) + return "pk %s, key %s" % (self.id, self.key) - class Meta(object): + class Meta: ordering = ("-created",) permissions = ( ("can_moderate", "Can moderate stuff."), @@ -119,10 +115,10 @@ class TicketComment(models.Model): moderator_only = models.BooleanField(default=False) def __str__(self): - return u"<# Message - ticket_id: %s, ticket_key: %s>" % \ + return "<# Message - ticket_id: %s, ticket_key: %s>" % \ (self.ticket.id, self.ticket.key) - class Meta(object): + class Meta: ordering = ("-created",) diff --git a/tickets/tests.py b/tickets/tests.py index 59d8baad89..f2a808b05f 100644 --- a/tickets/tests.py +++ b/tickets/tests.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import from future import standard_library standard_library.install_aliases() @@ -161,12 +160,12 @@ def setUp(self): def _perform_action(self, action): return self.client.post(reverse('tickets-moderation-assigned', args=[self.test_moderator.id]), { - 'action': action, 'message': u'', 'ticket': self.ticket.id, + 'action': action, 'message': '', 'ticket': self.ticket.id, 'is_explicit': IS_EXPLICIT_KEEP_USER_PREFERENCE_KEY}) @mock.patch('sounds.models.delete_sounds_from_search_engine') def test_delete_ticket_from_queue(self, delete_sound_solr): - resp = self._perform_action(u'Delete') + resp = self._perform_action('Delete') self.assertEqual(resp.status_code, 200) delete_sound_solr.assert_called_once_with([self.sound.id]) @@ -177,7 +176,7 @@ def test_delete_ticket_from_queue(self, delete_sound_solr): @mock.patch('general.tasks.whitelist_user.delay') def test_whitelist_from_queue(self, whitelist_task): - self._perform_action(u'Whitelist') + self._perform_action('Whitelist') whitelist_task.assert_called_once_with(ticket_ids=[self.ticket.id]) def _assert_ticket_and_sound_fields(self, status, assignee, moderation_state): @@ -191,17 +190,17 @@ def _assert_ticket_and_sound_fields(self, status, assignee, moderation_state): self.assertEqual(self.ticket.assignee, assignee) def test_approve_ticket_from_queue(self): - resp = self._perform_action(u'Approve') + resp = self._perform_action('Approve') self.assertEqual(resp.status_code, 200) self._assert_ticket_and_sound_fields(TICKET_STATUS_CLOSED, self.test_moderator, 'OK') def test_return_ticket_from_queue(self): - resp = self._perform_action(u'Return') + resp = self._perform_action('Return') self.assertEqual(resp.status_code, 200) self._assert_ticket_and_sound_fields(TICKET_STATUS_NEW, None, 'PE') def test_defer_ticket_from_queue(self): - resp = self._perform_action(u'Defer') + resp = self._perform_action('Defer') self.assertEqual(resp.status_code, 200) self._assert_ticket_and_sound_fields(TICKET_STATUS_DEFERRED, self.test_moderator, 'PE') @@ -233,7 +232,7 @@ def setUp(self): def _perform_action(self, action, is_explicit_flag_key): return self.client.post(reverse('tickets-moderation-assigned', args=[self.test_moderator.id]), { - 'action': action, 'message': u'', 'ticket': self.ticket.id, 'is_explicit': is_explicit_flag_key}) + 'action': action, 'message': '', 'ticket': self.ticket.id, 'is_explicit': is_explicit_flag_key}) def test_keep_is_explicit_preference_for_explicit_sound(self): """Test that when approving a sound marked as 'is_explicit' it continues to be marked as such the moderator @@ -241,7 +240,7 @@ def test_keep_is_explicit_preference_for_explicit_sound(self): """ self.ticket.sound.is_explicit = True self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_KEEP_USER_PREFERENCE_KEY) + self._perform_action('Approve', IS_EXPLICIT_KEEP_USER_PREFERENCE_KEY) self.ticket.sound.refresh_from_db() self.assertEqual(self.ticket.sound.is_explicit, True) @@ -251,7 +250,7 @@ def test_keep_is_explicit_preference_for_non_explicit_sound(self): """ self.ticket.sound.is_explicit = False self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_KEEP_USER_PREFERENCE_KEY) + self._perform_action('Approve', IS_EXPLICIT_KEEP_USER_PREFERENCE_KEY) self.ticket.sound.refresh_from_db() self.assertEqual(self.ticket.sound.is_explicit, False) @@ -261,7 +260,7 @@ def test_add_is_explicit_flag_for_explicit_sound(self): """ self.ticket.sound.is_explicit = True self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_ADD_FLAG_KEY) + self._perform_action('Approve', IS_EXPLICIT_ADD_FLAG_KEY) self.ticket.sound.refresh_from_db() self.assertTrue(self.ticket.sound.is_explicit) @@ -271,7 +270,7 @@ def test_add_is_explicit_flag_for_non_explicit_sound(self): """ self.ticket.sound.is_explicit = False self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_ADD_FLAG_KEY) + self._perform_action('Approve', IS_EXPLICIT_ADD_FLAG_KEY) self.ticket.sound.refresh_from_db() self.assertTrue(self.ticket.sound.is_explicit) @@ -281,7 +280,7 @@ def test_remove_is_explicit_flag_for_non_explicit_sound(self): """ self.ticket.sound.is_explicit = False self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_REMOVE_FLAG_KEY) + self._perform_action('Approve', IS_EXPLICIT_REMOVE_FLAG_KEY) self.ticket.sound.refresh_from_db() self.assertFalse(self.ticket.sound.is_explicit) @@ -291,6 +290,6 @@ def test_remove_is_explicit_flag_for_explicit_sound(self): """ self.ticket.sound.is_explicit = True self.ticket.sound.save() - self._perform_action(u'Approve', IS_EXPLICIT_REMOVE_FLAG_KEY) + self._perform_action('Approve', IS_EXPLICIT_REMOVE_FLAG_KEY) self.ticket.sound.refresh_from_db() self.assertFalse(self.ticket.sound.is_explicit) diff --git a/tickets/urls.py b/tickets/urls.py index 356bbf6739..a44ebbaa60 100644 --- a/tickets/urls.py +++ b/tickets/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/tickets/views.py b/tickets/views.py index 9d7c91087c..2bdf474558 100644 --- a/tickets/views.py +++ b/tickets/views.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import absolute_import import datetime import json diff --git a/utils/audioprocessing/color_schemes.py b/utils/audioprocessing/color_schemes.py index 8914fa5ae7..d83b9e8283 100644 --- a/utils/audioprocessing/color_schemes.py +++ b/utils/audioprocessing/color_schemes.py @@ -1,6 +1,3 @@ -from __future__ import division -from builtins import map -from builtins import range from past.utils import old_div from PIL import ImageColor from functools import partial diff --git a/utils/audioprocessing/convert_to_mp3.py b/utils/audioprocessing/convert_to_mp3.py index 58e95eaf40..e5e693ee40 100755 --- a/utils/audioprocessing/convert_to_mp3.py +++ b/utils/audioprocessing/convert_to_mp3.py @@ -20,7 +20,6 @@ # See AUTHORS file. # -from __future__ import absolute_import import sys from .processing import convert_to_mp3 diff --git a/utils/audioprocessing/convert_to_wav.py b/utils/audioprocessing/convert_to_wav.py index 10563e8c7e..5e1b7aff2e 100644 --- a/utils/audioprocessing/convert_to_wav.py +++ b/utils/audioprocessing/convert_to_wav.py @@ -20,8 +20,6 @@ # See AUTHORS file. # -from __future__ import print_function -from __future__ import absolute_import import sys from .processing import convert_to_wav, audio_info, AudioProcessingException diff --git a/utils/audioprocessing/freesound_audio_processing.py b/utils/audioprocessing/freesound_audio_processing.py index d06f708a95..bf6325ea4f 100644 --- a/utils/audioprocessing/freesound_audio_processing.py +++ b/utils/audioprocessing/freesound_audio_processing.py @@ -18,12 +18,8 @@ # See AUTHORS file. # -from __future__ import absolute_import -from __future__ import division -from builtins import str from past.utils import old_div -from builtins import object import json import os import signal @@ -90,7 +86,7 @@ def check_if_free_space(directory=settings.PROCESSING_TEMP_DIR, "aborting task as there might not be enough space for temp files") -class FreesoundAudioProcessorBase(object): +class FreesoundAudioProcessorBase: """ Base class to be used for Freesound processing and analysis code. It implements methods common to both use cases. @@ -185,7 +181,7 @@ def convert_to_pcm(self, sound_path, tmp_directory, force_use_ffmpeg=False, mono class FreesoundAudioProcessor(FreesoundAudioProcessorBase): def set_failure(self, message, error=None): - super(FreesoundAudioProcessor, self).set_failure(message, error) + super().set_failure(message, error) self.sound.set_processing_ongoing_state("FI") self.sound.change_processing_state("FA", processing_log=self.work_log) diff --git a/utils/audioprocessing/processing.py b/utils/audioprocessing/processing.py index 0c95f41b22..c1adf9bee0 100644 --- a/utils/audioprocessing/processing.py +++ b/utils/audioprocessing/processing.py @@ -20,14 +20,7 @@ # See AUTHORS file. # -from __future__ import print_function -from __future__ import absolute_import -from __future__ import division - -from builtins import str -from builtins import range -from builtins import object -from builtins import bytes + from past.utils import old_div import math import os @@ -46,7 +39,7 @@ class AudioProcessingException(Exception): pass -class TestAudioFile(object): +class TestAudioFile: """A class that mimics pysndfile.PySndfile but generates noise instead of reading a wave file. Additionally it can be told to have a "broken" header and thus crashing in the middle of the file. Also useful for testing ultra-short files of 20 samples.""" @@ -99,7 +92,7 @@ def get_max_level(filename): return max_value -class AudioProcessor(object): +class AudioProcessor: """ The audio processor processes chunks of audio an calculates the spectrac centroid and the peak samples in that chunk of audio. @@ -281,7 +274,7 @@ def interpolate_colors(colors, flat=False, num_colors=256): return palette -class WaveformImage(object): +class WaveformImage: """ Given peaks and spectral centroids from the AudioProcessor, this class will construct a wavefile image which can be saved as PNG. @@ -361,7 +354,7 @@ def save(self, filename): self.image.save(filename) -class SpectrogramImage(object): +class SpectrogramImage: """ Given spectra from the AudioProcessor, this class will construct a wavefile image which can be saved as PNG. diff --git a/utils/audioprocessing/wav2png.py b/utils/audioprocessing/wav2png.py index c072705218..55e6d78f40 100755 --- a/utils/audioprocessing/wav2png.py +++ b/utils/audioprocessing/wav2png.py @@ -20,10 +20,7 @@ # See AUTHORS file. # -from __future__ import print_function, absolute_import -from __future__ import division -from builtins import str from past.utils import old_div import argparse diff --git a/utils/aws.py b/utils/aws.py index 43bab70e2d..1793ca6e2f 100644 --- a/utils/aws.py +++ b/utils/aws.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.conf import settings from boto3 import client @@ -48,7 +47,7 @@ def init_client(service): aws_secret_access_key=settings.AWS_SQS_SECRET_ACCESS_KEY) -class EmailStats(object): +class EmailStats: total = 0 bounces = 0 complaints = 0 diff --git a/utils/dbtime.py b/utils/dbtime.py index ce8be2407e..89c9fef34b 100644 --- a/utils/dbtime.py +++ b/utils/dbtime.py @@ -20,14 +20,13 @@ from datetime import datetime -from builtins import object from django.conf import settings from django.core.cache import cache from sounds.models import Sound, Download -class DBTime(object): +class DBTime: last_time = None @staticmethod diff --git a/utils/downloads.py b/utils/downloads.py index a6ab48b24c..28f9061c99 100644 --- a/utils/downloads.py +++ b/utils/downloads.py @@ -1,4 +1,3 @@ - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/utils/encryption.py b/utils/encryption.py index dc13ac8713..2dc9144802 100644 --- a/utils/encryption.py +++ b/utils/encryption.py @@ -20,7 +20,6 @@ from future import standard_library standard_library.install_aliases() -from builtins import str import hashlib from django.core.signing import TimestampSigner diff --git a/utils/filesystem.py b/utils/filesystem.py index 6d327724ff..a40ef2f68f 100644 --- a/utils/filesystem.py +++ b/utils/filesystem.py @@ -18,17 +18,14 @@ # See AUTHORS file. # -from __future__ import print_function -from builtins import hex -from builtins import object import hashlib import os import shutil import zlib -class File(object): +class File: def __init__(self, id, name, full_path, is_dir): self.name = name diff --git a/utils/forms.py b/utils/forms.py index e52e7b384d..961986c240 100644 --- a/utils/forms.py +++ b/utils/forms.py @@ -36,7 +36,7 @@ class HtmlCleaningCharField(forms.CharField): """ A field that removes disallowed HTML tags as implemented in utils.text.clean_html and checks for too many upper chase characters""" def clean(self, value): - value = super(HtmlCleaningCharField, self).clean(value) + value = super().clean(value) if is_shouting(value): raise forms.ValidationError('Please moderate the amount of upper case characters in your post...') return clean_html(value) @@ -47,7 +47,7 @@ class TagField(forms.CharField): unique tag strings """ def __init__(self, **kwargs): - super(TagField, self).__init__(**kwargs) + super().__init__(**kwargs) self.validators.append( validators.MinLengthValidator(3, 'You should add at least 3 different tags. Tags must be separated by ' 'spaces')) @@ -55,7 +55,7 @@ def __init__(self, **kwargs): validators.MaxLengthValidator(30, 'There can be maximum 30 tags, please select the most relevant ones!')) def to_python(self, value): - value = super(TagField, self).to_python(value) + value = super().to_python(value) alphanum_only = re.compile(r"[^ a-zA-Z0-9-,]") if alphanum_only.search(value): raise ValidationError("Tags must contain only letters a-z, digits 0-9 and hyphen") diff --git a/utils/images.py b/utils/images.py index d11ee8dae1..cd9f5c5c0c 100644 --- a/utils/images.py +++ b/utils/images.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/utils/locations.py b/utils/locations.py index d19143af48..29f545fbd8 100644 --- a/utils/locations.py +++ b/utils/locations.py @@ -18,9 +18,7 @@ # See AUTHORS file. # -from __future__ import print_function -from builtins import object def locations_decorator(cache=True): """wraps a locations function and adds two things: * caching for the calculation done inside the function if cache is true @@ -57,7 +55,7 @@ def pretty_print_locations(locations, indent=0): if __name__ == "__main__": - class X(object): + class X: @locations_decorator() def locations(self): return dict(a=5) diff --git a/utils/logging_filters.py b/utils/logging_filters.py index 436ee5115b..2229ec169f 100644 --- a/utils/logging_filters.py +++ b/utils/logging_filters.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import ipaddress import logging import json diff --git a/utils/mail.py b/utils/mail.py index c0ea8044ed..c60a960936 100644 --- a/utils/mail.py +++ b/utils/mail.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import logging import json @@ -105,9 +104,9 @@ def send_mail(subject, email_body, user_to=None, email_to=None, email_from=None, if settings.ALLOWED_EMAILS: # for testing purposes, so we don't accidentally send emails to users email_to = [(username, email) for username, email in email_to if email in settings.ALLOWED_EMAILS] - full_subject = u'{} {}'.format(settings.EMAIL_SUBJECT_PREFIX, subject) + full_subject = '{} {}'.format(settings.EMAIL_SUBJECT_PREFIX, subject) if extra_subject: - full_subject = u'{} - {}'.format(full_subject, extra_subject) + full_subject = '{} - {}'.format(full_subject, extra_subject) try: emails = tuple(((full_subject, email_body, email_from, [email]) diff --git a/utils/management_commands.py b/utils/management_commands.py index 5265090397..0167490fb5 100644 --- a/utils/management_commands.py +++ b/utils/management_commands.py @@ -60,7 +60,7 @@ def log_start(self, data=None): if data is None: data = {} data['command'] = self.command_name - commands_logger.info('Started management command ({0})'.format(json.dumps(data))) + commands_logger.info('Started management command ({})'.format(json.dumps(data))) def log_end(self, data=None): if data is None: @@ -68,4 +68,4 @@ def log_end(self, data=None): if self.start_time: data['work_time'] = round(time.time() - self.start_time) data['command'] = self.command_name or self.find_command_name() - commands_logger.info('Finished management command ({0})'.format(json.dumps(data))) + commands_logger.info('Finished management command ({})'.format(json.dumps(data))) diff --git a/utils/mirror_files.py b/utils/mirror_files.py index d746edebac..d7976e7a45 100644 --- a/utils/mirror_files.py +++ b/utils/mirror_files.py @@ -1,4 +1,3 @@ -from builtins import str from django.conf import settings import os import shutil @@ -29,7 +28,7 @@ def copy_files(source_destination_tuples): shutil.copy2(source_path, destination_path) if settings.LOG_START_AND_END_COPYING_FILES: web_logger.info('Finished copying file %s to %s' % (source_path, destination_path)) - except IOError as e: + except OSError as e: # File does not exist, no permissions, etc. web_logger.error('Failed copying %s (%s)' % (source_path, str(e))) diff --git a/utils/nginxsendfile.py b/utils/nginxsendfile.py index 73423d9d70..20a10ebe73 100644 --- a/utils/nginxsendfile.py +++ b/utils/nginxsendfile.py @@ -32,8 +32,8 @@ def prepare_sendfile_arguments_for_sound_download(sound): if settings.USE_PREVIEWS_WHEN_ORIGINAL_FILES_MISSING and not os.path.exists(sound_path): sound_path = sound.locations("preview.LQ.mp3.path") - sound_friendly_filename = '{0}.{1}'.format(sound_friendly_filename[:sound_friendly_filename.rfind('.')], 'mp3') - sound_sendfile_url = '{0}.{1}'.format(sound_sendfile_url[:sound_sendfile_url.rfind('.')], 'mp3') + sound_friendly_filename = '{}.{}'.format(sound_friendly_filename[:sound_friendly_filename.rfind('.')], 'mp3') + sound_sendfile_url = '{}.{}'.format(sound_sendfile_url[:sound_sendfile_url.rfind('.')], 'mp3') return sound_path, sound_friendly_filename, sound_sendfile_url diff --git a/utils/pagination.py b/utils/pagination.py index 5a2ec90a00..88beb95f7b 100644 --- a/utils/pagination.py +++ b/utils/pagination.py @@ -37,7 +37,7 @@ def count(self): # If the count was provided return it, otherwise use the if self._count: return self._count - return super(CountProvidedPaginator, self).count + return super().count def paginate(request, qs, items_per_page=20, page_get_name='page', object_count=None): diff --git a/utils/paypal/wrapper.py b/utils/paypal/wrapper.py index 90c8d87fec..1d8be6cdb3 100644 --- a/utils/paypal/wrapper.py +++ b/utils/paypal/wrapper.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # PayPal python NVP API wrapper class. # This is a sample to help others get started on working # with the PayPal NVP API in Python. @@ -36,13 +34,11 @@ # # if you want to get all info: # paypal.get_transaction_details(response['transactionid']) -from __future__ import print_function from future import standard_library standard_library.install_aliases() -from builtins import object import urllib.request, urllib.parse, urllib.error, cgi -class Paypal(object): +class Paypal: def __init__(self, debug=True): # fill these in with the API values @@ -89,7 +85,7 @@ def query(self, parameters, add_urls=True): response = cgi.parse_qs(urllib.request.urlopen(self.API_ENDPOINT, params_string).read()) # the parsed dict has a list for each value, but all Paypal replies are unique - return dict([(key.lower(), value[0]) for (key,value) in response.items()]) + return {key.lower(): value[0] for (key,value) in response.items()} def set_express_checkout(self, amount): diff --git a/utils/ratelimit.py b/utils/ratelimit.py index 7d9f03b896..af6ac7a003 100644 --- a/utils/ratelimit.py +++ b/utils/ratelimit.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import ipaddress import logging import random diff --git a/utils/search/__init__.py b/utils/search/__init__.py index 0aa5901838..76d5f5f922 100644 --- a/utils/search/__init__.py +++ b/utils/search/__init__.py @@ -1,4 +1,3 @@ -from __future__ import division # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,9 +18,7 @@ # See AUTHORS file. # -from builtins import range from past.utils import old_div -from builtins import object import importlib from django.conf import settings @@ -41,7 +38,7 @@ def get_search_engine(backend_class=settings.SEARCH_ENGINE_BACKEND_CLASS): return getattr(module, class_name)() -class SearchResults(object): +class SearchResults: def __init__(self, docs=None, num_found=-1, start=-1, num_rows=-1, non_grouped_number_of_results=-1, facets=None, highlighting=None, q_time=-1): @@ -145,7 +142,7 @@ def __str__(self): return ''.format(self.num_found) -class SearchResultsPaginator(object): +class SearchResultsPaginator: def __init__(self, search_results, num_per_page): """Paginator object for search results which has a similar API to django.core.paginator.Paginator @@ -180,7 +177,7 @@ class SearchEngineException(Exception): pass -class SearchEngineBase(object): +class SearchEngineBase: # Test subclasses of SearchEngineBase with the test_search_engine_backend management command diff --git a/utils/search/backends/solr555pysolr.py b/utils/search/backends/solr555pysolr.py index 6f0d6823f5..cce9af1745 100644 --- a/utils/search/backends/solr555pysolr.py +++ b/utils/search/backends/solr555pysolr.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import json import random import re @@ -159,7 +156,7 @@ def convert_sound_to_search_engine_document(sound): value = ['{}'.format(item) for item in value] suffix = SOLR_DYNAMIC_FIELDS_SUFFIX_MAP.get(type(value), None) if suffix: - document['{0}{1}'.format(key, suffix)] = value + document['{}{}'.format(key, suffix)] = value return document @@ -215,7 +212,7 @@ def add_solr_suffix_to_dynamic_fieldnames_in_filter(query_filter): descriptors_map = settings.ANALYZERS_CONFIGURATION[analyzer]['descriptors_map'] for _, db_descriptor_key, descriptor_type in descriptors_map: query_filter = query_filter.replace( - '{0}:'.format(db_descriptor_key),'{0}{1}:'.format( + '{}:'.format(db_descriptor_key),'{}{}:'.format( db_descriptor_key, SOLR_DYNAMIC_FIELDS_SUFFIX_MAP[descriptor_type])) return query_filter @@ -288,7 +285,7 @@ def search_process_filter(query_filter, only_sounds_within_ids=False, only_sound if 'geotag:"Intersects(' in query_filter: # Replace geotag:"Intersects( )" # with geotag:[", " TO " "] - query_filter = re.sub('geotag:"Intersects\((.+?) (.+?) (.+?) (.+?)\)"', r'geotag:["\2,\1" TO "\4,\3"]', query_filter) + query_filter = re.sub(r'geotag:"Intersects\((.+?) (.+?) (.+?) (.+?)\)"', r'geotag:["\2,\1" TO "\4,\3"]', query_filter) query_filter = search_filter_make_intersection(query_filter) diff --git a/utils/search/backends/solr_common.py b/utils/search/backends/solr_common.py index 6c4f88314c..7f30b12496 100644 --- a/utils/search/backends/solr_common.py +++ b/utils/search/backends/solr_common.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -21,17 +19,13 @@ # from future import standard_library standard_library.install_aliases() -from builtins import str -from builtins import map -from builtins import range -from builtins import object import json import urllib.request, urllib.parse, urllib.error from utils.search import SearchEngineException -class SolrQuery(object): +class SolrQuery: """A wrapper around a lot of Solr query funcionality. """ @@ -286,7 +280,7 @@ def as_kwargs(self): return params -class SolrResponseInterpreter(object): +class SolrResponseInterpreter: def __init__(self, response, next_page_query=None): if "grouped" in response: if "thread_title_grouped" in list(response["grouped"].keys()): diff --git a/utils/search/backends/test_search_engine_backend.py b/utils/search/backends/test_search_engine_backend.py index aeb9fa8215..28286ffe7f 100644 --- a/utils/search/backends/test_search_engine_backend.py +++ b/utils/search/backends/test_search_engine_backend.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from __future__ import print_function import datetime import logging diff --git a/utils/search/lucene_parser.py b/utils/search/lucene_parser.py index 260f7b4d92..c531ad4a84 100644 --- a/utils/search/lucene_parser.py +++ b/utils/search/lucene_parser.py @@ -17,11 +17,8 @@ # Authors: # See AUTHORS file. # -from builtins import map -from builtins import chr import collections -import six import pyparsing as pp from pyparsing import pyparsing_common as ppc @@ -88,9 +85,8 @@ def flatten(l): for el in l: - if isinstance(el, collections.Iterable) and not isinstance(el, six.string_types): - for sub in flatten(el): - yield sub + if isinstance(el, collections.abc.Iterable) and not isinstance(el, str): + yield from flatten(el) else: # for range filter with TO, we manually add the mandatory spaces in the parsed output if el == 'TO': @@ -131,7 +127,7 @@ def parse_query_filter_string(filter_query): # check if not nested meaning there is only one filter # if yes, make it nested to treat it the same way as if there were several filters - if isinstance(filter_list_str[0], six.string_types): + if isinstance(filter_list_str[0], str): filter_list_str = [filter_list_str] # we flatten the sub lists contained in the parsed output diff --git a/utils/search/search_forum.py b/utils/search/search_forum.py index b57085b7fc..d340b0deb9 100644 --- a/utils/search/search_forum.py +++ b/utils/search/search_forum.py @@ -17,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import str import logging from utils.search import get_search_engine, SearchEngineException diff --git a/utils/search/search_sounds.py b/utils/search/search_sounds.py index af60e7a233..9fb4f2900c 100644 --- a/utils/search/search_sounds.py +++ b/utils/search/search_sounds.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import logging from django.conf import settings diff --git a/utils/similarity_utilities.py b/utils/similarity_utilities.py index b38f898d3c..10a78599cc 100644 --- a/utils/similarity_utilities.py +++ b/utils/similarity_utilities.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import str import logging import traceback diff --git a/utils/sound_upload.py b/utils/sound_upload.py index ec2fdf06fb..7cb04ff80e 100644 --- a/utils/sound_upload.py +++ b/utils/sound_upload.py @@ -18,11 +18,6 @@ # See AUTHORS file. # import csv -from builtins import next -from builtins import zip -from builtins import str -from builtins import range -from builtins import open import hashlib import json import logging @@ -82,7 +77,7 @@ def clean_processing_before_describe_files(audio_file_path): def get_duration_from_processing_before_describe_files(audio_file_path): info_file_path = os.path.join(get_processing_before_describe_sound_folder(audio_file_path), 'info.json') try: - return float(json.load(open(info_file_path, 'r'))['duration']) + return float(json.load(open(info_file_path))['duration']) except Exception as e: return 0.0 @@ -190,7 +185,7 @@ def create_sound(user, remove_uploaded_file_from_mirror_locations(sound.original_path) _remove_user_uploads_folder_if_empty(sound.user) - except IOError as e: + except OSError as e: raise CantMoveException("Failed to move file from %s to %s" % (sound.original_path, new_original_path)) sound.original_path = new_original_path sound.save() @@ -300,7 +295,7 @@ def get_csv_lines(csv_file_path): if csv_file_path.endswith('.csv'): # Read CSV formatted file - reader = csv.reader(open(csv_file_path, 'r', newline='', encoding="utf-8")) + reader = csv.reader(open(csv_file_path, newline='', encoding="utf-8")) header = next(reader) lines = [dict(zip(header, row)) for row in reader] elif csv_file_path.endswith('.xls') or csv_file_path.endswith('.xlsx'): diff --git a/utils/tagrecommendation_utilities.py b/utils/tagrecommendation_utilities.py index dcb3e01a97..6e6a1aed99 100644 --- a/utils/tagrecommendation_utilities.py +++ b/utils/tagrecommendation_utilities.py @@ -1,4 +1,3 @@ -from __future__ import print_function # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/utils/test_helpers.py b/utils/test_helpers.py index fddb4a6c04..76956cbf9d 100644 --- a/utils/test_helpers.py +++ b/utils/test_helpers.py @@ -18,8 +18,6 @@ # See AUTHORS file. # -from builtins import next -from builtins import range import os from functools import partial, wraps from itertools import count diff --git a/utils/tests/test_forms.py b/utils/tests/test_forms.py index 7d167c661c..0b8de7dd90 100644 --- a/utils/tests/test_forms.py +++ b/utils/tests/test_forms.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -18,7 +17,6 @@ # Authors: # See AUTHORS file. # -from builtins import range from django.core.exceptions import ValidationError from django.test import TestCase diff --git a/utils/tests/test_logging_filters.py b/utils/tests/test_logging_filters.py index 89de253716..69f9e79fc6 100644 --- a/utils/tests/test_logging_filters.py +++ b/utils/tests/test_logging_filters.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -18,13 +17,12 @@ # Authors: # See AUTHORS file. # -from builtins import object from django.test import TestCase from utils.logging_filters import get_client_ip -class DummyRequest(object): +class DummyRequest: """A dummy request to check the X-Forwarded-For header in logging_filters.get_client_ip""" def __init__(self, xforwardedfor): self.META = {"HTTP_X_FORWARDED_FOR": xforwardedfor} diff --git a/utils/tests/test_pagination.py b/utils/tests/test_pagination.py index 577342cf9f..7c411a1a35 100644 --- a/utils/tests/test_pagination.py +++ b/utils/tests/test_pagination.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/utils/tests/test_processing.py b/utils/tests/test_processing.py index 56ca2a75e0..b4bbd2f424 100644 --- a/utils/tests/test_processing.py +++ b/utils/tests/test_processing.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -99,7 +97,7 @@ def pre_test(self, create_sound_file=True): # Do some stuff which needs to be carried out right before each test self.assertEqual(self.sound.processing_state, "PE") if create_sound_file: - create_test_files(paths=[u'{}'.format(self.sound.locations('path'))], make_valid_wav_files=True, duration=2) + create_test_files(paths=['{}'.format(self.sound.locations('path'))], make_valid_wav_files=True, duration=2) def setUp(self): user, _, sounds = create_user_and_sounds(num_sounds=1, type="wav") @@ -298,7 +296,7 @@ def setUp(self): @override_processing_before_description_path_with_temp_directory @override_uploads_path_with_temp_directory def test_process_before_description(self): - for filename in [u'test_file.wav', u'test_filè2.wav']: + for filename in ['test_file.wav', 'test_filè2.wav']: uploaded_file_path = os.path.join(settings.UPLOADS_PATH, str(self.user.id), filename) create_test_files(paths=[uploaded_file_path], make_valid_wav_files=True, duration=2) result = FreesoundAudioProcessorBeforeDescription(audio_file_path=uploaded_file_path).process() diff --git a/utils/tests/test_search_general.py b/utils/tests/test_search_general.py index bab655643c..d437fc4327 100644 --- a/utils/tests/test_search_general.py +++ b/utils/tests/test_search_general.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -83,26 +82,26 @@ def test_search_prepare_parameters_with_query_params(self): 'num_sounds': settings.SOUNDS_PER_PAGE, 'current_page': 1, 'group_by_pack': False, - 'query_filter': u'duration:[1 TO 10] is_geotagged:1', - 'textual_query': u'dog', + 'query_filter': 'duration:[1 TO 10] is_geotagged:1', + 'textual_query': 'dog', 'only_sounds_with_pack': False, } expected_extra_vars = { - 'advanced': u'1', - 'filter_query_link_more_when_grouping_packs': u'duration:[1+TO+10]+is_geotagged:1', + 'advanced': '1', + 'filter_query_link_more_when_grouping_packs': 'duration:[1+TO+10]+is_geotagged:1', 'cluster_id': '', - 'filter_query_non_facets': u'duration:[1 TO 10] is_geotagged:1', + 'filter_query_non_facets': 'duration:[1 TO 10] is_geotagged:1', 'has_facet_filter': False, - 'parsed_filters': [[u'duration', ':', '[', u'1', ' TO ', u'10', ']'], [u'is_geotagged', ':', u'1']], + 'parsed_filters': [['duration', ':', '[', '1', ' TO ', '10', ']'], ['is_geotagged', ':', '1']], 'parsing_error': False, 'raw_weights_parameter': '' } expected_advanced_search_params_dict = { - 'a_tag': u'1', + 'a_tag': '1', 'a_username': '', - 'a_description': u'1', + 'a_description': '1', 'a_packname': '', 'a_filename': '', 'a_soundid': '', @@ -150,24 +149,24 @@ def test_remove_facet_filters_special_char3(self): def test_search_prepare_parameters_non_ascii_query(self): # Simple test to check if some non ascii characters are correctly handled by search_prepare_parameters() - request = self.factory.get(reverse('sounds-search')+u'?q=Æ æ ¿ É') + request = self.factory.get(reverse('sounds-search')+'?q=Æ æ ¿ É') query_params, advanced_search_params_dict, extra_vars = search_prepare_parameters(request) - self.assertEqual(query_params['textual_query'], u'\xc6 \xe6 \xbf \xc9') + self.assertEqual(query_params['textual_query'], '\xc6 \xe6 \xbf \xc9') def test_split_filter_query_duration_and_facet(self): # We check that the combination of a duration filter and a facet filter (CC Attribution) works correctly. - filter_query_string = u'duration:[0 TO 10] license:"Attribution" username:"XavierFav" grouping_pack:"1_best-pack-ever"' + filter_query_string = 'duration:[0 TO 10] license:"Attribution" username:"XavierFav" grouping_pack:"1_best-pack-ever"' parsed_filters = parse_query_filter_string(filter_query_string) filter_query_split = split_filter_query(filter_query_string, parsed_filters, '') # duraton filter is not a facet, but should stay present when removing a facet. expected_filter_query_split = [ - {'remove_url': u'duration:[0 TO 10]', 'name': u'license:Attribution'}, + {'remove_url': 'duration:[0 TO 10]', 'name': 'license:Attribution'}, ] expected_filter_query_split = [ - {'remove_url': urlquote_plus(u'duration:[0 TO 10] username:"XavierFav" grouping_pack:"1_best-pack-ever"'), 'name': u'license:Attribution'}, - {'remove_url': urlquote_plus(u'duration:[0 TO 10] license:"Attribution" grouping_pack:"1_best-pack-ever"'), 'name': u'username:XavierFav'}, - {'remove_url': urlquote_plus(u'duration:[0 TO 10] license:"Attribution" username:"XavierFav"'), 'name': u'pack:best-pack-ever'}, + {'remove_url': urlquote_plus('duration:[0 TO 10] username:"XavierFav" grouping_pack:"1_best-pack-ever"'), 'name': 'license:Attribution'}, + {'remove_url': urlquote_plus('duration:[0 TO 10] license:"Attribution" grouping_pack:"1_best-pack-ever"'), 'name': 'username:XavierFav'}, + {'remove_url': urlquote_plus('duration:[0 TO 10] license:"Attribution" username:"XavierFav"'), 'name': 'pack:best-pack-ever'}, ] # the order does not matter for the list of facet dicts. @@ -201,14 +200,14 @@ def test_split_filter_query_duration_and_facet(self): filter_query_split[grouping_pack_facet_dict_idx]['remove_url'].replace('++', '+')) def test_split_filter_query_special_chars(self): - filter_query_string = u'license:"Sampling+" grouping_pack:"1_example pack + @ #()*"' + filter_query_string = 'license:"Sampling+" grouping_pack:"1_example pack + @ #()*"' parsed_filters = parse_query_filter_string(filter_query_string) filter_query_split = split_filter_query(filter_query_string, parsed_filters, '') filter_query_names = [filter_query_dict['name'] for filter_query_dict in filter_query_split] expected_filter_query_split = [ - {'remove_url': urlquote_plus(u'grouping_pack:"1_example pack + @ #()*"'), 'name': u'license:Sampling+'}, - {'remove_url': urlquote_plus(u'license:"Sampling+"'), 'name': u'pack:example pack + @ #()*'}, + {'remove_url': urlquote_plus('grouping_pack:"1_example pack + @ #()*"'), 'name': 'license:Sampling+'}, + {'remove_url': urlquote_plus('license:"Sampling+"'), 'name': 'pack:example pack + @ #()*'}, ] cc_samplingplus_facet_dict_idx = filter_query_names.index('license:Sampling+') @@ -273,14 +272,14 @@ def test_parse_filter_nested_composed_with_OR(self): def test_split_filter_query_cluster_facet(self): # We check that the combination of a duration filter, a facet filter (CC Attribution) and a cluster filter # works correctly. - filter_query_string = u'duration:[0 TO 10] license:"Attribution"' + filter_query_string = 'duration:[0 TO 10] license:"Attribution"' # the cluster filter is set in the second argument of split_filter_query() parsed_filters = parse_query_filter_string(filter_query_string) filter_query_split = split_filter_query(filter_query_string, parsed_filters, '1') expected_filter_query_split = [ - {'remove_url': urlquote_plus(u'duration:[0 TO 10]'), 'name': u'license:Attribution'}, - {'remove_url': urlquote_plus(u'duration:[0 TO 10] license:"Attribution"'), 'name': 'Cluster #1'} + {'remove_url': urlquote_plus('duration:[0 TO 10]'), 'name': 'license:Attribution'}, + {'remove_url': urlquote_plus('duration:[0 TO 10] license:"Attribution"'), 'name': 'Cluster #1'} ] # check that the cluster facet exists diff --git a/utils/tests/test_text.py b/utils/tests/test_text.py index 48cc456490..9da1ad4a38 100644 --- a/utils/tests/test_text.py +++ b/utils/tests/test_text.py @@ -1,4 +1,3 @@ -# -*- coding: utf-8 -*- # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -19,7 +18,6 @@ # See AUTHORS file. # -from __future__ import unicode_literals from django.test import TestCase @@ -36,28 +34,28 @@ def test_is_shouting(self): self.assertFalse(is_shouting('This is a regular phrase.')) def test_text_may_be_spam(self): - self.assertFalse(text_may_be_spam(u'')) - self.assertFalse(text_may_be_spam(u' ')) - self.assertFalse(text_may_be_spam(u'this is the content of a blog post')) - self.assertTrue(text_may_be_spam(u'this post contains an http:// link')) - self.assertTrue(text_may_be_spam(u'this post contains an https:// link')) - self.assertTrue(text_may_be_spam(u'this post contains non-basic ascii characters :')) - self.assertTrue(text_may_be_spam(u'this post contains non-basic ascii characters \xc3')) - self.assertFalse(text_may_be_spam(u'this post contains few numbers 1245')) - self.assertTrue(text_may_be_spam(u'this post contains more numbers 1234567')) - self.assertTrue(text_may_be_spam(u'this post contains even more numbers 123456789')) - self.assertTrue(text_may_be_spam(u'this post contains an@email.com')) - self.assertTrue(text_may_be_spam(u'this post contains short.url')) - self.assertTrue(text_may_be_spam(u'BLaCk MaGiC SpEcIaLiSt babaji')) - self.assertTrue(text_may_be_spam(u'love marriage problem solution')) - self.assertTrue(text_may_be_spam(u'fbdad8fbdad8fbdad8')) - self.assertTrue(text_may_be_spam(u'fbdad8')) + self.assertFalse(text_may_be_spam('')) + self.assertFalse(text_may_be_spam(' ')) + self.assertFalse(text_may_be_spam('this is the content of a blog post')) + self.assertTrue(text_may_be_spam('this post contains an http:// link')) + self.assertTrue(text_may_be_spam('this post contains an https:// link')) + self.assertTrue(text_may_be_spam('this post contains non-basic ascii characters :')) + self.assertTrue(text_may_be_spam('this post contains non-basic ascii characters \xc3')) + self.assertFalse(text_may_be_spam('this post contains few numbers 1245')) + self.assertTrue(text_may_be_spam('this post contains more numbers 1234567')) + self.assertTrue(text_may_be_spam('this post contains even more numbers 123456789')) + self.assertTrue(text_may_be_spam('this post contains an@email.com')) + self.assertTrue(text_may_be_spam('this post contains short.url')) + self.assertTrue(text_may_be_spam('BLaCk MaGiC SpEcIaLiSt babaji')) + self.assertTrue(text_may_be_spam('love marriage problem solution')) + self.assertTrue(text_may_be_spam('fbdad8fbdad8fbdad8')) + self.assertTrue(text_may_be_spam('fbdad8')) def test_remove_control_chars(self): text = "some \xf0\x9f\x98\x80 emoji" self.assertEqual(remove_control_chars(text), "some \xf0\x9f\x98\x80 emoji") - unicodeemoji = u"hello \U0001f600" - self.assertEqual(remove_control_chars(unicodeemoji), u"hello \U0001f600") + unicodeemoji = "hello \U0001f600" + self.assertEqual(remove_control_chars(unicodeemoji), "hello \U0001f600") text = "normal text" self.assertEqual(remove_control_chars(text), "normal text") text = "text with \n newline" @@ -71,71 +69,71 @@ class CleanHtmlTest(TestCase): def test_clean_html(self): # Test if the text input contains allowed html tags # The only supported tags are : a, img, strong, b, em, li, u, p, br, blockquote and code - ret = clean_html(u'a b c d') - self.assertEqual(u'a b c d', ret) + ret = clean_html('a b c d') + self.assertEqual('a b c d', ret) # Also make sure links contains rel="nofollow" - ret = clean_html(u'google') - self.assertEqual(u'google', ret) + ret = clean_html('google') + self.assertEqual('google', ret) - ret = clean_html(u'google') - self.assertEqual(u'google', ret) + ret = clean_html('google') + self.assertEqual('google', ret) - ret = clean_html(u'

this should return the substring just fine

') - self.assertEqual(u'this should return the substring just fine', ret) + ret = clean_html('

this should return the substring just fine

') + self.assertEqual('this should return the substring just fine', ret) - ret = clean_html(u'
amazinggrace
') - self.assertEqual(u'amazinggrace', ret) + ret = clean_html('
amazinggrace
') + self.assertEqual('amazinggrace', ret) - ret = clean_html(u'click me') - self.assertEqual(u'click me', ret) + ret = clean_html('click me') + self.assertEqual('click me', ret) - ret = clean_html(u'

click me

') - self.assertEqual(u'

click me

', ret) + ret = clean_html('

click me

') + self.assertEqual('

click me

', ret) - ret = clean_html(u'') - self.assertEqual(u'', ret) + ret = clean_html('') + self.assertEqual('', ret) - ret = clean_html(u'hello') - self.assertEqual(u'hello', ret) + ret = clean_html('hello') + self.assertEqual('hello', ret) - ret = clean_html(u'

a
b
') - self.assertEqual(u'

a
b

', ret) + ret = clean_html('

a
b
') + self.assertEqual('

a
b

', ret) - ret = clean_html(u'

') - self.assertEqual(u'

', ret) + ret = clean_html('

') + self.assertEqual('

', ret) - ret = clean_html(u'http://www.google.com') - self.assertEqual(u'http://www.google.com', ret) + ret = clean_html('http://www.google.com') + self.assertEqual('http://www.google.com', ret) - ret = clean_html(u'http://www.google.com') - self.assertEqual(u'http://www.google.com', ret) + ret = clean_html('http://www.google.com') + self.assertEqual('http://www.google.com', ret) - ret = clean_html(u'http://www.google.com http://www.google.com') - self.assertEqual(u'http://www.google.com http://www.google.com', ret) + ret = clean_html('http://www.google.com http://www.google.com') + self.assertEqual('http://www.google.com http://www.google.com', ret) - ret = clean_html(u'

    123hellothere http://www.google.com

') - self.assertEqual(u'', ret) + ret = clean_html('

    123hellothere http://www.google.com

') + self.assertEqual('', ret) - ret = clean_html(u'abc http://www.google.com abc') - self.assertEqual(u'abc http://www.google.com abc', ret) + ret = clean_html('abc http://www.google.com abc') + self.assertEqual('abc http://www.google.com abc', ret) # The links inside <> are encoded by < and > - ret = clean_html(u'abc abc') - self.assertEqual(u'abc < http://www.google.com > abc', ret) + ret = clean_html('abc abc') + self.assertEqual('abc < http://www.google.com > abc', ret) - ret = clean_html(u'GALORE: https://freesound.iua.upf.edu/samplesViewSingle.php?id=22092\\nFreesound Moderator') - self.assertEqual(u'GALORE: https://freesound.iua.upf.edu/samplesViewSingle.php?id=22092\\nFreesound Moderator', ret) + ret = clean_html('GALORE: https://freesound.iua.upf.edu/samplesViewSingle.php?id=22092\\nFreesound Moderator') + self.assertEqual('GALORE: https://freesound.iua.upf.edu/samplesViewSingle.php?id=22092\\nFreesound Moderator', ret) # Allow custom placeholders - ret = clean_html(u'my sound id') - self.assertEqual(u'my sound id', ret) + ret = clean_html('my sound id') + self.assertEqual('my sound id', ret) - ret = clean_html(u'my sound url') - self.assertEqual(u'my sound url', ret) + ret = clean_html('my sound url') + self.assertEqual('my sound url', ret) - ret = clean_html(u'') - self.assertEqual(u'', ret) + ret = clean_html('') + self.assertEqual('', ret) - ret = clean_html(u'
  • Some list
') - self.assertEqual(u'
  • Some list
', ret) + ret = clean_html('
  • Some list
') + self.assertEqual('
  • Some list
', ret) diff --git a/utils/tests/tests.py b/utils/tests/tests.py index 3dc193210c..d52f7496cc 100644 --- a/utils/tests/tests.py +++ b/utils/tests/tests.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import range import datetime import os import shutil diff --git a/utils/text.py b/utils/text.py index dc6bad2532..907fedaae8 100644 --- a/utils/text.py +++ b/utils/text.py @@ -48,7 +48,7 @@ def is_shouting(string): def nofollow(attrs, new=False): - attrs[(None, u'rel')] = u'nofollow' + attrs[(None, 'rel')] = 'nofollow' return attrs @@ -79,13 +79,13 @@ def __iter__(self): def clean_html(input): # Replace html tags from user input, see utils.test for examples - ok_tags = [u"a", u"img", u"strong", u"b", u"em", u"i", u"u", u"ul", u"li", u"p", u"br", u"blockquote", u"code"] - ok_attributes = {u"a": [u"href", u"rel"], u"img": [u"src", u"alt", u"title"]} + ok_tags = ["a", "img", "strong", "b", "em", "i", "u", "ul", "li", "p", "br", "blockquote", "code"] + ok_attributes = {"a": ["href", "rel"], "img": ["src", "alt", "title"]} # all other tags: replace with the content of the tag # If input contains link in the format: then convert it to < http:// > # This is because otherwise the library recognizes it as a tag and breaks the link. - input = re.sub("\<(http\S+?)\>", r'< \1 >', input) + input = re.sub(r"\<(http\S+?)\>", r'< \1 >', input) cleaner = bleach.Cleaner( filters=[ diff --git a/wiki/admin.py b/wiki/admin.py index ae86a8a496..7902cb64c2 100644 --- a/wiki/admin.py +++ b/wiki/admin.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # diff --git a/wiki/forms.py b/wiki/forms.py index d2aab72314..52b0782bbd 100644 --- a/wiki/forms.py +++ b/wiki/forms.py @@ -18,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django import forms from wiki import models @@ -27,7 +26,7 @@ class ContentForm(forms.ModelForm): title = forms.CharField(label='Page name', widget=forms.TextInput(attrs={'size': '100'})) body = forms.CharField(widget=forms.Textarea(attrs={'rows': '40', 'cols': '100'})) - class Meta(object): + class Meta: model = models.Content exclude = ('author', 'page', 'created') @@ -35,7 +34,7 @@ class Meta(object): class BwContentForm(ContentForm): def __init__(self, *args, **kwargs): - super(BwContentForm, self).__init__(*args, **kwargs) + super().__init__(*args, **kwargs) self.fields['title'].label = False self.fields['title'].widget.attrs['placeholder'] = 'Title of the page' self.fields['body'].label = False diff --git a/wiki/migrations/0001_initial.py b/wiki/migrations/0001_initial.py index f8dca8c022..436389de90 100644 --- a/wiki/migrations/0001_initial.py +++ b/wiki/migrations/0001_initial.py @@ -1,6 +1,4 @@ -# -*- coding: utf-8 -*- # Generated by Django 1.9.5 on 2016-04-15 11:33 -from __future__ import unicode_literals from django.conf import settings from django.db import migrations, models diff --git a/wiki/models.py b/wiki/models.py index 54083217d3..f7b8b23918 100644 --- a/wiki/models.py +++ b/wiki/models.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA # @@ -20,7 +18,6 @@ # See AUTHORS file. # -from builtins import object from django.contrib.auth.models import User from django.db import models from django.utils.encoding import smart_text @@ -46,7 +43,7 @@ class Content(models.Model): body = models.TextField() created = models.DateTimeField(db_index=True, auto_now_add=True) - class Meta(object): + class Meta: ordering = ('-created', ) get_latest_by = 'created' diff --git a/wiki/urls.py b/wiki/urls.py index f121eb1d3a..127f2ae4b8 100644 --- a/wiki/urls.py +++ b/wiki/urls.py @@ -1,5 +1,3 @@ -# -*- coding: utf-8 -*- - # # Freesound is (c) MUSIC TECHNOLOGY GROUP, UNIVERSITAT POMPEU FABRA #