63 lines
1.8 KiB
Python
63 lines
1.8 KiB
Python
import json
|
||
import os
|
||
import urllib.error
|
||
import urllib.request
|
||
from typing import Any, Dict, Optional
|
||
from worklib.QueryData import kvs_query_data, kvs_query_data_place_id
|
||
from worklib.auth_as_employer import get_access_token
|
||
|
||
|
||
DEFAULT_COMPANY_ID = "65437401ae3af6f8ffcdbaf8"
|
||
|
||
|
||
|
||
def build_headers(access_token: str, *, company_id: str = DEFAULT_COMPANY_ID) -> Dict[str, str]:
|
||
return {
|
||
"authorization": f"bearer {access_token}",
|
||
"x-company-id": company_id,
|
||
}
|
||
|
||
|
||
def fetch_place_members(
|
||
*,
|
||
query: str,
|
||
variables: dict[str, str],
|
||
graphql_url: Optional[str] = None,
|
||
|
||
company_id: str = DEFAULT_COMPANY_ID,
|
||
access_token: Optional[str] = None,
|
||
timeout_s: int = 30,
|
||
) -> Dict[str, Any]:
|
||
graphql_url = graphql_url or os.getenv("GRAPHQL_URL") or "https://admin.dev.dipal.ru/graphql"
|
||
if not graphql_url:
|
||
raise ValueError("Не задан GRAPHQL_URL (передайте graphql_url или установите env GRAPHQL_URL)")
|
||
|
||
token = access_token or get_access_token()
|
||
headers = build_headers(token, company_id=company_id)
|
||
|
||
|
||
|
||
payload = {"query": query, "variables": variables}
|
||
req = urllib.request.Request(
|
||
graphql_url,
|
||
data=json.dumps(payload).encode("utf-8"),
|
||
headers={"content-type": "application/json", **headers},
|
||
method="POST",
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(req, timeout=timeout_s) as resp:
|
||
raw = resp.read().decode("utf-8")
|
||
except urllib.error.HTTPError as e:
|
||
body = e.read().decode("utf-8", errors="replace")
|
||
raise RuntimeError(f"GraphQL HTTP {e.code}: {body}") from e
|
||
|
||
data = json.loads(raw) if raw else {}
|
||
if isinstance(data, dict) and data.get("errors"):
|
||
raise RuntimeError(f"GraphQL errors: {data['errors']}")
|
||
return data
|
||
|
||
|
||
if __name__ == "__main__":
|
||
print()
|
||
|