-
First Check
Commit to Help
Example Codefrom json import loads
from uvicorn import run
from psycopg2 import connect, Error
from redis import Redis, RedisError
from urllib.request import urlopen
from fastapi import FastAPI
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
app = FastAPI()
app.mount("/static", StaticFiles(directory="./static"), name="static")
url = "http://worldtimeapi.org/api/ip"
try:
r = Redis(
host='localhost',
port=6379)
except (Exception, RedisError) as error:
print("Error while connecting to redis", error)
try:
connection = connect(user="filip", password="1234", host="172.17.0.3", port=5432, database="db")
cursor = connection.cursor()
except (Exception, Error) as error:
print("Error while connecting to PostgreSQL", error)
def time_api():
response = urlopen(url).read()
data = loads(response)
return data["datetime"]
@app.get("/time")
def time_operations():
time = r.get('TIME')
if time == None:
time = time_api()
r.set("TIME", time)
r.expire("TIME", 30)
cursor.execute("SELECT version();")
insert_query = """ INSERT INTO time (current) VALUES ('{}')""".format(time)
cursor.execute(insert_query)
connection.commit()
return time
@app.get("/", response_class=HTMLResponse)
def root():
return """
random html
"""
if __name__ == "__main__":
run(app, host="0.0.0.0", port=8080)DescriptionI am trying to run my fastapi app in docker. Operating SystemLinux Operating System DetailsNo response FastAPI Version0.79.0 Python Version3.9.2 Additional ContextThis is a complete log after doing docker compose: This is my compose: Dockerfile: |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
|
The issue was that ip provided for Postgre connection was wrong as the port 5432 was mapped to localhost, the reason why the app took so long is because postgre was trying to establish connection. |
Beta Was this translation helpful? Give feedback.
The issue was that ip provided for Postgre connection was wrong as the port 5432 was mapped to localhost, the reason why the app took so long is because postgre was trying to establish connection.