80 lines
2.1 KiB
Python
80 lines
2.1 KiB
Python
import uvicorn
|
|
# import pathlib
|
|
import datetime
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, Request, HTTPException
|
|
from fastapi.responses import HTMLResponse, JSONResponse
|
|
from fastapi.staticfiles import StaticFiles
|
|
from fastapi.templating import Jinja2Templates
|
|
|
|
from .database import create_tables, delete_tables
|
|
from .router import router as datings_router
|
|
from .validity import is_valid_uuid
|
|
|
|
|
|
from pydantic_settings import BaseSettings, SettingsConfigDict
|
|
|
|
|
|
class Settings(BaseSettings):
|
|
OPENAPI_URL: str = "/openapi.json"
|
|
|
|
model_config = SettingsConfigDict(
|
|
env_file=(".env", ".env.local", ".env.prod"),
|
|
env_file_encoding="utf-8",
|
|
case_sensitive=True
|
|
)
|
|
|
|
|
|
settings = Settings()
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
await create_tables()
|
|
print("База готова")
|
|
yield
|
|
# await delete_tables()
|
|
# print("База очищена")
|
|
pass
|
|
|
|
|
|
app = FastAPI(
|
|
lifespan=lifespan, docs_url=None, redoc_url=None, openapi_url=settings.OPENAPI_URL
|
|
)
|
|
|
|
templates = Jinja2Templates(directory="templates")
|
|
|
|
app.include_router(datings_router)
|
|
|
|
app.mount("/static", StaticFiles(directory="static"), name="static")
|
|
|
|
|
|
@app.get("/", response_class=HTMLResponse)
|
|
async def index(request: Request):
|
|
response = templates.TemplateResponse("index.html", {"request": request})
|
|
sessionKey = request.cookies.get("sessionkey")
|
|
if isinstance(sessionKey, str) and is_valid_uuid(sessionKey):
|
|
pass
|
|
else:
|
|
days = 365
|
|
expires_t_obj = datetime.datetime.now(datetime.timezone.utc) + datetime.timedelta(
|
|
days=days
|
|
)
|
|
expires_t_str = expires_t_obj.strftime("%a, %d %b %Y %H:%M:%S GMT")
|
|
|
|
response.set_cookie(
|
|
key="sessionkey", value=str(uuid.uuid4()), expires=expires_t_str
|
|
)
|
|
return response
|
|
|
|
|
|
@app.exception_handler(HTTPException)
|
|
async def http_exception_handler(request, exc):
|
|
return JSONResponse(status_code=exc.status_code, content={"detail": exc.detail})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
uvicorn.run(app, host="127.0.0.1", port=8001)
|