Skip to content

Commit a5ae80e

Browse files
committed
implement (async) client connection init function to fix the problem occurring in #64
1 parent 8dcbcc6 commit a5ae80e

File tree

6 files changed

+44
-29
lines changed

6 files changed

+44
-29
lines changed

README.md

+5
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,10 @@ discord = DiscordOAuthClient(
2121
"<client-id>", "<client-secret>", "<redirect-url>", ("identify", "guilds", "email")
2222
) # scopes
2323

24+
@app.on_event("startup")
25+
async def on_startup():
26+
await discord.init()
27+
2428

2529
@app.get("/login")
2630
async def login():
@@ -72,6 +76,7 @@ async def get_user(user: User = Depends(discord.user)):
7276
async def get_guilds(guilds: List = Depends(discord.guilds)):
7377
return guilds
7478
```
79+
7580
# Inspired by
7681
[Starlette-Discord](https://github.com/nwunderly/starlette-discord)
7782

examples/basic.py

+5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212
) # scopes
1313

1414

15+
@app.on_event("startup")
16+
async def on_startup():
17+
await discord.init()
18+
19+
1520
@app.get("/login")
1621
async def login():
1722
return {"url": discord.oauth_login_url}

examples/basic_with_custom_state.py

+5
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,11 @@
1212
) # scopes
1313

1414

15+
@app.on_event("startup")
16+
async def on_startup():
17+
await discord.init()
18+
19+
1520
@app.get("/login")
1621
async def login():
1722
return {"url": discord.get_oauth_login_url(state="my state")}

fastapi_discord/client.py

+26-25
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,6 @@
1-
import asyncio
21
from typing import Dict, List, Optional, Tuple, Union
32

43
import aiohttp
5-
import nest_asyncio
64
from aiocache import cached
75
from fastapi import Depends, Request
86
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
@@ -72,7 +70,7 @@ class DiscordOAuthClient:
7270
scopes: str
7371
proxy: Optional[str]
7472
proxy_auth: Optional[aiohttp.BasicAuth]
75-
client_session: aiohttp.ClientSession
73+
client_session: aiohttp.ClientSession = None
7674

7775
"""Client for Discord Oauth2.
7876
@@ -93,24 +91,27 @@ class DiscordOAuthClient:
9391
"""
9492

9593
def __init__(
96-
self,
97-
client_id,
98-
client_secret,
99-
redirect_uri,
100-
scopes=("identify",),
101-
proxy=None,
102-
proxy_auth: aiohttp.BasicAuth = None,
94+
self,
95+
client_id,
96+
client_secret,
97+
redirect_uri,
98+
scopes=("identify",),
99+
proxy=None,
100+
proxy_auth: aiohttp.BasicAuth = None,
103101
):
104102
self.client_id = client_id
105103
self.client_secret = client_secret
106104
self.redirect_uri = redirect_uri
107105
self.scopes = "%20".join(scope for scope in scopes)
108106
self.proxy = proxy
109107
self.proxy_auth = proxy_auth
110-
nest_asyncio.apply()
111-
asyncio.get_running_loop().run_until_complete(asyncio.create_task(self.initialize()))
112108

113-
async def initialize(self):
109+
async def init(self):
110+
"""
111+
Initialized the connection to the discord api
112+
"""
113+
if self.client_session is not None:
114+
return
114115
self.client_session = aiohttp.ClientSession()
115116

116117
def get_oauth_login_url(self, state: Optional[str] = None):
@@ -135,18 +136,18 @@ async def request(self, route: str, token: str = None, method: Literal["GET", "P
135136
headers = {"Authorization": f"Bearer {token}"}
136137
if method == "GET":
137138
async with self.client_session.get(
138-
f"{DISCORD_API_URL}{route}",
139-
headers=headers,
140-
proxy=self.proxy,
141-
proxy_auth=self.proxy_auth,
139+
f"{DISCORD_API_URL}{route}",
140+
headers=headers,
141+
proxy=self.proxy,
142+
proxy_auth=self.proxy_auth,
142143
) as resp:
143144
data = await resp.json()
144145
elif method == "POST":
145146
async with self.client_session.post(
146-
f"{DISCORD_API_URL}{route}",
147-
headers=headers,
148-
proxy=self.proxy,
149-
proxy_auth=self.proxy_auth,
147+
f"{DISCORD_API_URL}{route}",
148+
headers=headers,
149+
proxy=self.proxy,
150+
proxy_auth=self.proxy_auth,
150151
) as resp:
151152
data = await resp.json()
152153
else:
@@ -159,10 +160,10 @@ async def request(self, route: str, token: str = None, method: Literal["GET", "P
159160

160161
async def get_token_response(self, payload: PAYLOAD) -> TokenResponse:
161162
async with self.client_session.post(
162-
DISCORD_TOKEN_URL,
163-
data=payload,
164-
proxy=self.proxy,
165-
proxy_auth=self.proxy_auth,
163+
DISCORD_TOKEN_URL,
164+
data=payload,
165+
proxy=self.proxy,
166+
proxy_auth=self.proxy_auth,
166167
) as resp:
167168
return await resp.json()
168169

requirements.txt

+1-2
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
fastapi==0.85.0
22
aiohttp==3.8.3
33
aiocache==0.11.1
4-
uvicorn==0.18.3
5-
nest_asyncio==1.5.6
4+
uvicorn==0.18.3

setup.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -5,13 +5,13 @@
55
setup(
66
name="fastapi_discord",
77
packages=find_packages(),
8-
version="0.2.3",
8+
version="0.2.4",
99
description="Discord OAuth FastAPI extension for APIs",
1010
long_description=readme,
1111
long_description_content_type="text/markdown",
1212
author="Tert0",
1313
license="MIT",
14-
install_requires=["fastapi==0.85.0", "aiohttp==3.8.3", "aiocache==0.11.1", "nest_asyncio==1.5.6"],
14+
install_requires=["fastapi==0.85.0", "aiohttp==3.8.3", "aiocache==0.11.1"],
1515
python_requires=">=3.5",
1616
url="https://github.com/Tert0/fastapi-discord",
1717
)

0 commit comments

Comments
 (0)