1

I have set this FastApi server:

from fastapi import FastAPI, Request
from fastapi.responses import HTMLResponse
from fastapi.templating import Jinja2Templates
from fastapi.staticfiles import StaticFiles
from pathlib import Path
import requests
import mysql.connector as mariadb
from database import connection_properties as conn

mariadb_connection = mariadb.connect(user=conn.USER,
                                    password=conn.PASSWORD,
                                    host=conn.HOST,
                                    database=conn.DATABASE,
                                    auth_plugin='mysql_native_password')
cursor = mariadb_connection.cursor()

app = FastAPI()

templates = Jinja2Templates(directory="htmlPages")

app.mount(
    "/htmlPages/static",
    StaticFiles(directory=Path(__file__).parent.absolute() / "htmlPages" / "static"),
    name="static",
)

@app.get("/county")
async def get_regions():
    cursor.execute("SELECT name FROM county")
    regions = cursor.fetchall()
    return {"regions": regions}


@app.get("/")
async def home_page(req: Request):
    return templates.TemplateResponse("homePage.html", {"request": req})

@app.get("/predictions", response_class=HTMLResponse)
async def predictions(request: Request):
    response = requests.get("http://localhost:8000/county")
    regions = response.json()["regions"]
    return templates.TemplateResponse("predictions.html", {"request": request, "regions": regions})

The proble is that everytime I make a request at http://localhost:8000/predictions , the page seems like loading forever and I do not get anything. When I make a request at http://localhost:8000/county I receive the data that I want from the database. What is wrong?

mariniou77
  • 27
  • 5
  • 1
    When you do `response = requests.get("http://localhost:8000/county")` - your server is busy handling the previous request. If you want to use async, you'll have to use a async compatible library for handling the http requests (such as `aiohttp` and `await` the call. Secondly, having a global cursor in your application isn't a good idea - it should be created for each session instead (at least). I'd also recommend refactoring the part you need under `/county` to a separate function instead; calling other internal endpoints is usually a waste of resources. – MatsLindh Feb 20 '23 at 10:32
  • First of all thank you for your reply! May you give me an example of what you mean? – mariniou77 Feb 20 '23 at 10:36
  • 1
    For which of my suggestions? Generally, moving the county part out to a separate function instead of an endpoint would be `def counties(): cursor = cursor = mariadb_connection.cursor(), cursor.execute(..) return cursor.fetchall()` - then use this function both in `/counties` (I prefer naming endpoints plural as you did with `/predictions`) and in `/predictions` instead of making a http request. – MatsLindh Feb 20 '23 at 10:42

0 Answers0