Skip to content

Commit

Permalink
fixed codestyle, added new exception and updated examples
Browse files Browse the repository at this point in the history
  • Loading branch information
Tert0 committed Oct 14, 2022
1 parent a5ae80e commit 942d89a
Show file tree
Hide file tree
Showing 5 changed files with 54 additions and 21 deletions.
9 changes: 9 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ from typing import List
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from fastapi_discord import DiscordOAuthClient, RateLimited, Unauthorized, User
from fastapi_discord.exceptions import ClientSessionNotInitialized
from fastapi_discord.models import GuildPreview

app = FastAPI()
Expand All @@ -21,6 +22,7 @@ discord = DiscordOAuthClient(
"<client-id>", "<client-secret>", "<redirect-url>", ("identify", "guilds", "email")
) # scopes


@app.on_event("startup")
async def on_startup():
await discord.init()
Expand Down Expand Up @@ -63,6 +65,12 @@ async def rate_limit_error_handler(_, e: RateLimited):
)


@app.exception_handler(ClientSessionNotInitialized)
async def client_session_error_handler(_, e: ClientSessionNotInitialized):
print(e)
return JSONResponse({"error": "Internal Error"}, status_code=500)


@app.get("/user", dependencies=[Depends(discord.requires_authorization)], response_model=User)
async def get_user(user: User = Depends(discord.user)):
return user
Expand All @@ -75,6 +83,7 @@ async def get_user(user: User = Depends(discord.user)):
)
async def get_guilds(guilds: List = Depends(discord.guilds)):
return guilds

```

# Inspired by
Expand Down
7 changes: 7 additions & 0 deletions examples/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from fastapi_discord import DiscordOAuthClient, RateLimited, Unauthorized, User
from fastapi_discord.exceptions import ClientSessionNotInitialized
from fastapi_discord.models import GuildPreview

app = FastAPI()
Expand Down Expand Up @@ -54,6 +55,12 @@ async def rate_limit_error_handler(_, e: RateLimited):
)


@app.exception_handler(ClientSessionNotInitialized)
async def client_session_error_handler(_, e: ClientSessionNotInitialized):
print(e)
return JSONResponse({"error": "Internal Error"}, status_code=500)


@app.get("/user", dependencies=[Depends(discord.requires_authorization)], response_model=User)
async def get_user(user: User = Depends(discord.user)):
return user
Expand Down
7 changes: 7 additions & 0 deletions examples/basic_with_custom_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
from fastapi import Depends, FastAPI
from fastapi.responses import JSONResponse
from fastapi_discord import DiscordOAuthClient, RateLimited, Unauthorized, User
from fastapi_discord.exceptions import ClientSessionNotInitialized
from fastapi_discord.models import GuildPreview

app = FastAPI()
Expand Down Expand Up @@ -55,6 +56,12 @@ async def rate_limit_error_handler(_, e: RateLimited):
)


@app.exception_handler(ClientSessionNotInitialized)
async def client_session_error_handler(_, e: ClientSessionNotInitialized):
print(e)
return JSONResponse({"error": "Internal Error"}, status_code=500)


@app.get("/user", dependencies=[Depends(discord.requires_authorization)], response_model=User)
async def get_user(user: User = Depends(discord.user)):
return user
Expand Down
46 changes: 25 additions & 21 deletions fastapi_discord/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
from typing_extensions import TypedDict, Literal

from .config import DISCORD_API_URL, DISCORD_OAUTH_AUTHENTICATION_URL, DISCORD_TOKEN_URL
from .exceptions import RateLimited, ScopeMissing, Unauthorized, InvalidToken
from .exceptions import RateLimited, ScopeMissing, Unauthorized, InvalidToken, ClientSessionNotInitialized
from .models import Guild, GuildPreview, User


Expand Down Expand Up @@ -70,7 +70,7 @@ class DiscordOAuthClient:
scopes: str
proxy: Optional[str]
proxy_auth: Optional[aiohttp.BasicAuth]
client_session: aiohttp.ClientSession = None
client_session: Optional[aiohttp.ClientSession] = None

"""Client for Discord Oauth2.
Expand All @@ -91,13 +91,13 @@ class DiscordOAuthClient:
"""

def __init__(
self,
client_id,
client_secret,
redirect_uri,
scopes=("identify",),
proxy=None,
proxy_auth: aiohttp.BasicAuth = None,
self,
client_id,
client_secret,
redirect_uri,
scopes=("identify",),
proxy=None,
proxy_auth: aiohttp.BasicAuth = None,
):
self.client_id = client_id
self.client_secret = client_secret
Expand Down Expand Up @@ -131,23 +131,25 @@ def get_oauth_login_url(self, state: Optional[str] = None):

@cached(ttl=550)
async def request(self, route: str, token: str = None, method: Literal["GET", "POST"] = "GET"):
if self.client_session is None:
raise ClientSessionNotInitialized
headers: Dict = {}
if token:
headers = {"Authorization": f"Bearer {token}"}
if method == "GET":
async with self.client_session.get(
f"{DISCORD_API_URL}{route}",
headers=headers,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
f"{DISCORD_API_URL}{route}",
headers=headers,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
) as resp:
data = await resp.json()
elif method == "POST":
async with self.client_session.post(
f"{DISCORD_API_URL}{route}",
headers=headers,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
f"{DISCORD_API_URL}{route}",
headers=headers,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
) as resp:
data = await resp.json()
else:
Expand All @@ -159,11 +161,13 @@ async def request(self, route: str, token: str = None, method: Literal["GET", "P
return data

async def get_token_response(self, payload: PAYLOAD) -> TokenResponse:
if self.client_session is None:
raise ClientSessionNotInitialized
async with self.client_session.post(
DISCORD_TOKEN_URL,
data=payload,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
DISCORD_TOKEN_URL,
data=payload,
proxy=self.proxy,
proxy_auth=self.proxy_auth,
) as resp:
return await resp.json()

Expand Down
6 changes: 6 additions & 0 deletions fastapi_discord/exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,3 +27,9 @@ class ScopeMissing(Exception):
def __init__(self, scope: str):
self.scope = scope
super().__init__(self.scope)


class ClientSessionNotInitialized(Exception):
"""An exception raised when no Client Session is initialized but one would be needed"""

pass

0 comments on commit 942d89a

Please sign in to comment.