-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.py
106 lines (89 loc) · 2.8 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
import json
from typing import Annotated
from fastapi import FastAPI, File, UploadFile, Form, Request
from fastapi.responses import FileResponse, RedirectResponse
from fastapi.middleware.cors import CORSMiddleware
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from dotenv import load_dotenv
import os
import requests
load_dotenv()
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
allow_credentials=True,
)
templates_dir = os.path.join(os.path.dirname(__file__), "templates")
app.mount(
"/templates",
StaticFiles(
directory=templates_dir,
),
name="templates",
)
app.mount(
"/homepage_files",
StaticFiles(
directory=templates_dir+"/homepage_files",
),
name="homepage_files",
)
templates = Jinja2Templates(directory="templates")
@app.get("/")
async def root():
r"""
### Root Endpoint
A function that serves the root endpoint of the API. It returns a FileResponse object that
represents the "index.html" file located in the "templates" directory. This function is
decorated with the `@app.get("/")` decorator, which means it will handle GET requests to the
root URL ("/").
---
Returns:
FileResponse: A FileResponse object representing the "home.html" file.
"""
print(f"Serving template from: {os.path.join(templates_dir, 'home.html')}")
return FileResponse(os.path.join(templates_dir, 'home.html'))
@app.post("/data")
async def data(
amount: Annotated[str, Form()] = "",
date: Annotated[str, Form()] = "",
email: Annotated[str, Form()] = "",
):
# print("data")
print("amount: " + amount)
print("date: " + date)
print("email: " + email)
# Redirect to success page with USD to INR as default currencies
return RedirectResponse(url=f"/success?from_curr=USD&to_curr=INR", status_code=303)
# @app.get("/graph/usd_inr_all")
# async def graph_usd_inr_all():
# return FileResponse("data/usd_inr_all.png")
# @app.get("/favicon.ico")
# async def favicon():
# return FileResponse("favicon.ico")
@app.get("/success")
async def success(request: Request, from_curr: str, to_curr: str):
"""
Endpoint that fetches forex data and displays it using a template
"""
api_url = f"https://ewb.aryankeluskar.com/generate_data"
params = {
"from_currency": from_curr,
"to_currency": to_curr,
"password": os.getenv('API_PASSWORD')
}
response = requests.get(api_url, params=params)
forex_data = response.json()
return templates.TemplateResponse(
"success.html",
{
"from_curr": from_curr,
"to_curr": to_curr,
"request": request,
"forex_data": forex_data
}
)