gruhit-patel
commited on
Commit
·
826db2e
1
Parent(s):
a11e914
Added Host Access Control
Browse files
main.py
CHANGED
@@ -1,36 +1,42 @@
|
|
1 |
from fastapi import FastAPI, Request
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
|
|
3 |
from QuoteGenerator import QuoteGenerator
|
4 |
from typing import Union
|
5 |
from pydantic import BaseModel
|
|
|
6 |
|
7 |
class QuoteRequest(BaseModel):
|
8 |
tags: Union[None, str]
|
9 |
|
10 |
app = FastAPI()
|
11 |
|
12 |
-
origins = ['
|
13 |
|
14 |
-
#
|
15 |
app.add_middleware(
|
16 |
-
|
17 |
-
|
18 |
-
allow_credentials=True,
|
19 |
-
allow_methods=["POST"],
|
20 |
-
allow_headers=["Content-Type"]
|
21 |
)
|
22 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
23 |
quote_generator = QuoteGenerator()
|
24 |
quote_generator.load_generator()
|
25 |
|
26 |
@app.get("/")
|
27 |
def root(request: Request):
|
28 |
-
print("URL ", request.client.host)
|
29 |
return {"message": "This is the website for quote-generator"}
|
30 |
|
31 |
@app.post("/generate_quote")
|
32 |
-
def generate_quote(req: QuoteRequest
|
33 |
print("Tags: ", req.tags)
|
34 |
-
|
35 |
-
|
36 |
-
return {'quote': "Generated quote"}
|
|
|
1 |
from fastapi import FastAPI, Request
|
2 |
from fastapi.middleware.cors import CORSMiddleware
|
3 |
+
from fastapi.middleware.trustedhost import TrustedHostMiddleware
|
4 |
from QuoteGenerator import QuoteGenerator
|
5 |
from typing import Union
|
6 |
from pydantic import BaseModel
|
7 |
+
import time
|
8 |
|
9 |
class QuoteRequest(BaseModel):
|
10 |
tags: Union[None, str]
|
11 |
|
12 |
app = FastAPI()
|
13 |
|
14 |
+
origins = ['quote-generator.streamlit.app']
|
15 |
|
16 |
+
# Middleware to valiate host
|
17 |
app.add_middleware(
|
18 |
+
TrustedHostMiddleware,
|
19 |
+
allowed_hosts=origins
|
|
|
|
|
|
|
20 |
)
|
21 |
|
22 |
+
#Middleware to note time
|
23 |
+
@app.middleware("http")
|
24 |
+
async def note_response_time(request: Request, call_next):
|
25 |
+
start_time = time.time()
|
26 |
+
response = await call_next(request)
|
27 |
+
process_time = time.time()
|
28 |
+
print(f'Time taken = {process_time-start_time:.1f}s')
|
29 |
+
return response
|
30 |
+
|
31 |
quote_generator = QuoteGenerator()
|
32 |
quote_generator.load_generator()
|
33 |
|
34 |
@app.get("/")
|
35 |
def root(request: Request):
|
|
|
36 |
return {"message": "This is the website for quote-generator"}
|
37 |
|
38 |
@app.post("/generate_quote")
|
39 |
+
def generate_quote(req: QuoteRequest):
|
40 |
print("Tags: ", req.tags)
|
41 |
+
generated_quote_oup = quote_generator.generate_quote(req.tags)
|
42 |
+
return {'quote': generated_quote_oup}
|
|