+1 (315) 557-6473 

Crafting a Python-Based Food Recipes Website

In this guide, we will walk you through the process of building a food recipes website in Python. This website allows users to explore and generate delicious recipes based on a selected cuisine, making it a perfect resource for culinary enthusiasts and those looking for culinary inspiration. We will break down the Python code into smaller blocks and provide a detailed explanation of each block, ensuring you have a clear understanding of how to create your own recipe platform. Whether you're a beginner or an experienced Python developer, this guide will help you embark on your journey to building a delightful and functional food recipes website.

Creating Your Recipe Hub in Python

Explore the step-by-step guide on how to create your food recipes website in Python. This comprehensive resource empowers you to build a platform that allows users to discover and prepare delightful recipes based on their chosen cuisine. Whether you're a culinary enthusiast or a Python developer, this guide will help you with your Python assignment, providing insights into web development and culinary creativity. Dive into the world of coding and cooking, and bring your food recipe website to life with this user-friendly guide.

Import Statements

```python from setuptools import setup, find_packages ```
  • This block imports the necessary modules for the package setup.

Package Setup

```python setup( name="WhatToCook", version="0.1", packages=find_packages(), install_requires=[ "requests", "beautifulsoup4", "pdfkit", "weasyprint" ], entry_points={ "console_scripts": [ "what_to_cook = what_to_cook.Recipe:main", ], }, ) ```
  • This block contains package setup information. It defines the package name, version, required packages, and console script entry point.

Import Statements

```python import random import requests import bs4 import pdfkit import datetime from weasyprint import HTML ```
  • This section imports various modules, including `random` for random selections, `requests` for making HTTP requests, `bs4` (Beautiful Soup) for web scraping, `pdfkit` for generating PDFs, and `datetime` for working with date and time. Additionally, it imports `HTML` from the `weasyprint` library for HTML to PDF conversion.

Class Definition: Recipe

```python class Recipe: def __init__(self, cuisine): self.cuisine = cuisine self.recipes = self.get_recipes() self.veggies = { 1: ['carrot', 'ginger', 'spinach'], 2: ['broccoli', 'cauliflower', 'kale'], 3: ['asparagus', 'green beans', 'peas'], 4: ['zucchini', 'eggplant', 'bell pepper'], 5: ['onion', 'coriander', 'pepper', 'chilli', 'avocado', 'ginger', 'garlic', 'challots', 'turmeric', 'cumin', 'cloves', 'cardamom', 'sugar', 'potatoes', 'cabbage', 'rice'], 6: ['potatoes', 'onion', 'collard greens', 'coriander', 'pepper', 'tamarind', 'chilli', 'garlic', 'challots', 'ginger', 'sugar', 'turmeric', 'cumin', 'cardamom', 'cloves', 'cabbage', 'rice'], 7: ['squash', 'pumpkin', 'sweet potato'], 8: ['beet', 'turnip', 'radish'], 9: ['mushroom', 'onion', 'garlic'], 10: ['celery', 'fennel', 'leek'], 11: ['ginger', 'cabbage', 'radicchio'], 12: ['potato', 'carrot', 'parsnip'] } def get_recipes(self): recipes = [] courses = ['breakfast', 'lunch', 'dinner'] # Use API to get recipes response = requests.get(f'https://www.themealdb.com/api/json/v1/1/filter.php?a={self.cuisine}') data = response.json() if data is None: return recipes for recipe in data['meals']: recipe['course'] = random.choice(courses) recipes.append(recipe) # Scrape website for more recipes response = requests.get(f'https://www.allrecipes.com/recipes/{self.cuisine}/') soup = bs4.BeautifulSoup(response.text, 'html.parser') recipe_cards = soup.find_all('article', class_='card card--recipe') for card in recipe_cards: recipe = {} recipe['title'] = card.find('h3').text recipe['image'] = card.find('img')['src'] recipe['url'] = card.find('a')['href'] recipes.append(recipe) return recipes def simple(self): recipe = random.choice(self.recipes) return self.get_pdf(recipe) def course_specific(self, course): course_recipes = [recipe for recipe in self.recipes if course.lower() in recipe['course'].lower()] if course_recipes: recipe = random.choice(course_recipes) return self.get_pdf(recipe) else: print(f"There is no {course} specific recipe for the selected cuisine") def seasonal(self): now = datetime.datetime.now() month = now.month for recipe in self.recipes: response = requests.get(f'https://www.themealdb.com/api/json/v1/1/lookup.php?i={recipe["idMeal"]}') data = response.json() data = data["meals"][0] for i in range(1, 20): ingStr = f'strIngredient{i}' if data[ingStr] and data[ingStr].lower() in self.veggies[month]: return self.get_pdf(recipe) print("There is no seasonal recipe for the selected cuisine in the current month") def combined(self, course): now = datetime.datetime.now() month = now.month for recipe in self.recipes: if course.lower in recipe['course'].lower(): response = requests.get(f'https://www.themealdb.com/api/json/v1/1/lookup.php?i={recipe["idMeal"]}') data = response.json() data = data["meals"][0] for i in range(1, 20): ingStr = f'strIngredient{i}' if data[ingStr] and data[ingStr].lower() in self.veggies[month]: return self.get_pdf(recipe) print( "There is no combined recipe for the selected cuisine in the current month") def get_pdf(self, recipe): response = requests.get( f'https://www.themealdb.com/api/json/v1/1/lookup.php?i={recipe[ "idMeal"]}') data = response.json() data = data["meals"][0] html = f""" < h1>{recipe['strMeal']} < img src="{recipe['strMealThumb']}" > < h2>Ingredients < ul> < li>{data['strIngredient1']} < li>{data['strIngredient2']} < li>{data['strIngredient3']} < li>{data['strIngredient4']} < li>{data['strIngredient5']} < li>{data['strIngredient6']} < h2>Instructions < p>{data['strInstructions']} """ # Convert HTML string to PDF using WeasyPrint pdf = HTML(string=html).write_pdf() # Save PDF to file with open(f"{recipe['strMeal']}.pdf", "wb") as f: f.write(pdf) return pdf ```

The `Recipe` class is defined, which will handle the core functionality of the recipe website. It contains several methods:

  • `__init__`: Initializes the `Recipe` object with a selected cuisine and a dictionary of vegetables by season.
  • `get_recipes`: Retrieves recipes using an external API and web scraping, storing them in a list.
  • `simple`: Selects a random recipe from the list and generates a PDF of it.
  • `course_specific`: Selects a random recipe from a specific course and generates a PDF.
  • `seasonal`: Searches for a seasonal recipe based on the current month and available ingredients.
  • `combined`: Searches for a combined recipe based on a specific course and available ingredients.
  • `get_pdf`: Generates a PDF for a given recipe.

Main Script (not in a function)

```python """Initialize WhatToCook package.""" __version__ = '0.1.0' ```
  • This block defines the package version and serves as a placeholder for package initialization. It's outside any class or function.

Conclusion

This guide outlines the fundamental components of the Python code used to create a food recipes website. By implementing this code, you can provide users with a platform to explore and prepare a wide range of culinary delights based on their preferred cuisine. Enjoy building your own food recipes website! Whether you're a cooking enthusiast or a developer seeking a creative project, this endeavor offers a delicious blend of technology and gastronomy, allowing you to share your culinary passion with the world. Bon appétit!