1
0
Fork 0
sortable-recipes/python-api/api.py
Ava Gaiety Wroten 84a1e7d972 Backend
2019-12-24 16:52:05 -06:00

71 lines
2.2 KiB
Python

from pycnic.core import WSGI, Handler
from key_replacer import KeyReplacer
import requests
import json
class Base(Handler):
hostname = "https://www.themealdb.com/api/json/v1/1/"
def __init__(self):
self.replacable_keys = KeyReplacer(
[
["idMeal", "id"],
["strMeal", "name"],
["strCategory", "category"],
["strArea", "area"],
["strInstructions", "instructions"],
["strDrinkAlternate", "alternate_drink"],
["strMealThumb", "thumbnail_url"],
["strTags", "tags"],
["strYoutube", "youtube_url"],
["strSource", "source_url"],
["dateModified", "date_modified"],
])
def cleanup(self, meal):
self.replacable_keys.do_replace(meal)
self.cleanup_ingredients(meal)
def cleanup_ingredients(self, meal):
potential_length = 20
true_length = 0
# Cleanup Empty Values
for i in reversed(range(potential_length)):
x = str(i + 1)
if (meal["strIngredient" + x] == ''):
true_length = i
del meal["strIngredient" + x]
del meal["strMeasure" + x]
# Convert Ingredients/Measures to Array of Objects
meal["ingredients"] = [0]*true_length
for i in range(0, true_length):
x = str(i + 1)
meal["ingredients"][i] = {
"name": meal["strIngredient" + x],
"measure": meal["strMeasure" + x],
}
del meal["strIngredient" + x]
del meal["strMeasure" + x]
class Details(Base):
def get(self, meal_id = ''):
response = json.loads(requests.get(self.hostname + "lookup.php?i=" + meal_id).text)
for meal in response["meals"]:
self.cleanup(meal)
return json.dumps(response)
class Random(Base):
def get(self):
response = json.loads(requests.get(self.hostname + "random.php").text)
for meal in response["meals"]:
self.cleanup(meal)
return json.dumps(response)
class app(WSGI):
routes = [
("/meals/random", Random()),
("/meal/([\w]+)", Details())
]