Hana Celeste commited on
Update app/gscode_logic.py
Browse files- app/gscode_logic.py +39 -25
app/gscode_logic.py
CHANGED
|
@@ -1,40 +1,54 @@
|
|
| 1 |
# gscode_logic.py
|
| 2 |
-
import
|
| 3 |
from bs4 import BeautifulSoup
|
| 4 |
-
from fastapi import HTTPException
|
| 5 |
|
| 6 |
-
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
# 2. lấy HTML string
|
| 20 |
html = data.get("parse", {}).get("text", {}).get("*")
|
| 21 |
if not html:
|
| 22 |
return {"count": 0, "codes": []}
|
| 23 |
|
| 24 |
-
# 3. parse HTML
|
| 25 |
soup = BeautifulSoup(html, "html.parser")
|
| 26 |
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
codes.append(val)
|
| 33 |
-
|
| 34 |
-
# 5. unique + sort
|
| 35 |
-
codes = sorted(set(codes))
|
| 36 |
|
| 37 |
return {
|
| 38 |
"count": len(codes),
|
| 39 |
-
"codes": codes
|
| 40 |
}
|
|
|
|
| 1 |
# gscode_logic.py
|
| 2 |
+
import aiohttp
|
| 3 |
from bs4 import BeautifulSoup
|
|
|
|
| 4 |
|
| 5 |
+
GENSHIN_API = (
|
| 6 |
+
"https://genshin-impact.fandom.com/api.php"
|
| 7 |
+
"?action=parse"
|
| 8 |
+
"&page=Promotional_Code"
|
| 9 |
+
"&prop=text"
|
| 10 |
+
"&format=json"
|
| 11 |
+
)
|
| 12 |
|
| 13 |
+
class GenshinCodeLogic:
|
| 14 |
+
def __init__(self):
|
| 15 |
+
self.session: aiohttp.ClientSession | None = None
|
| 16 |
+
|
| 17 |
+
async def start(self):
|
| 18 |
+
if not self.session:
|
| 19 |
+
self.session = aiohttp.ClientSession()
|
| 20 |
+
|
| 21 |
+
async def stop(self):
|
| 22 |
+
if self.session:
|
| 23 |
+
await self.session.close()
|
| 24 |
+
self.session = None
|
| 25 |
+
|
| 26 |
+
async def fetch_codes(self):
|
| 27 |
+
async with self.session.get(
|
| 28 |
+
GENSHIN_API,
|
| 29 |
+
headers={
|
| 30 |
+
"User-Agent": "Mozilla/5.0"
|
| 31 |
+
},
|
| 32 |
+
timeout=aiohttp.ClientTimeout(total=20)
|
| 33 |
+
) as resp:
|
| 34 |
+
if resp.status != 200:
|
| 35 |
+
return {"count": 0, "codes": []}
|
| 36 |
+
|
| 37 |
+
data = await resp.json()
|
| 38 |
|
|
|
|
| 39 |
html = data.get("parse", {}).get("text", {}).get("*")
|
| 40 |
if not html:
|
| 41 |
return {"count": 0, "codes": []}
|
| 42 |
|
|
|
|
| 43 |
soup = BeautifulSoup(html, "html.parser")
|
| 44 |
|
| 45 |
+
codes = {
|
| 46 |
+
c.text.strip()
|
| 47 |
+
for c in soup.select("code")
|
| 48 |
+
if c.text and len(c.text.strip()) >= 6
|
| 49 |
+
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
|
| 51 |
return {
|
| 52 |
"count": len(codes),
|
| 53 |
+
"codes": sorted(codes)
|
| 54 |
}
|