def fetch_user_data(access_token: str) -> dict: try: response = requests.get( url=settings.PATREON_USER_URL, headers={ "Content-Type": "application/x-www-form-urlencoded", "Authorization": f"Bearer {access_token}", }, params={ "include": "memberships", "fields[user]": "full_name,email,image_url,about", "fields[member]": "patron_status,last_charge_status,last_charge_date,pledge_relationship_start," "lifetime_support_cents,currently_entitled_amount_cents", }, ) except requests.exceptions.RequestException as ex: log.exception(f"Patreon error on fetching user data: {ex}") raise PatreonException(ex) if response.status_code >= 400: # unauthorized etc log.warning( f"Patreon error on fetching user data {response.status_code}: {response.text}" ) raise PatreonException(response.text) try: return response.json() except JSONDecodeError: raise PatreonException("Patreon is down. Please try again")
def fetch_auth_data(code: str) -> dict: try: response = requests.post( url=settings.PATREON_TOKEN_URL, headers={"Content-Type": "application/x-www-form-urlencoded"}, data={ "code": code, "grant_type": "authorization_code", "client_id": settings.PATREON_CLIENT_ID, "client_secret": settings.PATREON_CLIENT_SECRET, "redirect_uri": settings.PATREON_REDIRECT_URL, }, ) except requests.exceptions.RequestException as ex: if "invalid_grant" not in str(ex): log.exception(f"Patreon error on login: {ex}") raise PatreonException(ex) if response.status_code >= 400: log.error( f"Patreon error on login {response.status_code}: {response.text}") raise PatreonException(response.text) try: return response.json() except JSONDecodeError: raise PatreonException("Patreon is down. Please try again")
def refresh_auth_data(refresh_token: str) -> dict: try: response = requests.post( url=settings.PATREON_TOKEN_URL, headers={"Content-Type": "application/x-www-form-urlencoded"}, data={ "refresh_token": refresh_token, "grant_type": "refresh_token", "client_id": settings.PATREON_CLIENT_ID, "client_secret": settings.PATREON_CLIENT_SECRET, }, ) except requests.exceptions.RequestException as ex: log.exception(f"Patreon error on refreshing token: {ex}") raise PatreonException(ex) if response.status_code >= 400: log.error( f"Patreon error on refreshing token {response.status_code}: {response.text}" ) raise PatreonException(response.text) try: return response.json() except JSONDecodeError: raise PatreonException("Patreon is down. Please try again")
def test_patreon_exception(self, mocked_patreon): # given mocked_patreon.fetch_auth_data.side_effect = PatreonException("custom_test_exception") # when response = self.client.get(reverse('patreon_oauth_callback'), data={'code': '1234'}) # then self.assertContains(response=response, text="Не получилось загрузить ваш профиль с серверов патреона", status_code=200)