forum-app/backend/forum.py

104 lines
1.8 KiB
Python
Raw Normal View History

from fastapi import FastAPI
from pydantic import BaseModel
app = FastAPI()
class Post:
id: int
2024-04-01 03:27:57 +00:00
thread_id: int
title: str
content: str
2024-04-01 03:27:57 +00:00
def __init__(self, id, thread_id, title, content):
self.id = id
2024-04-01 03:27:57 +00:00
self.thread_id = thread_id
self.title = title
self.content = content
class PostCreate(BaseModel):
title: str
content: str
2024-04-01 02:55:50 +00:00
class Thread:
id: int
title: str
2024-04-01 03:09:22 +00:00
closed: bool
2024-04-01 02:55:50 +00:00
2024-04-01 03:09:22 +00:00
def __init__(self, id, title, closed=False):
2024-04-01 02:55:50 +00:00
self.id = id
self.title = title
2024-04-01 03:09:22 +00:00
self.closed = closed
2024-04-01 02:55:50 +00:00
2024-04-01 02:25:10 +00:00
POSTS = []
2024-04-01 03:09:22 +00:00
THREADS = []
@app.get("/")
2024-04-01 03:27:57 +00:00
async def get_threads():
return THREADS
@app.post("/post")
async def create_post(data: PostCreate):
2024-04-01 03:27:57 +00:00
id = len(POSTS) + 1
title = data.title
content = data.content
# Create thread
thread = Thread(
id=id,
title=title
)
THREADS.append(thread)
# Create post
post = Post(
2024-04-01 03:27:57 +00:00
id=id,
thread_id=id,
title=title,
content=content
)
POSTS.append(post)
2024-04-01 03:27:57 +00:00
return post
2024-04-01 03:27:57 +00:00
@app.get("/{thread_id}")
async def get_thread(thread_id: int):
result = []
for post in POSTS:
2024-04-01 03:27:57 +00:00
if post.thread_id == thread_id:
result.append(post)
return result
@app.post("/{thread_id}/post")
2024-04-01 03:29:23 +00:00
async def reply_to_post(thread_id: int, data: PostCreate):
2024-04-01 03:27:57 +00:00
parent = None
for thread in THREADS:
if thread.id == thread_id:
parent = thread
if parent:
id = len(POSTS) + 1
title = data.title
content = data.content
# Create post
post = Post(
id=id,
thread_id=parent.id,
title=title,
content=content
)
POSTS.append(post)
return post
2024-04-01 03:27:57 +00:00
return {'error': 'could not find parent thread'}