-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample.py
More file actions
101 lines (85 loc) · 4.27 KB
/
Copy pathexample.py
File metadata and controls
101 lines (85 loc) · 4.27 KB
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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
"""
example.py — Демонстрация использования Serpmax Python SDK.
Установка зависимости:
pip install requests
Запуск:
python example.py
"""
import json
from serpmax_client import SerpmaxAPI, SerpmaxAPIError
# ── Инициализация ──────────────────────────────────────────────────────────────
# Получите ваш API-ключ в личном кабинете: https://serpmax.ru/account-api
API_KEY = "ВАШ КЛЮЧ"
client = SerpmaxAPI(api_key=API_KEY)
def pp(label: str, data) -> None:
"""Красивый вывод JSON-ответа в консоль."""
print(f"\n{'─' * 60}")
print(f" {label}")
print('─' * 60)
print(json.dumps(data, ensure_ascii=False, indent=2))
# ── 1. Информация о текущем пользователе ──────────────────────────────────────
user = client.get_user()
pp("Профиль пользователя", {
"id": user["data"]["id"],
"email": user["data"]["email"],
"plan_id": user["data"]["plan_id"],
"plan_expiration_date": user["data"]["plan_expiration_date"],
})
# ── 2. Список сайтов ───────────────────────────────────────────────────────────
websites = client.list_websites(page=1)
pp("Список сайтов (страница 1)", {
"total": websites["meta"]["total_results"],
"sites": [
{"id": w["id"], "host": w["host"], "score": w["score"]}
for w in websites["data"]
],
})
# ── 3. Создать новый аудит (одиночный URL) ─────────────────────────────────────
print("\n⏳ Запускаем аудит для https://example.com ...")
new_audit = client.create_audit(url="https://example.com")
audit_data = new_audit["data"]
pp("Результат аудита", {
"id": audit_data["id"],
"url": audit_data["url"],
"score": audit_data["score"],
"is_https": audit_data["is_https"],
"is_ssl_valid": audit_data["is_ssl_valid"],
"ttfb_ms": audit_data["ttfb"],
"response_time_ms": audit_data["response_time"],
"page_size_kb": audit_data["page_size"],
"http_requests": audit_data["http_requests"],
"issues": {
"major": audit_data["major_issues"],
"moderate": audit_data["moderate_issues"],
"minor": audit_data["minor_issues"],
},
"is_queued": audit_data["is_queued"],
})
# ── 4. Получить конкретный аудит по ID ────────────────────────────────────────
audit_id = audit_data["id"]
fetched = client.get_audit(audit_id)
pp(f"Аудит #{audit_id} (полный объект)", fetched["data"])
# ── 5. Список аудитов с фильтрацией по хосту ──────────────────────────────────
audits = client.list_audits(page=1, host="example.com")
pp("Аудиты для example.com", {
"total": audits["meta"]["total_results"],
"items": [
{"id": a["id"], "url": a["url"], "score": a["score"]}
for a in audits["data"]
],
})
# ── 6. Обработка ошибок ────────────────────────────────────────────────────────
print("\n\n── Тест обработки ошибок ──")
try:
bad_client = SerpmaxAPI(api_key="invalid_key_000000")
bad_client.get_user()
except SerpmaxAPIError as e:
print(f"✓ Поймана ошибка API: [{e.status_code}] {e}")
try:
SerpmaxAPI(api_key="")
except ValueError as e:
print(f"✓ Поймана ошибка валидации (пустой ключ): {e}")
try:
SerpmaxAPI(api_key="ключ_с_кириллицей")
except ValueError as e:
print(f"✓ Поймана ошибка валидации (не-ASCII): {e}")