Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
174 lines (147 loc) · 5.39 KB
/
Copy pathmain.py
File metadata and controls
174 lines (147 loc) · 5.39 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
# FastAPI Blog Application with Authorization
# Main application file with JWT-based authentication and authorization implementation
# Features: User authentication, protected endpoints, role-based access control, session management
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
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.orm import selectinload
from starlette.exceptions import HTTPException as StarletteHTTPException
import python_tutorial.fastapi_tutorial.fastapi_blog_lec10.models as models
from python_tutorial.fastapi_tutorial.fastapi_blog_lec10.database import Base, engine, get_db
from python_tutorial.fastapi_tutorial.fastapi_blog_lec10.routers import posts
from python_tutorial.fastapi_tutorial.fastapi_blog_lec10.routers import users
@asynccontextmanager
async def lifespan(_app: FastAPI):
# Startup
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)
yield
# Shutdown
await engine.dispose()
app = FastAPI(lifespan=lifespan)
app.mount("/static", StaticFiles(directory="static"), name="static")
app.mount("/media", StaticFiles(directory="media"), name="media")
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.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)]):
result = await db.execute(
select(models.Post)
.options(selectinload(models.Post.author))
.order_by(models.Post.date_posted.desc()),
)
posts = result.scalars().all()
return templates.TemplateResponse(
request,
"home.html",
{"posts": posts, "title": "Home"},
)
@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",
)
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()),
)
posts = result.scalars().all()
return templates.TemplateResponse(
request,
"user_posts.html",
{"posts": posts, "user": user, "title": f"{user.username}'s Posts"},
)
@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.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,
)