forum-app/backend/forum.py

112 lines
2.0 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
author: str
title: str
content: str
def __init__(self, id, thread_id, author, title, content):
self.id = id
2024-04-01 03:27:57 +00:00
self.thread_id = thread_id
self.author = author
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
author: str
2024-04-01 02:55:50 +00:00
title: str
2024-04-01 03:09:22 +00:00
closed: bool
2024-04-01 02:55:50 +00:00
def __init__(self, id, author, title, closed=False):
2024-04-01 02:55:50 +00:00
self.id = id
self.author = author
2024-04-01 02:55:50 +00:00
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
author = 'anon'
2024-04-01 03:27:57 +00:00
title = data.title
content = data.content
# Create thread
thread = Thread(
id=id,
author=author,
2024-04-01 03:27:57 +00:00
title=title
)
THREADS.append(thread)
# Create post
post = Post(
2024-04-01 03:27:57 +00:00
id=id,
thread_id=id,
author=author,
2024-04-01 03:27:57 +00:00
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,
author='anon',
2024-04-01 03:27:57 +00:00
title=title,
content=content
)
POSTS.append(post)
return post
2024-04-01 03:27:57 +00:00
return {'error': 'could not find parent thread'}