support vercel kv db and remove mysql

This commit is contained in:
2024-06-21 13:25:09 +08:00
parent 01c7fb5666
commit b6a025ddef
5 files changed
+56 -110

No files matched your search

+4 -4
View File
@@ -68,9 +68,9 @@ async def query_theme(name: str):
} }
for i in data: for i in data:
response["data"].append({ response["data"].append({
"index": i[0], "index": i["id"],
"image": i[1], "image": i["base64"],
"width": i[2], "width": i["width"],
"height": i[3] "height": i["height"]
}) })
return JSONResponse(response) return JSONResponse(response)
+4 -3
View File
@@ -14,6 +14,7 @@ class Config:
mysql -> mysql://user:pwd@host:port/db mysql -> mysql://user:pwd@host:port/db
deta -> deta deta -> deta
""" """
database = os.getenv("COUNTER_DB") or "sqlite3" # 数据库类型 database = os.getenv("COUNTER_DB") or "vercelkv" # 数据库类型
if os.getenv("PJ_DETA"): api_key = os.getenv("VERCEL_KV_KEY") or "<KEY>"
database = "deta" # 自动设置为deta vercel_kv_url = os.getenv("VERCEL_KV_URL") or "http://127.0.0.1:8000"
themes = {}
+20 -3
View File
@@ -8,6 +8,9 @@
import os import os
from urllib.request import urlretrieve from urllib.request import urlretrieve
import requests
from src.config import Config from src.config import Config
database = Config.database # operator database = Config.database # operator
@@ -26,8 +29,22 @@ if database == "sqlite3":
if database == "sqlite3": if database == "sqlite3":
from src.db.db import SQLite as Database from src.db.db import SQLite as Database
elif database == "deta":
from src.db.db import DetaBase as Database
else: else:
from src.db.db import MySQL as Database from src.db.db import VercelKV as Database
base_url = "https://static.rtast.cn/static/counter"
themes_file = [
"lisu.json",
"moebooru.json",
"asoul.json",
"blacked.json",
"hgelbooru.json",
"lewd.json",
"rule34.json",
"hmoebooru.json"
]
for i in themes_file:
result = requests.get(base_url + f"/{i}").json()
print(f"{i}, Done!")
Config.themes[i.replace(".json", "")] = result
__all__ = [Database] __all__ = [Database]
+22 -94
View File
@@ -4,17 +4,12 @@
# @Development Tool: PyCharm # @Development Tool: PyCharm
# @Create Time: 2022/9/11 # @Create Time: 2022/9/11
# @File Name: db.py # @File Name: db.py
import requests
import os
from src.config import Config from src.config import Config
if Config.database in ["sqlite3", "sqlite"]: if Config.database in ["sqlite3", "sqlite"]:
import sqlite3 as operator import sqlite3 as operator
elif Config.database == "deta":
from deta import Deta
else:
import pymysql as operator
class SQL: class SQL:
@@ -63,102 +58,35 @@ class SQLite(SQL):
self.cursor = self.conn.cursor() self.cursor = self.conn.cursor()
class MySQL(SQL): class VercelKV:
def __init__(self):
super().__init__()
_CONFIG = Config.database.replace("mysql://", "").split("@")
user = _CONFIG[0].split(":")[0]
pwd = _CONFIG[0].split(":")[1]
host = _CONFIG[1].split(":")[0]
port = int(_CONFIG[1].split(":")[1].split("/")[0])
db = _CONFIG[1].split("/")[1]
self.conn = operator.connect(user=user,
passwd=pwd,
host=host,
port=port,
database=db)
self.cursor = self.conn.cursor()
class DetaBase:
def __init__(self):
self.__deta = Deta(os.getenv("PJ_DETA"))
self.__data = self.__deta.AsyncBase("times")
self.__image = self.__deta.AsyncBase("images")
async def __get(self, _id: str) -> tuple:
result = await self.__data.get(_id)
if result is None:
await self.__put_data(_id)
return tuple([_id, 0])
await self.update(_id, result["times"])
await self.__image.close()
await self.__data.close()
return tuple([_id, result["times"]])
async def __put_data(self, _id: str) -> bool:
await self.__data.put({"times": 0}, _id)
await self.__image.close()
await self.__data.close()
return True
async def __update_data(self, _id: str, times: int) -> bool:
new = {"times": times + 1}
await self.__data.update(new, _id)
await self.__image.close()
await self.__data.close()
return True
async def __insert_data(self, _id: str) -> bool:
await self.__put_data(_id)
await self.__image.close()
await self.__data.close()
return True
async def __get_images(self, theme: str) -> list:
response = []
result = await self.__image.get(theme)
for i in result:
if i != "key":
response.append(tuple([
i,
result[i]["base64"],
result[i]["width"],
result[i]["height"]
]))
await self.__image.close()
await self.__data.close()
return response
async def query(self, _id: str) -> tuple: async def query(self, _id: str) -> tuple:
result = await self.__get(_id) times = requests.get(
return result f"{Config.vercel_kv_url}/get/{_id}",
headers={"Authorization": f"Bearer {Config.api_key}"}
).json()["result"]
if times is None:
await self.insert(_id)
return tuple([_id, 0])
await self.update(_id, int(times))
return tuple([_id, times])
async def insert(self, _id: str) -> bool: async def insert(self, _id: str) -> bool:
await self.__insert_data(_id) requests.get(
f"{Config.vercel_kv_url}/set/{_id}/1",
headers={"Authorization": f"Bearer {Config.api_key}"}
)
return True return True
async def update(self, _id: str, times: int) -> bool: async def update(self, _id: str, times: int) -> bool:
await self.__update_data(_id, times) times += 1
requests.get(
f"{Config.vercel_kv_url}/set/{_id}/{times}",
headers={"Authorization": f"Bearer {Config.api_key}"}
)
return True return True
async def query_all(self) -> list: async def query_all(self) -> list:
res = await self.__data.fetch() return list("")
all_items = res.items
while res.last:
res = await self.__data.fetch(last=res.last)
all_items += res.items
await self.__image.close()
await self.__data.close()
result = []
for i in all_items:
result.append((
i["key"],
i["times"]
))
return result
async def query_image(self, theme: str) -> list: async def query_image(self, theme: str) -> list:
result = await self.__get_images(theme) return Config.themes[theme]
return result
+6 -6
View File
@@ -28,15 +28,15 @@ async def resp(_id: str, length: int = 7, theme: str = "lewd") -> dict:
headers = {"cache-control": "max-age=0, no-cache, no-store, must-revalidate", headers = {"cache-control": "max-age=0, no-cache, no-store, must-revalidate",
"Content-Type": "image/svg+xml; charset=utf-8"} "Content-Type": "image/svg+xml; charset=utf-8"}
data = await Database().query_image(theme) data = await Database().query_image(theme)
height = data[0][-1] height = data[0]["height"]
width = data[0][-2] width = data[0]["width"]
counter = 0 counter = 0
for i, n in zip(data, show_number): for i, n in zip(data, show_number):
context.append({ context.append({
"position": i[-2] * counter, "position": i["width"] * counter,
"width": i[-2], "width": i["width"],
"height": i[-1], "height": i["height"],
"base64": data[int(n)][1] "base64": data[int(n)]["base64"]
}) })
counter += 1 counter += 1