-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
252 lines (208 loc) · 7.14 KB
/
main.py
File metadata and controls
252 lines (208 loc) · 7.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
from contextlib import asynccontextmanager
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.exception_handlers import (
http_exception_handler,
request_validation_exception_handler,
)
from fastapi.exceptions import RequestValidationError
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
from sqlalchemy import select, func, text
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from starlette.exceptions import HTTPException as StarletteHTTPException
import models
from database import engine, get_db
from config import settings
from routers import users, posts
@asynccontextmanager
async def lifespan(_app: FastAPI):
yield
# Shutdown
await engine.dispose()
app = FastAPI(lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
templates = Jinja2Templates(directory="templates")
app.include_router(users.router, prefix="/api/users", tags=["users"])
app.include_router(posts.router, prefix="/api/posts", tags=["posts"])
@app.middleware("http")
async def add_security_headers(request: Request, call_next):
response = await call_next(request)
response.headers["X-Frame-Options"] = "SAMEORIGIN"
response.headers["X-Content-Type-Options"] = "nosniff"
if "Referrer-Policy" not in response.headers:
response.headers["Referrer-Policy"] = "strict-origin-when-cross-origin"
if request.url.hostname not in ("localhost", "127.0.0.1"):
response.headers["Strict-Transport-Security"] = (
"max-age=63072000; includeSubDomains"
)
return response
@app.get("/health")
async def health_check(db: Annotated[AsyncSession, Depends(get_db)]):
try:
await db.execute(text("SELECT 1"))
except Exception as e:
raise HTTPException(
status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
detail="Database is not available",
) from e
return {"status": "healthy!"}
@app.get("/", include_in_schema=False, name="home")
@app.get("/posts", include_in_schema=False, name="posts")
async def home(request: Request, db: Annotated[AsyncSession, Depends(get_db)]):
count_result = await db.execute(select(func.count()).select_from(models.Post))
total = count_result.scalar() or 0
result = await db.execute(
select(models.Post)
.options(selectinload(models.Post.author))
.order_by(models.Post.date_posted.desc())
.limit(settings.posts_per_page),
)
posts = result.scalars().all()
has_more = len(posts) < total
return templates.TemplateResponse(
request,
"home.html",
{
"posts": posts,
"title": "Home",
"limit": settings.posts_per_page,
"has_more": has_more,
},
)
@app.get("/posts/{post_id}", include_in_schema=False)
async def post_page(
request: Request,
post_id: int,
db: Annotated[AsyncSession, Depends(get_db)],
):
result = await db.execute(
select(models.Post)
.options(selectinload(models.Post.author))
.where(models.Post.id == post_id),
)
post = result.scalars().first()
if post:
title = post.title[:50]
return templates.TemplateResponse(
request,
"post.html",
{"post": post, "title": title},
)
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Post not found")
@app.get("/users/{user_id}/posts", include_in_schema=False, name="user_posts")
async def user_posts_page(
request: Request,
user_id: int,
db: Annotated[AsyncSession, Depends(get_db)],
):
result = await db.execute(select(models.User).where(models.User.id == user_id))
user = result.scalars().first()
if not user:
raise HTTPException(
status_code=status.HTTP_404_NOT_FOUND,
detail="User not found",
)
count_result = await db.execute(
select(func.count())
.select_from(models.Post)
.where(models.Post.user_id == user_id),
)
total = count_result.scalar() or 0
result = await db.execute(
select(models.Post)
.options(selectinload(models.Post.author))
.where(models.Post.user_id == user_id)
.order_by(models.Post.date_posted.desc())
.limit(settings.posts_per_page),
)
posts = result.scalars().all()
has_more = len(posts) < total
return templates.TemplateResponse(
request,
"user_posts.html",
{
"posts": posts,
"user": user,
"title": f"{user.username}'s Posts",
"limit": settings.posts_per_page,
"has_more": has_more,
},
)
@app.get("/login", include_in_schema=False)
async def login_page(request: Request):
return templates.TemplateResponse(
request,
"login.html",
{"title": "Login"},
)
@app.get("/register", include_in_schema=False)
async def register_page(request: Request):
return templates.TemplateResponse(
request,
"register.html",
{"title": "Register"},
)
@app.get("/account", include_in_schema=False)
async def account_page(request: Request):
return templates.TemplateResponse(
request,
"account.html",
{"title": "Account"},
)
@app.get("/forgot-password", include_in_schema=False)
async def forgot_password_page(request: Request):
return templates.TemplateResponse(
request,
"forgot_password.html",
{"title": "Forgot Password"},
)
@app.get("/reset-password", include_in_schema=False)
async def reset_password_page(request: Request):
response = templates.TemplateResponse(
request,
"reset_password.html",
{"title": "Reset Password"},
)
response.headers["Referrer-Policy"] = "no-referrer"
return response
@app.exception_handler(StarletteHTTPException)
async def general_http_exception_handler(
request: Request,
exception: StarletteHTTPException,
):
if request.url.path.startswith("/api"):
return await http_exception_handler(request, exception)
message = (
exception.detail
if exception.detail
else "An error occurred. Please check your request and try again."
)
return templates.TemplateResponse(
request,
"error.html",
{
"status_code": exception.status_code,
"title": exception.status_code,
"message": message,
},
status_code=exception.status_code,
)
@app.exception_handler(RequestValidationError)
async def validation_exception_handler(
request: Request,
exception: RequestValidationError,
):
if request.url.path.startswith("/api"):
return await request_validation_exception_handler(request, exception)
return templates.TemplateResponse(
request,
"error.html",
{
"status_code": status.HTTP_422_UNPROCESSABLE_CONTENT,
"title": status.HTTP_422_UNPROCESSABLE_CONTENT,
"message": "Invalid request. Please check your input and try again.",
},
status_code=status.HTTP_422_UNPROCESSABLE_CONTENT,
)