Internally handle JSONDecodeError

This commit is contained in:
thec0sm0s
2020-05-10 17:47:31 +05:30
parent 1e97db58f5
commit 78e21c4702
2 changed files with 13 additions and 10 deletions

View File

@@ -1,4 +1,6 @@
import requests
import typing
import json
import os
import abc
@@ -74,7 +76,7 @@ class DiscordOAuth2HttpClient(abc.ABC):
auto_refresh_url=configs.DISCORD_TOKEN_URL,
token_updater=self._token_updater)
def request(self, route: str, method="GET", data=None, oauth=True, **kwargs) -> dict:
def request(self, route: str, method="GET", data=None, oauth=True, **kwargs) -> typing.Union[dict, str]:
"""Sends HTTP request to provided route or discord endpoint.
Note
@@ -94,8 +96,9 @@ class DiscordOAuth2HttpClient(abc.ABC):
Returns
-------
dict
Dictionary containing received from sent HTTP GET request.
dict, str
Dictionary containing received from sent HTTP GET request if content-type is ``application/json``
otherwise returns raw text content of the response.
Raises
------
@@ -112,4 +115,7 @@ class DiscordOAuth2HttpClient(abc.ABC):
if response.status_code == 401:
raise exceptions.Unauthorized
try:
return response.json()
except json.JSONDecodeError:
return response.text

View File

@@ -1,6 +1,5 @@
from .. import configs
from json import JSONDecodeError
from .base import DiscordModelsBase
from flask import current_app, session
@@ -93,11 +92,9 @@ class User(DiscordModelsBase):
"""
data = {"access_token": session["DISCORD_OAUTH2_TOKEN"]["access_token"]}
headers = {"Authorization": f"Bot {current_app.config['DISCORD_BOT_TOKEN']}"}
try:
return current_app.discord.request(
f"/guilds/{guild_id}/members/{self.id}", method="PUT", oauth=False, json=data, headers=headers)
except JSONDecodeError:
return dict()
f"/guilds/{guild_id}/members/{self.id}", method="PUT", oauth=False, json=data, headers=headers
) or dict()
class Bot(User):