aboutsummaryrefslogtreecommitdiffstats
path: root/arthur/apis/cloudflare/zones.py
blob: 367dc3be33cef92b414919d4d7ce1152b5cc987b (plain) (blame)
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
"""APIs for managing Cloudflare zones."""
from typing import Optional

import aiohttp

from arthur.config import CONFIG

CF_TOKEN = CONFIG.cloudflare_token


async def list_zones(zone_name: Optional[str] = None) -> dict[str, str]:
    """List all Cloudflare zones."""
    endpoint = "https://api.cloudflare.com/client/v4/zones"
    request_headers = {"X-Auth-User-Service-Key": CF_TOKEN}

    if zone_name is not None:
        endpoint += f"?name={zone_name}"

    async with aiohttp.ClientSession() as session:
        async with session.get(endpoint, headers=request_headers) as response:
            info = await response.json()

    zones = info["result"]

    return {zone.name: zone.id for zone in zones}


async def purge_zone(zone_identifier: str) -> dict:
    """Purge the cache for a Cloudflare zone."""
    endpoint = f"https://api.cloudflare.com/client/v4/zones/{zone_identifier}/purge_cache?purge_everything=true"  # noqa: E501
    request_headers = {"X-Auth-User-Service-Key": CF_TOKEN}

    async with aiohttp.ClientSession() as session:
        async with session.post(endpoint, headers=request_headers) as response:
            info = await response.json()

    return {"success": info["success"], "errors": info["errors"]}