notifier/services/core.py

56 lines
1.7 KiB
Python
Raw Normal View History

2023-11-23 22:58:55 +00:00
from typing import List
2023-11-26 10:18:57 +00:00
from httpx import AsyncClient
2023-11-23 22:58:55 +00:00
2023-11-26 10:18:57 +00:00
from orm.author import Author
from orm.shout import Shout
from settings import API_BASE
2023-11-23 22:58:55 +00:00
2023-11-26 10:18:57 +00:00
headers = {"Content-Type": "application/json"}
2023-11-23 22:58:55 +00:00
2023-11-26 10:18:57 +00:00
async def _request_endpoint(query_name, body):
2023-11-23 22:58:55 +00:00
async with AsyncClient() as client:
try:
2023-11-26 10:18:57 +00:00
response = await client.post(API_BASE, headers=headers, json=body)
2023-11-23 22:58:55 +00:00
print(f"[services.core] {query_name}: [{response.status_code}] {len(response.text)} bytes")
if response.status_code != 200:
return []
r = response.json()
if r:
2023-11-26 10:18:57 +00:00
return r.get("data", {}).get(query_name, {})
else:
raise Exception("json response error")
2023-11-23 22:58:55 +00:00
except Exception:
import traceback
traceback.print_exc()
2023-11-26 10:18:57 +00:00
async def get_author(author_id) -> Author:
query_name = "getAuthor"
2023-11-23 22:58:55 +00:00
query_type = "query"
2023-11-26 10:18:57 +00:00
operation = "GetAuthor"
2023-11-24 02:18:02 +00:00
query_fields = "id slug pic name"
2023-11-23 22:58:55 +00:00
gql = {
2023-11-26 10:18:57 +00:00
"query": query_type + " " + operation + " { " + query_name + " { " + query_fields + "м} " + " }",
2023-11-23 22:58:55 +00:00
"operationName": operation,
"variables": None,
}
2023-11-26 10:18:57 +00:00
return await _request_endpoint(query_name, gql)
2023-11-24 02:18:02 +00:00
2023-11-26 10:18:57 +00:00
async def get_followed_shouts(author_id: int) -> List[Shout]:
query_name = "getFollowedShouts"
2023-11-24 02:18:02 +00:00
query_type = "query"
2023-11-26 10:18:57 +00:00
operation = "GetFollowedShouts"
query_fields = "id slug title"
2023-11-24 02:18:02 +00:00
2023-11-26 10:18:57 +00:00
query = f"{query_type} {operation}($author_id: Int!) {{ {query_name}(author_id: $author_id) {{ {query_fields} }} }}"
2023-11-24 02:18:02 +00:00
2023-11-26 10:18:57 +00:00
body = {"query": query, "operationName": operation, "variables": {"author_id": author_id}}
2023-11-24 02:18:02 +00:00
2023-11-26 10:18:57 +00:00
return await _request_endpoint(query_name, body)