From c0bc820e0ec6659da09d5c50ec7db1dda5a241d2 Mon Sep 17 00:00:00 2001 From: Rishab Kumar Date: Thu, 7 Mar 2024 10:55:09 -0500 Subject: [PATCH] added fastapi implementation --- app.py | 59 ++++++++++++++++++++++++++++---------------- requirements.txt | 23 ++++++++++++++--- templates/index.html | 2 +- 3 files changed, 58 insertions(+), 26 deletions(-) diff --git a/app.py b/app.py index a4fa125..ad988c2 100644 --- a/app.py +++ b/app.py @@ -1,15 +1,17 @@ -from flask import Flask, jsonify, render_template, request, send_from_directory -import random -import json +from fastapi import FastAPI, Request, HTTPException +from typing import Optional +from fastapi.staticfiles import StaticFiles +from fastapi.templating import Jinja2Templates from azure.cosmos import CosmosClient import os from dotenv import load_dotenv +import random load_dotenv() -#Initialize Flask -app = Flask(__name__) +# Initialize FastAPI +app = FastAPI() # Initialize Cosmos Client url = os.getenv("AZURE_COSMOSDB_URL") @@ -28,33 +30,48 @@ documents = list(container.read_all_items()) +templates = Jinja2Templates(directory="templates") + # Load Browser Favicon Icon -@app.route('/favicon.ico') -def favicon(): - return send_from_directory(os.path.join(app.root_path, 'static'), - 'favicon.ico',mimetype='image/vnd.microsoft.icon') +app.mount("/static", StaticFiles(directory="static"), name="static") + +@app.get('/', description="Return the home page with a random quote.") +async def home(request: Request): + """ + Return the home page with a random quote. -@app.route('/') -def home(): + - **request**: The request object. + """ random_document = random.choice(documents) random_quote = random.choice(random_document['quotes']) - return render_template('index.html', quote=random_quote['quote'], author=random_quote['author']) + return templates.TemplateResponse('index.html', {"request": request, "quote": random_quote['quote'], "author": random_quote['author']}) -@app.route('/api/random', methods=['GET']) -def get_quote(): +@app.get('/api/random', description="Return a random quote.") +async def get_quote(): + """ + Return a random quote. + + This endpoint returns a random quote from the database in JSON format. + """ # Select a random document random_document = random.choice(documents) # Select a random quote from the 'quotes' array in the document random_quote = random.choice(random_document['quotes']) - return jsonify(random_quote), 200 + return {"quote": random_quote['quote'], "author": random_quote['author']} + + +@app.get('/api/search', description="Search for quotes containing a specific word.") +async def search(word: Optional[str] = None): + """ + Search for quotes containing a specific word. + - **word**: The word to search for in the quotes. -@app.route('/api/search', methods=['GET']) -def search(): - word = request.args.get('word', '') + This endpoint returns all quotes that contain the word in JSON format. + """ if not word: - return jsonify({'response': 200, 'message': 'No word provided for search.'}) + return HTTPException(status_code=400, detail="No word provided for search.") # Query for all documents documents = list(container.read_all_items()) @@ -63,9 +80,9 @@ def search(): matching_quotes = [quote for document in documents for quote in document['quotes'] if word.lower() in quote['quote'].lower()] if not matching_quotes: - return jsonify({'response': 200, 'message': 'No quotes matched the query.'}) + return {"response": 200, "message": "No quotes matched the query."} - return jsonify({'response': 200, 'results': matching_quotes}) + return {"response": 200, "results": matching_quotes} #Build Pagination endpoint diff --git a/requirements.txt b/requirements.txt index f3e941e..49f9562 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,8 +1,16 @@ +annotated-types==0.6.0 +anyio==4.3.0 +azure-core==1.30.0 +azure-cosmos==4.5.1 blinker==1.6.2 +certifi==2024.2.2 +charset-normalizer==3.3.2 click==8.1.3 colorama==0.4.6 exceptiongroup==1.2.0 -Flask==2.3.2 +fastapi==0.110.0 +h11==0.14.0 +idna==3.6 importlib-metadata==6.6.0 iniconfig==2.0.0 itsdangerous==2.1.2 @@ -11,11 +19,18 @@ jsonify==0.5 MarkupSafe==2.1.3 packaging==23.2 pluggy==1.4.0 +pydantic==2.6.3 +pydantic-core==2.16.3 pytest==8.0.2 pytest-flask==1.3.0 +python-dotenv==1.0.1 +requests==2.31.0 +six==1.16.0 +sniffio==1.3.1 +starlette==0.36.3 tomli==2.0.1 +typing-extensions==4.10.0 +urllib3==2.2.1 +uvicorn==0.27.1 Werkzeug==2.3.6 zipp==3.15.0 -azure-cosmos==4.5.1 -python-dotenv==1.0.1 - diff --git a/templates/index.html b/templates/index.html index 9bf763b..183bea2 100644 --- a/templates/index.html +++ b/templates/index.html @@ -5,7 +5,7 @@ - +