consolidate database transactions when creating new thread

This commit is contained in:
agatha 2024-04-05 19:41:57 -04:00
parent b3feb1b7a0
commit e4f0105a6e

View File

@ -36,34 +36,38 @@ async def get_posts(db: db_dependency):
@app.post('/', status_code=status.HTTP_201_CREATED)
async def create_thread(db: db_dependency, data: PostCreate):
# Create the post
post = Post(
author=data.author,
title=data.title,
content=data.content
)
db.add(post)
db.commit()
try:
# Create the post
post = Post(
author=data.author,
title=data.title,
content=data.content
)
db.add(post)
db.flush()
# Create the thread
thread = Thread(
author=post.author,
title=post.title,
content=post.content
)
db.add(thread)
db.commit()
# Create the thread
thread = Thread(
author=post.author,
title=post.title,
content=post.content
)
db.add(thread)
db.flush()
# Update the Post with thread_id
post.thread_id = thread.id
db.commit()
# Update the Post with thread_id
post.thread_id = thread.id
db.commit()
return {
'id': post.id,
'author': post.author,
'title': post.title,
'content': post.content
}
return {
'id': post.id,
'author': post.author,
'title': post.title,
'content': post.content
}
except Exception as e:
db.rollback()
raise HTTPException(status_code=400, detail=str(e))
@app.get('/{thread_id}', status_code=status.HTTP_200_OK)
@ -95,7 +99,7 @@ async def create_reply(db: db_dependency, data: PostCreate, thread_id: int = Pat
'content': post.content
}
raise HTTPException(404, f'Could not find thread')
raise HTTPException(status_code=404, detail='Could not find thread')
@app.get('/catalog', status_code=status.HTTP_200_OK)