Files
lottery_ycms/lottery/api_test.py

102 lines
3.4 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# import requests
# import json
# from dotenv import load_dotenv
# import os
# load_dotenv()
# API_URL='http://106.245.250.243:8000/api/clients'
# API_KEY='g1XqG9lir4RneLuX01VAob+F0MpVCZTpG2is8UBWLZ0='
# def fetch_clients(api_url, api_key):
# """
# Подключаемся к API с использованием заданного X-API-Key
# """
# headers = {
# "X-API-Key": api_key
# }
# try:
# response = requests.get(api_url, headers=headers)
# response.raise_for_status()
# return response.json()
# except requests.exceptions.RequestException as e:
# print(f"Ошибка при запросе к API: {e}")
# return None
# if __name__ == '__main__':
# api_endpoint = f"{os.getenv('API_URL')}"
# api_key = os.getenv("API_KEY")
# print(api_endpoint, api_key)
# if not api_endpoint or not api_key:
# print("Необходимо задать API_URL и API_KEY в .env файле.")
# exit(1)
# clients = fetch_clients(api_endpoint, api_key)
# if clients is not None:
# print(json.dumps(clients, indent=4, ensure_ascii=False))
# else:
# print("Не удалось получить данные с API.")
import requests
import json
import os
from dotenv import load_dotenv
load_dotenv()
class ApiClient:
def __init__(self, base_url=None, api_key=None):
self.base_url = base_url or os.getenv('API_URL', 'http://106.245.250.243:8000/api')
self.api_key = api_key or os.getenv('API_KEY')
if not self.api_key:
raise ValueError("API_KEY не задан ни в .env, ни через параметры конструктора")
self.headers = {
"X-API-Key": self.api_key
}
def fetch_clients(self):
"""Получение списка клиентов"""
try:
url = f"{self.base_url}/clients"
response = requests.get(url, headers=self.headers)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Ошибка при получении клиентов: {e}")
return None
def fetch_invoices(self, filters=None):
"""Получение списка счетов с возможными фильтрами"""
try:
url = f"{self.base_url}/invoices"
response = requests.get(url, headers=self.headers, params=filters)
response.raise_for_status()
return response.json()
except requests.exceptions.RequestException as e:
print(f"Ошибка при получении счетов: {e}")
return None
if __name__ == '__main__':
client = ApiClient()
print("=== Клиенты ===")
clients = client.fetch_clients()
if clients:
print(json.dumps(clients, indent=4, ensure_ascii=False))
else:
print("Не удалось получить клиентов")
print("\n=== Счета ===")
filters = {
"page": 1,
# "created_at[after]": "2024-12-01T00:00:00",
# "created_at[before]": "2025-01-01T00:00:00"
}
invoices = client.fetch_invoices(filters)
if invoices:
print(json.dumps(invoices, indent=4, ensure_ascii=False))
else:
print("Не удалось получить счета")