I have develope an API via FastAPI
.
This API will do:
- POST with
user_ip
inclient.py
- Use BigQuery API Client to
query
from data table inv1_router.py
- If
user_ip
exist in data table, return hisgroup
The response time will cost 5 sec
in my computer.
I have try to use time
function to analyze:
3 sec
: instancebigquery.Client
inv1_router.py
2 sec
: doclient.query
andres.to_dataframe().to_dict(orient='records')
Can Someone suggest me how to improve the response time ?
Thanks!
Project Folder Structure
│ client.py
│ main.py
│
├─routers
│ │ v1_router.py
│ │ __init__.py
Data Table
user_ip group
a12345 1, 2
b12345 1, 3
c12345 3
d12345 2
e12345 3, 1, 2
f12345 1
g12345 3
h12345 1
i12345 1
j12345 2
k12345 3
FastAPI
main.py
from fastapi import FastAPI
import uvicorn
from routers import v1_router
app = FastAPI()
app.include_router(v1_router)
if __name__ == "__main__":
uvicorn.run(app="main:app", host="0.0.0.0", port=8000, reload=True)
/routers/v1_router.py
from fastapi import APIRouter
from google.cloud import bigquery
from pydantic import BaseModel
v1_router = APIRouter(
prefix="/v1",
)
client = bigquery.Client()
class User(BaseModel):
ip: str
@v1_router.post("")
async def get_recommend(user: User):
user_ip = user.ip
QUERY = (f"""
SELECT group
FROM dataset.datatable
WHERE user_ip = '{user_ip}'
""")
query_job = client.query(QUERY)
res = query_job.result()
res = res.to_dataframe().to_dict(orient='records')
return res
client.py
import requests
host = "http://localhost:8000/"
url = f"{host}v1/"
user = {"ip": "f12345"}
res = requests.post(url, json=user)
if res.status_code == 200:
print(res.json())
else:
print("Error: ", res.text)