-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathrest_api.py
More file actions
92 lines (76 loc) · 2.34 KB
/
Copy pathrest_api.py
File metadata and controls
92 lines (76 loc) · 2.34 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
import os
import json
import logging
import http.client
from typing import List
import typer
from dotenv import load_dotenv
# Load environment variables from .env file
load_dotenv(override=True)
app = typer.Typer()
@app.command("d1_table_query")
def d1_table_query(db_id: str, sql: str, sql_params: List[str] = []) -> dict:
"""
https://developers.cloudflare.com/api/operations/cloudflare-d1-query-database
"""
account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
api_key = os.getenv("CLOUDFLARE_API_KEY")
payload = {
"params": sql_params,
"sql": sql,
}
body = json.dumps(payload)
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
conn = http.client.HTTPSConnection("api.cloudflare.com")
conn.request(
"POST",
f"/client/v4/accounts/{account_id}/d1/database/{db_id}/query",
body,
headers,
)
res = conn.getresponse()
data = res.read().decode("utf-8")
# print(data)
json_data = json.loads(data)
logging.debug(f"body:{body}, db_id:{db_id}, query res:{json_data}")
return json_data
@app.command("d1_db")
def d1_db(db_id: str) -> dict:
"""
https://developers.cloudflare.com/api/operations/cloudflare-d1-get-database
"""
account_id = os.getenv("CLOUDFLARE_ACCOUNT_ID")
api_key = os.getenv("CLOUDFLARE_API_KEY")
conn = http.client.HTTPSConnection("api.cloudflare.com")
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json",
}
conn.request(
"GET",
f"/client/v4/accounts/{account_id}/d1/database/{db_id}",
headers=headers,
)
res = conn.getresponse()
data = res.read()
data = res.read().decode("utf-8")
json_data = json.loads(data)
logging.info(f"get db_id:{db_id}, query res:{json_data}")
return json_data
r"""
python -m demo.cloudflare.rest_api d1_db \
09f7a7c7-66ae-41ea-9dbe-b8b635b19758
python -m demo.cloudflare.rest_api d1_table_query \
09f7a7c7-66ae-41ea-9dbe-b8b635b19758 \
"select * from podcast limit 1"
"""
if __name__ == "__main__":
logging.basicConfig(
level=logging.DEBUG,
format="%(asctime)s - %(name)s - %(levelname)s - %(pathname)s:%(lineno)d - %(funcName)s - %(message)s",
handlers=[logging.StreamHandler()],
)
app()