From 942d89a08a44b26584fff2cde36969395e00804f Mon Sep 17 00:00:00 2001 From: Tert0 <62036464+Tert0@users.noreply.github.com> Date: Fri, 14 Oct 2022 22:14:05 +0200 Subject: [PATCH] fixed codestyle, added new exception and updated examples --- README.md | 9 ++++++ examples/basic.py | 7 +++++ examples/basic_with_custom_state.py | 7 +++++ fastapi_discord/client.py | 46 ++++++++++++++++------------- fastapi_discord/exceptions.py | 6 ++++ 5 files changed, 54 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index d1e6725..d20ed3b 100644 --- a/README.md +++ b/README.md @@ -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() @@ -21,6 +22,7 @@ discord = DiscordOAuthClient( "", "", "", ("identify", "guilds", "email") ) # scopes + @app.on_event("startup") async def on_startup(): await discord.init() @@ -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 @@ -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 diff --git a/examples/basic.py b/examples/basic.py index 47879d3..b862686 100644 --- a/examples/basic.py +++ b/examples/basic.py @@ -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() @@ -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 diff --git a/examples/basic_with_custom_state.py b/examples/basic_with_custom_state.py index 1eb8db2..9ece130 100644 --- a/examples/basic_with_custom_state.py +++ b/examples/basic_with_custom_state.py @@ -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() @@ -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 diff --git a/fastapi_discord/client.py b/fastapi_discord/client.py index 1f65b4b..ea8820f 100644 --- a/fastapi_discord/client.py +++ b/fastapi_discord/client.py @@ -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 @@ -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. @@ -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 @@ -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: @@ -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() diff --git a/fastapi_discord/exceptions.py b/fastapi_discord/exceptions.py index 34a5a64..cf49946 100644 --- a/fastapi_discord/exceptions.py +++ b/fastapi_discord/exceptions.py @@ -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