From 325cc917d5ad14b130b156d23b7adca46499dc24 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Miroslav=20=C5=A0ediv=C3=BD?= <6774676+eumiro@users.noreply.github.com> Date: Fri, 2 Dec 2022 22:04:23 +0100 Subject: refactor: use f-strings --- mastodon/accounts.py | 59 ++++++++++++++------------------- mastodon/admin.py | 35 ++++++++++---------- mastodon/authentication.py | 12 +++---- mastodon/conversations.py | 3 +- mastodon/filters.py | 9 ++---- mastodon/hashtags.py | 4 +-- mastodon/instance.py | 11 ++----- mastodon/internals.py | 40 +++++++++++------------ mastodon/lists.py | 14 ++++---- mastodon/media.py | 10 +++--- mastodon/notifications.py | 6 ++-- mastodon/polls.py | 8 ++--- mastodon/relationships.py | 6 ++-- mastodon/statuses.py | 72 +++++++++++++++-------------------------- mastodon/streaming_endpoints.py | 4 +-- mastodon/suggestions.py | 3 +- mastodon/timeline.py | 7 ++-- mastodon/utility.py | 13 ++++---- tests/test_create_app.py | 2 +- tests/test_pagination.py | 15 ++++++--- tests/test_status.py | 2 +- 21 files changed, 141 insertions(+), 194 deletions(-) diff --git a/mastodon/accounts.py b/mastodon/accounts.py index 219edac..3d10088 100644 --- a/mastodon/accounts.py +++ b/mastodon/accounts.py @@ -66,7 +66,7 @@ class Mastodon(Internals): response = self.__api_request('POST', '/oauth/token', oauth_params, do_ratelimiting=False) temp_access_token = response['access_token'] except Exception as e: - raise MastodonIllegalArgumentError('Invalid request during oauth phase: %s' % e) + raise MastodonIllegalArgumentError(f'Invalid request during oauth phase: {e}') # Step 2: Use that to create a user try: @@ -74,7 +74,7 @@ class Mastodon(Internals): if "error" in response: if return_detailed_error: return None, response - raise MastodonIllegalArgumentError('Invalid request: %s' % e) + raise MastodonIllegalArgumentError(f'Invalid request: {e}') self.access_token = response['access_token'] self.__set_refresh_token(response.get('refresh_token')) self.__set_token_expired(int(response.get('expires_in', 0))) @@ -88,7 +88,10 @@ class Mastodon(Internals): received_scopes += _SCOPE_SETS[scope_set] if not set(scopes) <= set(received_scopes): - raise MastodonAPIError('Granted scopes "' + " ".join(received_scopes) + '" do not contain all of the requested scopes "' + " ".join(scopes) + '".') + raise MastodonAPIError( + f'Granted scopes "{" ".join(received_scopes)}" ' + f'do not contain all of the requested scopes "{" ".join(scopes)}".' + ) if to_file is not None: with open(to_file, 'w') as token_file: @@ -124,8 +127,7 @@ class Mastodon(Internals): Returns a :ref:`account dict `. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/accounts/{id}') @api_version("1.0.0", "2.1.0", _DICT_VERSION_ACCOUNT) def account_verify_credentials(self): @@ -185,8 +187,7 @@ class Mastodon(Internals): if not exclude_reblogs: del params["exclude_reblogs"] - url = '/api/v1/accounts/{0}/statuses'.format(str(id)) - return self.__api_request('GET', url, params) + return self.__api_request('GET', f'/api/v1/accounts/{id}/statuses', params) @api_version("1.0.0", "2.6.0", _DICT_VERSION_ACCOUNT) def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None): @@ -206,8 +207,7 @@ class Mastodon(Internals): since_id = self.__unpack_id(since_id, dateconv=True) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/accounts/{0}/following'.format(str(id)) - return self.__api_request('GET', url, params) + return self.__api_request('GET', f'/api/v1/accounts/{id}/following', params) @api_version("1.0.0", "2.6.0", _DICT_VERSION_ACCOUNT) def account_followers(self, id, max_id=None, min_id=None, since_id=None, limit=None): @@ -227,8 +227,7 @@ class Mastodon(Internals): since_id = self.__unpack_id(since_id, dateconv=True) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/accounts/{0}/followers'.format(str(id)) - return self.__api_request('GET', url, params) + return self.__api_request('GET', f'/api/v1/accounts/{id}/followers', params) @api_version("1.0.0", "1.4.0", _DICT_VERSION_RELATIONSHIP) def account_relationships(self, id): @@ -269,8 +268,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/accounts/{0}/lists'.format(str(id)) - return self.__api_request('GET', url, params) + return self.__api_request('GET', f'/api/v1/accounts/{id}/lists', params) @api_version("3.4.0", "3.4.0", _DICT_VERSION_ACCOUNT) def account_lookup(self, acct): @@ -317,8 +315,7 @@ class Mastodon(Internals): if params["reblogs"] is None: del params["reblogs"] - url = '/api/v1/accounts/{0}/follow'.format(str(id)) - return self.__api_request('POST', url, params) + return self.__api_request('POST', f'/api/v1/accounts/{id}/follow', params) @api_version("1.0.0", "2.1.0", _DICT_VERSION_ACCOUNT) def follows(self, uri): @@ -338,7 +335,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/accounts/{0}/unfollow'.format(str(id))) + return self.__api_request('POST', f'/api/v1/accounts/{id}/unfollow') @api_version("3.5.0", "3.5.0", _DICT_VERSION_RELATIONSHIP) def account_remove_from_followers(self, id): @@ -349,7 +346,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` reflecting the updated following status. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/accounts/{0}/remove_from_followers'.format(str(id))) + return self.__api_request('POST', f'/api/v1/accounts/{id}/remove_from_followers') @api_version("1.0.0", "1.4.0", _DICT_VERSION_RELATIONSHIP) @@ -360,8 +357,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}/block'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/accounts/{id}/block') @api_version("1.0.0", "1.4.0", _DICT_VERSION_RELATIONSHIP) def account_unblock(self, id): @@ -371,8 +367,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}/unblock'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/accounts/{id}/unblock') @api_version("1.1.0", "2.4.3", _DICT_VERSION_RELATIONSHIP) def account_mute(self, id, notifications=True, duration=None): @@ -387,8 +382,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/accounts/{0}/mute'.format(str(id)) - return self.__api_request('POST', url, params) + return self.__api_request('POST', f'/api/v1/accounts/{id}/mute', params) @api_version("1.1.0", "1.4.0", _DICT_VERSION_RELATIONSHIP) def account_unmute(self, id): @@ -398,8 +392,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}/unmute'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/accounts/{id}/unmute', params) @api_version("1.1.1", "3.1.0", _DICT_VERSION_ACCOUNT) def account_update_credentials(self, display_name=None, note=None, @@ -436,10 +429,8 @@ class Mastodon(Internals): fields_attributes = [] for idx, (field_name, field_value) in enumerate(fields): - params_initial['fields_attributes[' + - str(idx) + '][name]'] = field_name - params_initial['fields_attributes[' + - str(idx) + '][value]'] = field_value + params_initial[f'fields_attributes[{idx}][name]'] = field_name + params_initial[f'fields_attributes[{idx}][value]'] = field_value # Clean up params for param in ["avatar", "avatar_mime_type", "header", "header_mime_type", "fields"]: @@ -464,8 +455,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}/pin'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/accounts/{id}/pin') @api_version("2.5.0", "2.5.0", _DICT_VERSION_RELATIONSHIP) def account_unpin(self, id): @@ -475,8 +465,7 @@ class Mastodon(Internals): Returns a :ref:`relationship dict ` containing the updated relationship to the user. """ id = self.__unpack_id(id) - url = '/api/v1/accounts/{0}/unpin'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/accounts/{id}/unpin') @api_version("3.2.0", "3.2.0", _DICT_VERSION_RELATIONSHIP) def account_note_set(self, id, comment): @@ -487,7 +476,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ["id"]) - return self.__api_request('POST', '/api/v1/accounts/{0}/note'.format(str(id)), params) + return self.__api_request('POST', f'/api/v1/accounts/{id}/note', params) @api_version("3.3.0", "3.3.0", _DICT_VERSION_HASHTAG) def account_featured_tags(self, id): @@ -497,4 +486,4 @@ class Mastodon(Internals): Returns a list of :ref:`hashtag dicts ` (NOT `featured tag dicts`_). """ id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/accounts/{0}/featured_tags'.format(str(id))) + return self.__api_request('GET', f'/api/v1/accounts/{id}/featured_tags') diff --git a/mastodon/admin.py b/mastodon/admin.py index e2f5f20..422be35 100644 --- a/mastodon/admin.py +++ b/mastodon/admin.py @@ -142,7 +142,7 @@ class Mastodon(Internals): Returns that dict. """ id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/admin/accounts/{0}'.format(id)) + return self.__api_request('GET', f'/api/v1/admin/accounts/{id}') @api_version("2.9.1", "2.9.1", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_enable(self, id): @@ -152,7 +152,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/enable'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{id}/enable') @api_version("2.9.1", "2.9.1", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_approve(self, id): @@ -162,7 +162,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/approve'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{id}/approve') @api_version("2.9.1", "2.9.1", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_reject(self, id): @@ -172,7 +172,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict ` for the account that is now gone. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/reject'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{id}/reject') @api_version("2.9.1", "2.9.1", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_unsilence(self, id): @@ -182,7 +182,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/unsilence'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{id}/unsilence') @api_version("2.9.1", "2.9.1", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_unsuspend(self, id): @@ -192,7 +192,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/unsuspend'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{id}/unsuspend') @api_version("3.3.0", "3.3.0", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_delete(self, id): @@ -202,7 +202,7 @@ class Mastodon(Internals): The deleted accounts :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('DELETE', '/api/v1/admin/accounts/{0}'.format(id)) + return self.__api_request('DELETE', f'/api/v1/admin/accounts/{id}') @api_version("3.3.0", "3.3.0", _DICT_VERSION_ADMIN_ACCOUNT) def admin_account_unsensitive(self, id): @@ -212,7 +212,7 @@ class Mastodon(Internals): Returns the updated :ref:`admin account dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/accounts/{0}/unsensitive'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/accounts/{f}/unsensitive') @api_version("2.9.1", "2.9.1", "2.9.1") def admin_account_moderate(self, id, action=None, report_id=None, warning_preset_id=None, text=None, send_email_notification=True): @@ -248,8 +248,7 @@ class Mastodon(Internals): params["type"] = action - self.__api_request( - 'POST', '/api/v1/admin/accounts/{0}/action'.format(id), params) + self.__api_request('POST', f'/api/v1/admin/accounts/{id}/action', params) @api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT) def admin_reports(self, resolved=False, account_id=None, target_account_id=None, max_id=None, min_id=None, since_id=None, limit=None): @@ -290,7 +289,7 @@ class Mastodon(Internals): Returns a :ref:`report dict `. """ id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/admin/reports/{0}'.format(id)) + return self.__api_request('GET', f'/api/v1/admin/reports/{id}') @api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT) def admin_report_assign(self, id): @@ -300,7 +299,7 @@ class Mastodon(Internals): Returns the updated :ref:`report dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/reports/{0}/assign_to_self'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/reports/{id}/assign_to_self') @api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT) def admin_report_unassign(self, id): @@ -310,7 +309,7 @@ class Mastodon(Internals): Returns the updated :ref:`report dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/reports/{0}/unassign'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/reports/{id}/unassign') @api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT) def admin_report_reopen(self, id): @@ -320,7 +319,7 @@ class Mastodon(Internals): Returns the updated :ref:`report dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/reports/{0}/reopen'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/reports/{id}/reopen') @api_version("2.9.1", "2.9.1", _DICT_VERSION_REPORT) def admin_report_resolve(self, id): @@ -330,7 +329,7 @@ class Mastodon(Internals): Returns the updated :ref:`report dict `. """ id = self.__unpack_id(id) - return self.__api_request('POST', '/api/v1/admin/reports/{0}/resolve'.format(id)) + return self.__api_request('POST', f'/api/v1/admin/reports/{id}/resolve') @api_version("3.5.0", "3.5.0", _DICT_VERSION_HASHTAG) def admin_trending_tags(self, limit=None): @@ -376,7 +375,7 @@ class Mastodon(Internals): """ if id is not None: id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/admin/domain_blocks/{0}'.format(id)) + return self.__api_request('GET', f'/api/v1/admin/domain_blocks/{id}') else: params = self.__generate_params(locals(),['limit']) return self.__api_request('GET', '/api/v1/admin/domain_blocks/', params) @@ -430,7 +429,7 @@ class Mastodon(Internals): raise AttributeError("Must provide an id to modify the existing moderation actions on a given domain.") id = self.__unpack_id(id) params = self.__generate_params(locals(), ["id"]) - return self.__api_request('PUT', '/api/v1/admin/domain_blocks/{0}'.format(id), params) + return self.__api_request('PUT', f'/api/v1/admin/domain_blocks/{id}', params) @api_version("4.0.0", "4.0.0", _DICT_VERSION_ADMIN_DOMAIN_BLOCK) def admin_delete_domain_block(self, id=None): @@ -443,7 +442,7 @@ class Mastodon(Internals): """ if id is not None: id = self.__unpack_id(id) - self.__api_request('DELETE', '/api/v1/admin/domain_blocks/{0}'.format(id)) + self.__api_request('DELETE', f'/api/v1/admin/domain_blocks/{id}') else: raise AttributeError("You must provide an id of an existing domain block to remove it.") diff --git a/mastodon/authentication.py b/mastodon/authentication.py index d4cb283..9f42587 100644 --- a/mastodon/authentication.py +++ b/mastodon/authentication.py @@ -61,13 +61,13 @@ class Mastodon(Internals): if website is not None: request_data['website'] = website if session: - ret = session.post(api_base_url + '/api/v1/apps', data=request_data, timeout=request_timeout) + ret = session.post(f"{api_base_url}/api/v1/apps", data=request_data, timeout=request_timeout) response = ret.json() else: - response = requests.post(api_base_url + '/api/v1/apps', data=request_data, timeout=request_timeout) + response = requests.post(f"{api_base_url}/api/v1/apps", data=request_data, timeout=request_timeout) response = response.json() except Exception as e: - raise MastodonNetworkError("Could not complete request: %s" % e) + raise MastodonNetworkError(f"Could not complete request: {e}") if to_file is not None: with open(to_file, 'w') as secret_file: @@ -325,11 +325,11 @@ class Mastodon(Internals): self.__set_token_expired(int(response.get('expires_in', 0))) except Exception as e: if username is not None or password is not None: - raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e) + raise MastodonIllegalArgumentError(f'Invalid user name, password, or redirect_uris: {e}') elif code is not None: - raise MastodonIllegalArgumentError('Invalid access token or redirect_uris: %s' % e) + raise MastodonIllegalArgumentError(f'Invalid access token or redirect_uris: {e}') else: - raise MastodonIllegalArgumentError('Invalid request: %s' % e) + raise MastodonIllegalArgumentError(f'Invalid request: {e}') received_scopes = response["scope"].split(" ") for scope_set in _SCOPE_SETS.keys(): diff --git a/mastodon/conversations.py b/mastodon/conversations.py index ba3ee61..5482fb7 100644 --- a/mastodon/conversations.py +++ b/mastodon/conversations.py @@ -39,5 +39,4 @@ class Mastodon(Internals): Returns the updated :ref:`conversation dict `. """ id = self.__unpack_id(id) - url = '/api/v1/conversations/{0}/read'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/conversations/{id}/read') diff --git a/mastodon/filters.py b/mastodon/filters.py index 5f373d4..8841ba8 100644 --- a/mastodon/filters.py +++ b/mastodon/filters.py @@ -29,8 +29,7 @@ class Mastodon(Internals): Returns a :ref:`filter dict `. """ id = self.__unpack_id(id) - url = '/api/v1/filters/{0}'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/filters/{id}') @api_version("2.4.3", "2.4.3", _DICT_VERSION_FILTER) def filters_apply(self, objects, filters, context): @@ -106,8 +105,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/filters/{0}'.format(str(id)) - return self.__api_request('PUT', url, params) + return self.__api_request('PUT', f'/api/v1/filters/{id}', params) @api_version("2.4.3", "2.4.3", "2.4.3") def filter_delete(self, id): @@ -115,5 +113,4 @@ class Mastodon(Internals): Deletes the filter with the given `id`. """ id = self.__unpack_id(id) - url = '/api/v1/filters/{0}'.format(str(id)) - self.__api_request('DELETE', url) \ No newline at end of file + self.__api_request('DELETE', f'/api/v1/filters/{id}') diff --git a/mastodon/hashtags.py b/mastodon/hashtags.py index 89e8cac..f894c11 100644 --- a/mastodon/hashtags.py +++ b/mastodon/hashtags.py @@ -47,6 +47,4 @@ class Mastodon(Internals): Deletes one of the logged-in user's featured hashtags. """ id = self.__unpack_id(id) - url = '/api/v1/featured_tags/{0}'.format(str(id)) - self.__api_request('DELETE', url) - \ No newline at end of file + self.__api_request('DELETE', f'/api/v1/featured_tags/{id}') diff --git a/mastodon/instance.py b/mastodon/instance.py index dfbbefb..1217596 100644 --- a/mastodon/instance.py +++ b/mastodon/instance.py @@ -156,8 +156,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) - url = '/api/v1/announcements/{0}/dismiss'.format(str(id)) - self.__api_request('POST', url) + self.__api_request('POST', f'/api/v1/announcements/{id}/dismiss') @api_version("3.1.0", "3.1.0", "3.1.0") def announcement_reaction_create(self, id, reaction): @@ -171,9 +170,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) - url = '/api/v1/announcements/{0}/reactions/{1}'.format( - str(id), reaction) - self.__api_request('PUT', url) + self.__api_request('PUT', f'/api/v1/announcements/{id}/reactions/{reaction}') @api_version("3.1.0", "3.1.0", "3.1.0") def announcement_reaction_delete(self, id, reaction): @@ -184,6 +181,4 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) - url = '/api/v1/announcements/{0}/reactions/{1}'.format( - str(id), reaction) - self.__api_request('DELETE', url) + self.__api_request('DELETE', f'/api/v1/announcements/{id}/reactions/{reaction}') diff --git a/mastodon/internals.py b/mastodon/internals.py index 758a1d4..d94a116 100644 --- a/mastodon/internals.py +++ b/mastodon/internals.py @@ -182,11 +182,10 @@ class Mastodon(): base_url = base_url_override if self.debug_requests: - print('Mastodon: Request to endpoint "' + base_url + - endpoint + '" using method "' + method + '".') - print('Parameters: ' + str(params)) - print('Headers: ' + str(headers)) - print('Files: ' + str(files)) + print(f'Mastodon: Request to endpoint "{base_url}{endpoint}" using method "{method}".') + print(f'Parameters: {params}') + print(f'Headers: {headers}') + print(f'Files: {files}') # Make request request_complete = False @@ -205,7 +204,7 @@ class Mastodon(): response_object = self.session.request(method, base_url + endpoint, **kwargs) except Exception as e: - raise MastodonNetworkError("Could not complete request: %s" % e) + raise MastodonNetworkError(f"Could not complete request: {e}") if response_object is None: raise MastodonIllegalArgumentError("Illegal request.") @@ -219,8 +218,7 @@ class Mastodon(): # For gotosocial, we need an int representation, but for non-ints this would crash try: - ratelimit_intrep = str( - int(response_object.headers['X-RateLimit-Reset'])) + ratelimit_intrep = str(int(response_object.headers['X-RateLimit-Reset'])) except: ratelimit_intrep = None @@ -240,13 +238,13 @@ class Mastodon(): self.ratelimit_reset += server_time_diff self.ratelimit_lastcall = time.time() except Exception as e: - raise MastodonRatelimitError("Rate limit time calculations failed: %s" % e) + raise MastodonRatelimitError(f"Rate limit time calculations failed: {e}") # Handle response if self.debug_requests: - print('Mastodon: Response received with code ' + str(response_object.status_code) + '.') - print('response headers: ' + str(response_object.headers)) - print('Response text content: ' + str(response_object.text)) + print(f'Mastodon: Response received with code {response_object.status_code}.') + print(f'response headers: {response_object.headers}') + print(f'Response text content: {response_object.text}') if not response_object.ok: try: @@ -306,9 +304,9 @@ class Mastodon(): response = response_object.json(object_hook=self.__json_hooks) except: raise MastodonAPIError( - "Could not parse response as JSON, response code was %s, " - "bad json content was '%s'" % (response_object.status_code, - response_object.content)) + f"Could not parse response as JSON, response code was {response_object.status_code}, " + f"bad json content was {response_object.content!r}." + ) else: response = response_object.content @@ -413,8 +411,8 @@ class Mastodon(): url = "http://" + parse.netloc else: raise MastodonAPIError( - "Could not parse streaming api location returned from server: {}.".format( - instance["urls"]["streaming_api"])) + f"Could not parse streaming api location returned from server: {instance['urls']['streaming_api']}." + ) else: url = self.api_base_url return url @@ -436,16 +434,14 @@ class Mastodon(): # Connect function (called and then potentially passed to async handler) def connect_func(): - headers = {"Authorization": "Bearer " + - self.access_token} if self.access_token else {} + headers = {"Authorization": "Bearer " + self.access_token} if self.access_token else {} if self.user_agent: headers['User-Agent'] = self.user_agent connection = self.session.get(url + endpoint, headers=headers, data=params, stream=True, timeout=(self.request_timeout, timeout)) if connection.status_code != 200: - raise MastodonNetworkError( - "Could not connect to streaming server: %s" % connection.reason) + raise MastodonNetworkError(f"Could not connect to streaming server: {connection.reason}") return connection connection = None @@ -638,7 +634,7 @@ class Mastodon(): raise MastodonIllegalArgumentError('Could not determine mime type or data passed directly without mime type.') if file_name is None: random_suffix = uuid.uuid4().hex - file_name = "mastodonpyupload_" + str(time.time()) + "_" + str(random_suffix) + mimetypes.guess_extension(mime_type) + file_name = f"mastodonpyupload_{time.time()}_{random_suffix}{mimetypes.guess_extension(mime_type)}" return (file_name, media_file, mime_type) @staticmethod diff --git a/mastodon/lists.py b/mastodon/lists.py index 0882133..57ced46 100644 --- a/mastodon/lists.py +++ b/mastodon/lists.py @@ -26,7 +26,7 @@ class Mastodon(Internals): Returns a :ref:`list dict `. """ id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/lists/{0}'.format(id)) + return self.__api_request('GET', f'/api/v1/lists/{id}') @api_version("2.1.0", "2.6.0", _DICT_VERSION_ACCOUNT) def list_accounts(self, id, max_id=None, min_id=None, since_id=None, limit=None): @@ -47,7 +47,7 @@ class Mastodon(Internals): since_id = self.__unpack_id(since_id, dateconv=True) params = self.__generate_params(locals(), ['id']) - return self.__api_request('GET', '/api/v1/lists/{0}/accounts'.format(id)) + return self.__api_request('GET', f'/api/v1/lists/{id}/accounts') ### # Writing data: Lists @@ -71,7 +71,7 @@ class Mastodon(Internals): """ id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) - return self.__api_request('PUT', '/api/v1/lists/{0}'.format(id), params) + return self.__api_request('PUT', f'/api/v1/lists/{id}', params) @api_version("2.1.0", "2.1.0", "2.1.0") def list_delete(self, id): @@ -79,7 +79,7 @@ class Mastodon(Internals): Delete a list. """ id = self.__unpack_id(id) - self.__api_request('DELETE', '/api/v1/lists/{0}'.format(id)) + self.__api_request('DELETE', f'/api/v1/lists/{id}') @api_version("2.1.0", "2.1.0", "2.1.0") def list_accounts_add(self, id, account_ids): @@ -93,8 +93,7 @@ class Mastodon(Internals): account_ids = list(map(lambda x: self.__unpack_id(x), account_ids)) params = self.__generate_params(locals(), ['id']) - self.__api_request( - 'POST', '/api/v1/lists/{0}/accounts'.format(id), params) + self.__api_request('POST', f'/api/v1/lists/{id}/accounts', params) @api_version("2.1.0", "2.1.0", "2.1.0") def list_accounts_delete(self, id, account_ids): @@ -108,5 +107,4 @@ class Mastodon(Internals): account_ids = list(map(lambda x: self.__unpack_id(x), account_ids)) params = self.__generate_params(locals(), ['id']) - self.__api_request( - 'DELETE', '/api/v1/lists/{0}/accounts'.format(id), params) \ No newline at end of file + self.__api_request('DELETE', f'/api/v1/lists/{id}/accounts', params) \ No newline at end of file diff --git a/mastodon/media.py b/mastodon/media.py index 3c815fb..41843a6 100644 --- a/mastodon/media.py +++ b/mastodon/media.py @@ -19,7 +19,7 @@ class Mastodon(Internals): to the logged-in user. """ id = self.__unpack_id(id) - return self.__api_request('GET', '/api/v1/media/{0}'.format(str(id))) + return self.__api_request('GET', f'/api/v1/media/{id}') ### # Writing data: Media @@ -57,7 +57,7 @@ class Mastodon(Internals): media_file, mime_type, file_name)} if focus is not None: - focus = str(focus[0]) + "," + str(focus[1]) + focus = f"{focus[0]},{focus[1]}" if thumbnail is not None: if not self.verify_minimum_version("3.2.0", cached=True): @@ -99,7 +99,7 @@ class Mastodon(Internals): id = self.__unpack_id(id) if focus is not None: - focus = str(focus[0]) + "," + str(focus[1]) + focus = f"{focus[0]},{focus[1]}" params = self.__generate_params( locals(), ['id', 'thumbnail', 'thumbnail_mime_type']) @@ -109,6 +109,6 @@ class Mastodon(Internals): raise MastodonVersionError('Thumbnail requires version > 3.2.0') files = {"thumbnail": self.__load_media_file( thumbnail, thumbnail_mime_type)} - return self.__api_request('PUT', '/api/v1/media/{0}'.format(str(id)), params, files=files) + return self.__api_request('PUT', f'/api/v1/media/{id}', params, files=files) else: - return self.__api_request('PUT', '/api/v1/media/{0}'.format(str(id)), params) + return self.__api_request('PUT', f'/api/v1/media/{id}', params) diff --git a/mastodon/notifications.py b/mastodon/notifications.py index f65b3fb..6d2d1f7 100644 --- a/mastodon/notifications.py +++ b/mastodon/notifications.py @@ -64,8 +64,7 @@ class Mastodon(Internals): return self.__api_request('GET', '/api/v1/notifications', params) else: id = self.__unpack_id(id) - url = '/api/v1/notifications/{0}'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f"/api/v1/notifications/{id}") ### # Writing data: Notifications @@ -85,8 +84,7 @@ class Mastodon(Internals): id = self.__unpack_id(id) if self.verify_minimum_version("2.9.2", cached=True): - url = '/api/v1/notifications/{0}/dismiss'.format(str(id)) - self.__api_request('POST', url) + self.__api_request('POST', f'/api/v1/notifications/{id}/dismiss') else: params = self.__generate_params(locals()) self.__api_request('POST', '/api/v1/notifications/dismiss', params) diff --git a/mastodon/polls.py b/mastodon/polls.py index d974531..2722ba8 100644 --- a/mastodon/polls.py +++ b/mastodon/polls.py @@ -17,8 +17,7 @@ class Mastodon(Internals): Returns a :ref:`poll dict `. """ id = self.__unpack_id(id) - url = '/api/v1/polls/{0}'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/polls/{id}') ### # Writing data: Polls @@ -44,9 +43,8 @@ class Mastodon(Internals): choices = [choices] params = self.__generate_params(locals(), ['id']) - url = '/api/v1/polls/{0}/votes'.format(id) - self.__api_request('POST', url, params) - + self.__api_request('POST', f'/api/v1/polls/{id}/votes', params) + def make_poll(self, options, expires_in, multiple=False, hide_totals=False): """ Generate a poll object that can be passed as the `poll` option when posting a status. diff --git a/mastodon/relationships.py b/mastodon/relationships.py index 9cf15db..043174c 100644 --- a/mastodon/relationships.py +++ b/mastodon/relationships.py @@ -102,8 +102,7 @@ class Mastodon(Internals): Returns the updated :ref:`relationship dict ` for the requesting account. """ id = self.__unpack_id(id) - url = '/api/v1/follow_requests/{0}/authorize'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/follow_requests/{id}/authorize') @api_version("1.0.0", "3.0.0", _DICT_VERSION_RELATIONSHIP) def follow_request_reject(self, id): @@ -113,8 +112,7 @@ class Mastodon(Internals): Returns the updated :ref:`relationship dict ` for the requesting account. """ id = self.__unpack_id(id) - url = '/api/v1/follow_requests/{0}/reject'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/follow_requests/{id}/reject') ### # Writing data: Domain blocks diff --git a/mastodon/statuses.py b/mastodon/statuses.py index 36a7d2b..eb372d8 100644 --- a/mastodon/statuses.py +++ b/mastodon/statuses.py @@ -23,8 +23,7 @@ class Mastodon(Internals): Returns a :ref:`status dict `. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/statuses/{id}') @api_version("1.0.0", "3.0.0", _DICT_VERSION_CARD) def status_card(self, id): @@ -45,8 +44,7 @@ class Mastodon(Internals): return self.status(id).card else: id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/card'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/statuses/{id}/card') @api_version("1.0.0", "1.0.0", _DICT_VERSION_CONTEXT) def status_context(self, id): @@ -58,8 +56,7 @@ class Mastodon(Internals): Returns a :ref:`context dict `. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/context'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/statuses/{id}/context') @api_version("1.0.0", "2.1.0", _DICT_VERSION_ACCOUNT) def status_reblogged_by(self, id): @@ -71,8 +68,7 @@ class Mastodon(Internals): Returns a list of :ref:`account dicts `. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/reblogged_by'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/statuses/{id}/reblogged_by') @api_version("1.0.0", "2.1.0", _DICT_VERSION_ACCOUNT) def status_favourited_by(self, id): @@ -84,8 +80,7 @@ class Mastodon(Internals): Returns a list of :ref:`account dicts `. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/favourited_by'.format(str(id)) - return self.__api_request('GET', url) + return self.__api_request('GET', f'/api/v1/statuses/{id}/favourited_by') ### # Reading data: Scheduled statuses @@ -107,9 +102,8 @@ class Mastodon(Internals): Returns a :ref:`scheduled status dict `. """ id = self.__unpack_id(id) - url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) - return self.__api_request('GET', url) - + return self.__api_request('GET', f'/api/v1/scheduled_statuses/{id}') + ### # Writing data: Statuses ### @@ -150,7 +144,7 @@ class Mastodon(Internals): else: params_initial['visibility'] = params_initial['visibility'].lower() if params_initial['visibility'] not in valid_visibilities: - raise ValueError('Invalid visibility value! Acceptable values are %s' % valid_visibilities) + raise ValueError(f'Invalid visibility value! Acceptable values are {valid_visibilities}') if params_initial['language'] is None: del params_initial['language'] @@ -170,7 +164,7 @@ class Mastodon(Internals): for media_id in media_ids: media_ids_proper.append(self.__unpack_id(media_id)) except Exception as e: - raise MastodonIllegalArgumentError("Invalid media dict: %s" % e) + raise MastodonIllegalArgumentError(f"Invalid media dict: {e}") params_initial["media_ids"] = media_ids_proper @@ -187,7 +181,7 @@ class Mastodon(Internals): return self.__api_request('POST', '/api/v1/statuses', params, headers=headers, use_json=use_json) else: # Edit - return self.__api_request('PUT', '/api/v1/statuses/{0}'.format(str(self.__unpack_id(edit))), params, headers=headers, use_json=use_json) + return self.__api_request('PUT', f'/api/v1/statuses/{self.__unpack_id(edit)}', params, headers=headers, use_json=use_json) @api_version("1.0.0", "2.8.0", _DICT_VERSION_STATUS) def status_post(self, status, in_reply_to_id=None, media_ids=None, @@ -303,7 +297,7 @@ class Mastodon(Internals): will have three, and so on. """ id = self.__unpack_id(id) - return self.__api_request('GET', "/api/v1/statuses/{0}/history".format(str(id))) + return self.__api_request('GET', f"/api/v1/statuses/{id}/history") def status_source(self, id): """ @@ -314,7 +308,7 @@ class Mastodon(Internals): instead. """ id = self.__unpack_id(id) - return self.__api_request('GET', "/api/v1/statuses/{0}/source".format(str(id))) + return self.__api_request('GET', f"/api/v1/statuses/{id}/source") @api_version("1.0.0", "2.8.0", _DICT_VERSION_STATUS) def status_reply(self, to_status, status, in_reply_to_id=None, media_ids=None, @@ -372,8 +366,7 @@ class Mastodon(Internals): "delete and redraft" functionality) """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}'.format(str(id)) - return self.__api_request('DELETE', url) + return self.__api_request('DELETE', f'/api/v1/statuses/{id}') @api_version("1.0.0", "2.0.0", _DICT_VERSION_STATUS) def status_reblog(self, id, visibility=None): @@ -390,12 +383,10 @@ class Mastodon(Internals): if 'visibility' in params: params['visibility'] = params['visibility'].lower() if params['visibility'] not in valid_visibilities: - raise ValueError('Invalid visibility value! Acceptable ' - 'values are %s' % valid_visibilities) + raise ValueError(f'Invalid visibility value! Acceptable values are {valid_visibilities}') id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/reblog'.format(str(id)) - return self.__api_request('POST', url, params) + return self.__api_request('POST', f'/api/v1/statuses/{id}/reblog', params) @api_version("1.0.0", "2.0.0", _DICT_VERSION_STATUS) def status_unreblog(self, id): @@ -405,8 +396,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the status that used to be reblogged. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/unreblog'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/unreblog') @api_version("1.0.0", "2.0.0", _DICT_VERSION_STATUS) def status_favourite(self, id): @@ -416,8 +406,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the favourited status. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/favourite'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/favourite') @api_version("1.0.0", "2.0.0", _DICT_VERSION_STATUS) def status_unfavourite(self, id): @@ -427,8 +416,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the un-favourited status. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/unfavourite'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/unfavourite') @api_version("1.4.0", "2.0.0", _DICT_VERSION_STATUS) def status_mute(self, id): @@ -438,8 +426,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the now muted status """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/mute'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/mute') @api_version("1.4.0", "2.0.0", _DICT_VERSION_STATUS) def status_unmute(self, id): @@ -449,8 +436,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the status that used to be muted. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/unmute'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/unmute') @api_version("2.1.0", "2.1.0", _DICT_VERSION_STATUS) def status_pin(self, id): @@ -460,8 +446,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the now pinned status """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/pin'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/pin') @api_version("2.1.0", "2.1.0", _DICT_VERSION_STATUS) def status_unpin(self, id): @@ -471,8 +456,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the status that used to be pinned. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/unpin'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/unpin') @api_version("3.1.0", "3.1.0", _DICT_VERSION_STATUS) def status_bookmark(self, id): @@ -482,8 +466,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the now bookmarked status """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/bookmark'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/bookmark') @api_version("3.1.0", "3.1.0", _DICT_VERSION_STATUS) def status_unbookmark(self, id): @@ -493,8 +476,7 @@ class Mastodon(Internals): Returns a :ref:`status dict ` with the status that used to be bookmarked. """ id = self.__unpack_id(id) - url = '/api/v1/statuses/{0}/unbookmark'.format(str(id)) - return self.__api_request('POST', url) + return self.__api_request('POST', f'/api/v1/statuses/{id}/unbookmark') ### # Writing data: Scheduled statuses @@ -511,8 +493,7 @@ class Mastodon(Internals): scheduled_at = self.__consistent_isoformat_utc(scheduled_at) id = self.__unpack_id(id) params = self.__generate_params(locals(), ['id']) - url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) - return self.__api_request('PUT', url, params) + return self.__api_request('PUT', f'/api/v1/scheduled_statuses/{id}', params) @api_version("2.7.0", "2.7.0", "2.7.0") def scheduled_status_delete(self, id): @@ -520,5 +501,4 @@ class Mastodon(Internals): Deletes a scheduled status. """ id = self.__unpack_id(id) - url = '/api/v1/scheduled_statuses/{0}'.format(str(id)) - self.__api_request('DELETE', url) + self.__api_request('DELETE', f'/api/v1/scheduled_statuses/{id}') diff --git a/mastodon/streaming_endpoints.py b/mastodon/streaming_endpoints.py index 9ff72f5..fc705e6 100644 --- a/mastodon/streaming_endpoints.py +++ b/mastodon/streaming_endpoints.py @@ -46,7 +46,7 @@ class Mastodon(Internals): base = '/api/v1/streaming/hashtag' if local: base += '/local' - return self.__stream("{}?tag={}".format(base, tag), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) + return self.__stream(f"{base}?tag={tag}", listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) @api_version("2.1.0", "2.1.0", _DICT_VERSION_STATUS) def stream_list(self, id, listener, run_async=False, timeout=_DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=_DEFAULT_STREAM_RECONNECT_WAIT_SEC): @@ -55,7 +55,7 @@ class Mastodon(Internals): list. """ id = self.__unpack_id(id) - return self.__stream("/api/v1/streaming/list?list={}".format(id), listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) + return self.__stream(f"/api/v1/streaming/list?list={id}", listener, run_async=run_async, timeout=timeout, reconnect_async=reconnect_async, reconnect_async_wait_sec=reconnect_async_wait_sec) @api_version("2.6.0", "2.6.0", _DICT_VERSION_STATUS) def stream_direct(self, listener, run_async=False, timeout=_DEFAULT_STREAM_TIMEOUT, reconnect_async=False, reconnect_async_wait_sec=_DEFAULT_STREAM_RECONNECT_WAIT_SEC): diff --git a/mastodon/suggestions.py b/mastodon/suggestions.py index ab55993..a94204b 100644 --- a/mastodon/suggestions.py +++ b/mastodon/suggestions.py @@ -28,5 +28,4 @@ class Mastodon(Internals): Remove the user with the given `account_id` from the follow suggestions. """ account_id = self.__unpack_id(account_id) - url = '/api/v1/suggestions/{0}'.format(str(account_id)) - self.__api_request('DELETE', url) \ No newline at end of file + self.__api_request('DELETE', f'/api/v1/suggestions/{account_id}') diff --git a/mastodon/timeline.py b/mastodon/timeline.py index 04406ed..37790c8 100644 --- a/mastodon/timeline.py +++ b/mastodon/timeline.py @@ -50,8 +50,7 @@ class Mastodon(Internals): params_initial['local'] = True params = self.__generate_params(params_initial, ['timeline']) - url = '/api/v1/timelines/{0}'.format(timeline) - return self.__api_request('GET', url, params) + return self.__api_request('GET', f'/api/v1/timelines/{timeline}', params) @api_version("1.0.0", "3.1.4", _DICT_VERSION_STATUS) def timeline_home(self, max_id=None, min_id=None, since_id=None, limit=None, only_media=False, local=False, remote=False): @@ -91,7 +90,7 @@ class Mastodon(Internals): if hashtag.startswith("#"): raise MastodonIllegalArgumentError( "Hashtag parameter should omit leading #") - return self.timeline('tag/{0}'.format(hashtag), max_id=max_id, min_id=min_id, since_id=since_id, limit=limit, only_media=only_media, local=local, remote=remote) + return self.timeline(f'tag/{hashtag}', max_id=max_id, min_id=min_id, since_id=since_id, limit=limit, only_media=only_media, local=local, remote=remote) @api_version("2.1.0", "3.1.4", _DICT_VERSION_STATUS) def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None, only_media=False, local=False, remote=False): @@ -101,5 +100,5 @@ class Mastodon(Internals): Returns a list of :ref:`status dicts `. """ id = self.__unpack_id(id) - return self.timeline('list/{0}'.format(id), max_id=max_id, min_id=min_id, since_id=since_id, limit=limit, only_media=only_media, local=local, remote=remote) + return self.timeline(f'list/{id}', max_id=max_id, min_id=min_id, since_id=since_id, limit=limit, only_media=only_media, local=local, remote=remote) diff --git a/mastodon/utility.py b/mastodon/utility.py index 2510dca..200f5c1 100644 --- a/mastodon/utility.py +++ b/mastodon/utility.py @@ -39,14 +39,13 @@ def api_version(created_ver, last_changed_ver, return_value_ver): version = max_version(last_changed_ver, return_value_ver) major, minor, patch = parse_version_string(version) if major > self.mastodon_major: - raise MastodonVersionError("Version check failed (Need version " + version + ")") + raise MastodonVersionError(f"Version check failed (Need version {version})") elif major == self.mastodon_major and minor > self.mastodon_minor: - raise MastodonVersionError("Version check failed (Need version " + version + ")") + raise MastodonVersionError(f"Version check failed (Need version {version})") elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch: - raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")") + raise MastodonVersionError(f"Version check failed (Need version {version}, patch is {self.mastodon_patch})") return function(self, *args, **kwargs) - function.__doc__ = function.__doc__ + "\n\n *Added: Mastodon v" + \ - created_ver + ", last changed: Mastodon v" + last_changed_ver + "*" + function.__doc__ += f"\n\n *Added: Mastodon v{created_ver}, last changed: Mastodon v{last_changed_ver}*" return decorate(function, wrapper) return api_min_version_decorator @@ -59,7 +58,7 @@ class AttribAccessDict(dict): if attr in self: return self[attr] else: - raise AttributeError("Attribute not found: " + str(attr)) + raise AttributeError(f"Attribute not found: {attr}") def __setattr__(self, attr, val): if attr in self: @@ -76,7 +75,7 @@ class AttribAccessList(list): if attr in self: return self[attr] else: - raise AttributeError("Attribute not found: " + str(attr)) + raise AttributeError(f"Attribute not found: {attr}") def __setattr__(self, attr, val): if attr in self: diff --git a/tests/test_create_app.py b/tests/test_create_app.py index c7282df..97556c6 100644 --- a/tests/test_create_app.py +++ b/tests/test_create_app.py @@ -64,7 +64,7 @@ def test_app_account_create(): test_app[1], api_base_url="http://localhost:3000/" ) - test_token = test_app_api.create_account("coolguy" + suffix, "swordfish", "email@localhost" + suffix, agreement=True) + test_token = test_app_api.create_account(f"coolguy{suffix}", "swordfish", f"email@localhost{suffix}", agreement=True) assert test_token # We can also test resending (marginally) diff --git a/tests/test_pagination.py b/tests/test_pagination.py index 9f26140..0c83fe4 100644 --- a/tests/test_pagination.py +++ b/tests/test_pagination.py @@ -16,7 +16,7 @@ UNLIKELY_HASHTAG = "fgiztsshwiaqqiztpmmjbtvmescsculuvmgjgopwoeidbcrixp" def many_statuses(api, n=10, suffix=''): statuses = list() for i in range(n): - status = api.status_post("Toot number {}!{}".format(i, suffix)) + status = api.status_post(f"Toot number {i}!{suffix}") statuses.append(status) yield statuses for status in statuses: @@ -102,10 +102,15 @@ def test_link_headers(api): _id='abc1234' - rmock.register_uri('GET', requests_mock.ANY, json=[{"foo": "bar"}], headers={"link":""" - <{base}/api/v1/timelines/tag/{tag}?max_id={_id}>; rel="next", <{base}/api/v1/timelines/tag/{tag}?since_id={_id}>; rel="prev" - """.format(base=api.api_base_url, tag=UNLIKELY_HASHTAG, _id=_id).strip() - }) + rmock.register_uri( + 'GET', + requests_mock.ANY, + json=[{"foo": "bar"}], + headers={ + "link": f"<{api.api_base_url}/api/v1/timelines/tag/{UNLIKELY_HASHTAG}?max_id={_id}>; rel=\"next\", " + f"<{api.api_base_url}/api/v1/timelines/tag/{UNLIKELY_HASHTAG}?since_id={_id}>; rel=\"prev\"" + } + ) resp = api.timeline_hashtag(UNLIKELY_HASHTAG) assert resp._pagination_next['max_id'] == _id diff --git a/tests/test_status.py b/tests/test_status.py index 8461bc3..56e7397 100644 --- a/tests/test_status.py +++ b/tests/test_status.py @@ -203,7 +203,7 @@ def test_scheduled_status_long_part1(api): else: the_medium_term_future = datetime.datetime.now() + datetime.timedelta(minutes=6) pickle.dump(the_medium_term_future.timestamp(), open("tests/cassettes_special/test_scheduled_status_long_datetimeobjects.pkl", 'wb')) - scheduled_toot = api.status_post("please ensure maximum headroom at " + str(the_medium_term_future), scheduled_at=the_medium_term_future) + scheduled_toot = api.status_post(f"please ensure maximum headroom at {the_medium_term_future}", scheduled_at=the_medium_term_future) scheduled_toot_list = api.scheduled_statuses() assert scheduled_toot.id in map(lambda x: x.id, scheduled_toot_list) pickle.dump(scheduled_toot.params.text, open("tests/cassettes_special/test_scheduled_status_long_text.pkl", 'wb')) -- cgit v1.2.3