Skip to content

Commit

Permalink
implement (async) client connection init function to fix the problem …
Browse files Browse the repository at this point in the history
…occurring in #64
  • Loading branch information
Tert0 committed Oct 14, 2022
1 parent 8dcbcc6 commit a5ae80e
Show file tree
Hide file tree
Showing 6 changed files with 44 additions and 29 deletions.
5 changes: 5 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,10 @@ discord = DiscordOAuthClient(
"<client-id>", "<client-secret>", "<redirect-url>", ("identify", "guilds", "email")
) # scopes

@app.on_event("startup")
async def on_startup():
await discord.init()


@app.get("/login")
async def login():
Expand Down Expand Up @@ -72,6 +76,7 @@ async def get_user(user: User = Depends(discord.user)):
async def get_guilds(guilds: List = Depends(discord.guilds)):
return guilds
```

# Inspired by
[Starlette-Discord](https://github.com/nwunderly/starlette-discord)

Expand Down
5 changes: 5 additions & 0 deletions examples/basic.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
) # scopes


@app.on_event("startup")
async def on_startup():
await discord.init()


@app.get("/login")
async def login():
return {"url": discord.oauth_login_url}
Expand Down
5 changes: 5 additions & 0 deletions examples/basic_with_custom_state.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,11 @@
) # scopes


@app.on_event("startup")
async def on_startup():
await discord.init()


@app.get("/login")
async def login():
return {"url": discord.get_oauth_login_url(state="my state")}
Expand Down
51 changes: 26 additions & 25 deletions fastapi_discord/client.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
import asyncio
from typing import Dict, List, Optional, Tuple, Union

import aiohttp
import nest_asyncio
from aiocache import cached
from fastapi import Depends, Request
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
Expand Down Expand Up @@ -72,7 +70,7 @@ class DiscordOAuthClient:
scopes: str
proxy: Optional[str]
proxy_auth: Optional[aiohttp.BasicAuth]
client_session: aiohttp.ClientSession
client_session: aiohttp.ClientSession = None

"""Client for Discord Oauth2.
Expand All @@ -93,24 +91,27 @@ 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
self.redirect_uri = redirect_uri
self.scopes = "%20".join(scope for scope in scopes)
self.proxy = proxy
self.proxy_auth = proxy_auth
nest_asyncio.apply()
asyncio.get_running_loop().run_until_complete(asyncio.create_task(self.initialize()))

async def initialize(self):
async def init(self):
"""
Initialized the connection to the discord api
"""
if self.client_session is not None:
return
self.client_session = aiohttp.ClientSession()

def get_oauth_login_url(self, state: Optional[str] = None):
Expand All @@ -135,18 +136,18 @@ async def request(self, route: str, token: str = None, method: Literal["GET", "P
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,10 +160,10 @@ async def request(self, route: str, token: str = None, method: Literal["GET", "P

async def get_token_response(self, payload: PAYLOAD) -> TokenResponse:
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
3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
fastapi==0.85.0
aiohttp==3.8.3
aiocache==0.11.1
uvicorn==0.18.3
nest_asyncio==1.5.6
uvicorn==0.18.3
4 changes: 2 additions & 2 deletions setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,13 @@
setup(
name="fastapi_discord",
packages=find_packages(),
version="0.2.3",
version="0.2.4",
description="Discord OAuth FastAPI extension for APIs",
long_description=readme,
long_description_content_type="text/markdown",
author="Tert0",
license="MIT",
install_requires=["fastapi==0.85.0", "aiohttp==3.8.3", "aiocache==0.11.1", "nest_asyncio==1.5.6"],
install_requires=["fastapi==0.85.0", "aiohttp==3.8.3", "aiocache==0.11.1"],
python_requires=">=3.5",
url="https://github.com/Tert0/fastapi-discord",
)

0 comments on commit a5ae80e

Please sign in to comment.