Spaces:
Running
Running
File size: 1,994 Bytes
4b6b17e a3fa62e 4b6b17e 88af923 4b6b17e a3fa62e 4b6b17e 88af923 a3fa62e 65f66d6 a3fa62e 4b6b17e a3fa62e 4b6b17e a3fa62e 88af923 a3fa62e 4b6b17e a3fa62e 88af923 a3fa62e |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
import os
import httpx
hordeApiKey = os.environ.get("HORDE_API_KEY")
baseUrl = "https://aihorde.net/api/v2/"
headers = {
"Content-Type": "application/json",
"apikey": f"{hordeApiKey}"
}
class HordeAPI:
# 省去类初始化,直接在每个方法里创建客户端
async def _fetch(self, url, method="GET", headers=headers):
async with httpx.AsyncClient() as client:
if method == "GET":
response = await client.get(url, headers=headers)
elif method == "POST":
response = await client.post(url, headers=headers)
if response.status_code == 200:
return response.json()
else:
return {
"code": response.status_code,
"reason": response.text
}
class APIContextManager:
def __init__(self, api_call):
self.api_call = api_call
self.result = None
async def __aenter__(self):
self.result = await self.api_call()
return self.result
async def __aexit__(self, exc_type, exc_value, traceback):
pass
# 提供 API 调用方法,直接通过 async with 使用
@staticmethod
def getUserDetails():
async def api_call():
url = f"{baseUrl}find_user"
return await HordeAPI()._fetch(url)
return HordeAPI.APIContextManager(api_call)
@staticmethod
def generateCheck(id):
async def api_call():
url = f"{baseUrl}generate/check/{id}"
return await HordeAPI()._fetch(url, headers={"Content-Type": "application/json"})
return HordeAPI.APIContextManager(api_call)
@staticmethod
def generateStatus(id):
async def api_call():
url = f"{baseUrl}generate/status/{id}"
return await HordeAPI()._fetch(url, headers={"Content-Type": "application/json"})
return HordeAPI.APIContextManager(api_call)
|