Skill Tracer
Skills › Scientific Agent Skills › open-notebook › _common.py

_common.py

45 lines · skills/open-notebook/scripts/_common.py at 5f2bc03

1"""Small requests client shared by the Open Notebook examples (v1.14.0)."""
2
3import os
4from urllib.parse import quote
5
6import requests
7
8
9def api_url():
10 """Accept the backend origin or an origin already ending in /api."""
11 base = os.getenv("OPEN_NOTEBOOK_URL", "http://localhost:5055").rstrip("/")
12 return base if base.endswith("/api") else base + "/api"
15def record_path(record_id):
16 """Encode a server-returned record ID as one URL path segment."""
17 return quote(str(record_id), safe="")
20def request(method, path, **kwargs):
21 """Send an authenticated request; fail before decoding a non-success response."""
22 headers = dict(kwargs.pop("headers", {}))
23 password = os.getenv("OPEN_NOTEBOOK_PASSWORD")
24 if password:
25 headers["Authorization"] = f"Bearer {password}"
26 kwargs.setdefault("timeout", (10, 300))
27 # A redirect is not expected for these exact routes. Do not forward a secret
28 # or a mutation body to a different path/deployment implicitly.
29 response = requests.request(
30 method, api_url() + path, headers=headers, allow_redirects=False, **kwargs
31 )
32 try:
33 response.raise_for_status()
34 except requests.HTTPError:
35 response.close()
36 raise
37 if 300 <= response.status_code < 400:
38 response.close()
39 raise requests.HTTPError("Unexpected Open Notebook redirect", response=response)
40 return response
43def request_json(method, path, **kwargs):
44 with request(method, path, **kwargs) as response:
45 return response.json()