Files
papi-py/posts.py
stephen schuresko e59924b1fe
Some checks failed
Build and Push to Private Registry101 / build (push) Failing after 6s
Build and Push to Private Registry101 / deploy (push) Has been skipped
feat: enhance deployment and installation process in build-and-push workflow
2025-03-07 14:13:09 -05:00

53 lines
1.5 KiB
Python

from fastapi import APIRouter, Depends
from sqlalchemy.orm import sessionmaker, Session, declarative_base
from sqlalchemy import create_engine, Column, Integer,String, ForeignKey
import db
class Post(db.Base):
__tablename__ = "posts"
id = Column(Integer, primary_key=True, index=True)
title = Column(String)
content = Column(String)
author_id = Column(Integer, ForeignKey("users.id"),index=True)
router = APIRouter(prefix="/posts")
@router.get("")
def get_users(db: Session = Depends(db.get_db)):
return db.query(Post).all()
@router.get("/{id}")
def get_user( id, db: Session = Depends(db.get_db)):
db_post = db.query(Post).filter(Post.id == id).first()
return db_post
@router.post("")
def create_post( post: dict, db: Session = Depends(db.get_db)):
db_post = Post(**post)
db.add(db_post)
db.commit()
db.refresh(db_post)
return {"message":"Post created successfully","post":db_post}
@router.put("/{id}")
def update_post( id, post: dict, db: Session = Depends(db.get_db)):
db_post = db.query(Post).filter(Post.id == id).first()
if "title" in post:
db_post.title = post["title"]
if "content" in post:
db_post.content = post["content"]
db.commit()
db.refresh(db_post)
return {"message":"Post updated successfully","post":db_post}
@router.delete("/{id}")
def delete_post(id, db: Session = Depends(db.get_db)):
db_post = db.query(Post).filter(Post.id == id).first()
db.delete(db_post)
db.commit()
return {"message":"Post deleted successfully","post":db_post}