97 lines
2.3 KiB
Python
97 lines
2.3 KiB
Python
import requests
|
|
import os
|
|
import json
|
|
from pathvalidate import validate_filename
|
|
|
|
from config import *
|
|
|
|
headers = {}
|
|
if TANDOOR_API_TOKEN:
|
|
headers["Authorization"] = f"Bearer {TANDOOR_API_TOKEN}"
|
|
|
|
|
|
def fetch_keyword_id(keyword):
|
|
endpoint = "/api/keyword"
|
|
page = 1
|
|
|
|
while True:
|
|
params = {"query": keyword, "page": page}
|
|
response = requests.get(
|
|
f"{TANDOOR_URL}{endpoint}", params=params, headers=headers
|
|
)
|
|
if response.status_code != 200:
|
|
print(f"Error: Received status code {response.status_code}")
|
|
return None
|
|
|
|
data = response.json()
|
|
|
|
results = data.get("results", [])
|
|
for item in results:
|
|
if item.get("name") == keyword:
|
|
return item.get("id")
|
|
|
|
if not data.get("next"):
|
|
break
|
|
|
|
page += 1
|
|
|
|
raise RuntimeError(f"Keyword '{keyword}' not found.")
|
|
|
|
|
|
def fetch_recipes(keyword_id):
|
|
recipes = []
|
|
endpoint = "/api/recipe"
|
|
page = 1
|
|
|
|
while True:
|
|
params = {"keywords": keyword_id, "page": page}
|
|
response = requests.get(
|
|
f"{TANDOOR_URL}{endpoint}", params=params, headers=headers
|
|
)
|
|
|
|
if response.status_code != 200:
|
|
print(f"Error: Received status code {response.status_code}")
|
|
return None
|
|
|
|
data = response.json()
|
|
|
|
results = data.get("results", [])
|
|
for item in results:
|
|
recipe = fetch_recipe(item.get("id"))
|
|
recipes.append(recipe)
|
|
|
|
if not data.get("next"):
|
|
break
|
|
|
|
page += 1
|
|
|
|
return recipes
|
|
|
|
|
|
def fetch_recipe(recipe_id):
|
|
endpoint = "/api/recipe"
|
|
|
|
response = requests.get(f"{TANDOOR_URL}/api/recipe/{recipe_id}", headers=headers)
|
|
|
|
if response.status_code != 200:
|
|
print(f"Error: Received status code {response.status_code}")
|
|
return None
|
|
|
|
recipe = response.json()
|
|
return recipe
|
|
|
|
|
|
def main():
|
|
keyword_id = fetch_keyword_id(TANDOOR_KEYWORD)
|
|
recipes = fetch_recipes(keyword_id)
|
|
|
|
for recipe in recipes:
|
|
json_fn = f"{recipe.get('name', 'Untitled Recipe')}.json"
|
|
validate_filename(json_fn)
|
|
os.makedirs(OUTDIR_JSON, exist_ok=True)
|
|
with open(os.path.join(OUTDIR_JSON, json_fn), "w") as f:
|
|
json.dump(recipe, f, sort_keys=True, indent=2)
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|