redis added in main.py
This commit is contained in:
68
main.py
68
main.py
@ -7,10 +7,43 @@ from db import get_session, engine, Base
|
|||||||
from models import WeatherRecord
|
from models import WeatherRecord
|
||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
from fastapi.responses import HTMLResponse, JSONResponse
|
from fastapi.responses import HTMLResponse, JSONResponse
|
||||||
|
#from tenacity import retry, stop_after_attempt, wait_fixed #DODANE
|
||||||
|
import asyncio
|
||||||
|
import asyncpg
|
||||||
|
import redis
|
||||||
|
import json
|
||||||
|
|
||||||
|
redis_client = redis.StrictRedis(host='localhost', port=6379, db=0, decode_responses=True)
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
templates = Jinja2Templates(directory="templates")
|
templates = Jinja2Templates(directory="templates")
|
||||||
|
|
||||||
|
@app.middleware("http")
|
||||||
|
async def log_user_action(request: Request, call_next):
|
||||||
|
method = request.method
|
||||||
|
path = request.url.path
|
||||||
|
query = dict(request.query_params)
|
||||||
|
timestamp = datetime.utcnow().isoformat()
|
||||||
|
|
||||||
|
action = {
|
||||||
|
"method": method,
|
||||||
|
"path": path,
|
||||||
|
"query": query,
|
||||||
|
"timestamp": timestamp
|
||||||
|
}
|
||||||
|
|
||||||
|
# Zapisujemy jako JSON w liście w Redis
|
||||||
|
redis_client.rpush("user_actions", json.dumps(action))
|
||||||
|
|
||||||
|
response = await call_next(request)
|
||||||
|
return response
|
||||||
|
|
||||||
|
@app.get("/logs")
|
||||||
|
def get_logs():
|
||||||
|
entries = redis_client.lrange("user_actions", 0, -1)
|
||||||
|
return [json.loads(e) for e in entries]
|
||||||
|
|
||||||
|
|
||||||
CITIES = {
|
CITIES = {
|
||||||
"warszawa": (52.23, 21.01),
|
"warszawa": (52.23, 21.01),
|
||||||
"krakow": (50.06, 19.94),
|
"krakow": (50.06, 19.94),
|
||||||
@ -82,11 +115,27 @@ CITIES = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
'''
|
||||||
@app.on_event("startup")
|
@app.on_event("startup")
|
||||||
async def startup():
|
async def startup():
|
||||||
async with engine.begin() as conn:
|
async with engine.begin() as conn:
|
||||||
await conn.run_sync(Base.metadata.create_all)
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
'''
|
||||||
|
|
||||||
|
@app.on_event("startup")
|
||||||
|
async def startup():
|
||||||
|
for attempt in range(50):
|
||||||
|
try:
|
||||||
|
async with engine.begin() as conn:
|
||||||
|
await conn.run_sync(Base.metadata.create_all)
|
||||||
|
print("Połączono z bazą danych.")
|
||||||
|
break
|
||||||
|
except asyncpg.InvalidPasswordError:
|
||||||
|
print("Nieprawidłowe hasło.")
|
||||||
|
#raise
|
||||||
|
except Exception as e:
|
||||||
|
#print(f"Próba {attempt+1}/10 nieudana: {e}")
|
||||||
|
await asyncio.sleep(2)
|
||||||
|
|
||||||
@app.get("/weather")
|
@app.get("/weather")
|
||||||
async def get_weather(city: str = Query("warszawa"), session: AsyncSession = Depends(get_session)):
|
async def get_weather(city: str = Query("warszawa"), session: AsyncSession = Depends(get_session)):
|
||||||
@ -94,7 +143,7 @@ async def get_weather(city: str = Query("warszawa"), session: AsyncSession = Dep
|
|||||||
if not coords:
|
if not coords:
|
||||||
return {"error": "Miasto nieobsługiwane"}
|
return {"error": "Miasto nieobsługiwane"}
|
||||||
|
|
||||||
url = f"https://api.open-meteo.com/v1/forecast?latitude={coords[0]}&longitude={coords[1]}¤t_weather=true"
|
url = f"http://api.open-meteo.com/v1/forecast?latitude={coords[0]}&longitude={coords[1]}¤t_weather=true"
|
||||||
|
|
||||||
async with httpx.AsyncClient() as client:
|
async with httpx.AsyncClient() as client:
|
||||||
res = await client.get(url)
|
res = await client.get(url)
|
||||||
@ -159,7 +208,7 @@ async def get_weather_by_coords(
|
|||||||
session: AsyncSession = Depends(get_session)
|
session: AsyncSession = Depends(get_session)
|
||||||
):
|
):
|
||||||
url = (
|
url = (
|
||||||
f"https://api.open-meteo.com/v1/forecast?"
|
f"http://api.open-meteo.com/v1/forecast?"
|
||||||
f"latitude={latitude}&longitude={longitude}¤t_weather=true"
|
f"latitude={latitude}&longitude={longitude}¤t_weather=true"
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -209,7 +258,7 @@ async def get_forecast(
|
|||||||
)
|
)
|
||||||
|
|
||||||
url = (
|
url = (
|
||||||
f"https://api.open-meteo.com/v1/forecast?"
|
f"http://api.open-meteo.com/v1/forecast?"
|
||||||
f"latitude={coords[0]}&longitude={coords[1]}"
|
f"latitude={coords[0]}&longitude={coords[1]}"
|
||||||
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
||||||
f"&timezone=Europe/Warsaw"
|
f"&timezone=Europe/Warsaw"
|
||||||
@ -248,7 +297,7 @@ async def get_forecast_geo(
|
|||||||
days: int = Query(3, ge=1, le=16)
|
days: int = Query(3, ge=1, le=16)
|
||||||
):
|
):
|
||||||
url = (
|
url = (
|
||||||
f"https://api.open-meteo.com/v1/forecast?"
|
f"http://api.open-meteo.com/v1/forecast?"
|
||||||
f"latitude={latitude}&longitude={longitude}"
|
f"latitude={latitude}&longitude={longitude}"
|
||||||
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
||||||
f"&timezone=Europe/Warsaw"
|
f"&timezone=Europe/Warsaw"
|
||||||
@ -288,7 +337,7 @@ async def get_hourly_forecast_geo(
|
|||||||
hours: int = Query(12, ge=1, le=48)
|
hours: int = Query(12, ge=1, le=48)
|
||||||
):
|
):
|
||||||
url = (
|
url = (
|
||||||
f"https://api.open-meteo.com/v1/forecast?"
|
f"http://api.open-meteo.com/v1/forecast?"
|
||||||
f"latitude={latitude}&longitude={longitude}"
|
f"latitude={latitude}&longitude={longitude}"
|
||||||
f"&hourly=temperature_2m,windspeed_10m,precipitation"
|
f"&hourly=temperature_2m,windspeed_10m,precipitation"
|
||||||
f"&timezone=Europe/Warsaw"
|
f"&timezone=Europe/Warsaw"
|
||||||
@ -345,7 +394,7 @@ async def get_hourly_forecast_city(
|
|||||||
latitude, longitude = coords
|
latitude, longitude = coords
|
||||||
|
|
||||||
url = (
|
url = (
|
||||||
f"https://api.open-meteo.com/v1/forecast?"
|
f"http://api.open-meteo.com/v1/forecast?"
|
||||||
f"latitude={latitude}&longitude={longitude}"
|
f"latitude={latitude}&longitude={longitude}"
|
||||||
f"&hourly=temperature_2m,windspeed_10m,precipitation"
|
f"&hourly=temperature_2m,windspeed_10m,precipitation"
|
||||||
f"&timezone=Europe/Warsaw"
|
f"&timezone=Europe/Warsaw"
|
||||||
@ -405,7 +454,7 @@ async def get_weather_history_range(
|
|||||||
latitude, longitude = coords
|
latitude, longitude = coords
|
||||||
|
|
||||||
url = (
|
url = (
|
||||||
f"https://archive-api.open-meteo.com/v1/archive?"
|
f"http://archive-api.open-meteo.com/v1/archive?"
|
||||||
f"latitude={latitude}&longitude={longitude}"
|
f"latitude={latitude}&longitude={longitude}"
|
||||||
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
||||||
f"&start_date={start_date}&end_date={end_date}"
|
f"&start_date={start_date}&end_date={end_date}"
|
||||||
@ -448,7 +497,7 @@ async def get_weather_history_range_geo(
|
|||||||
end_date: str = Query(..., description="Końcowa data w formacie YYYY-MM-DD")
|
end_date: str = Query(..., description="Końcowa data w formacie YYYY-MM-DD")
|
||||||
):
|
):
|
||||||
url = (
|
url = (
|
||||||
f"https://archive-api.open-meteo.com/v1/archive?"
|
f"http://archive-api.open-meteo.com/v1/archive?"
|
||||||
f"latitude={latitude}&longitude={longitude}"
|
f"latitude={latitude}&longitude={longitude}"
|
||||||
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
f"&daily=temperature_2m_max,temperature_2m_min,precipitation_sum"
|
||||||
f"&start_date={start_date}&end_date={end_date}"
|
f"&start_date={start_date}&end_date={end_date}"
|
||||||
@ -485,3 +534,4 @@ async def get_weather_history_range_geo(
|
|||||||
"history": daily
|
"history": daily
|
||||||
})
|
})
|
||||||
|
|
||||||
|
|
||||||
|
@ -4,3 +4,6 @@ sqlalchemy
|
|||||||
asyncpg
|
asyncpg
|
||||||
jinja2
|
jinja2
|
||||||
uvicorn
|
uvicorn
|
||||||
|
redis[asyncio]
|
||||||
|
python-multipart
|
||||||
|
aioredis
|
||||||
|
Reference in New Issue
Block a user