Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
84 lines (66 loc) · 2.06 KB
/
Copy pathmain.py
File metadata and controls
84 lines (66 loc) · 2.06 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
from fastapi import FastAPI, Depends, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from models import Base, User, Post
from pydantic import BaseModel
from dotenv import load_dotenv
import os
load_dotenv()
DATABASE_URL = os.getenv("DATABASE_URL")
engine = create_engine(DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base.metadata.create_all(bind=engine)
app = FastAPI()
# Dependency
def get_db():
db = SessionLocal()
try:
yield db
finally:
db.close()
class UserCreate(BaseModel):
username: str
email: str
password: str
class PostCreate(BaseModel):
title: str
content: str
user_id: int
class PostRead(BaseModel):
id: int
title: str
content: str
user_id: int
username: str
@app.post("/users/")
def create_user(user: UserCreate, db: Session = Depends(get_db)):
db_user = User(**user.model_dump())
db.add(db_user)
db.commit()
db.refresh(db_user)
return db_user
@app.post("/posts/")
def create_post(post: PostCreate, db: Session = Depends(get_db)):
try:
# Sprawdzam czy user_id istnieje
db_user = db.query(User).filter(User.id == post.user_id).first()
if db_user is None:
raise HTTPException(status_code=404, detail="User not found")
# Tworzę posta po walidacji
db_post = Post(**post.model_dump())
db.add(db_post)
db.commit()
db.refresh(db_post)
return db_post
except:
db.rollback() # Cofanie w przypadku błędu
raise
@app.get("/posts/", response_model=list[PostRead])
def read_posts(skip: int = 0, limit: int = 10, db: Session = Depends(get_db)):
posts = db.query(Post).offset(skip).limit(limit).all()
results = []
for post in posts:
user = db.query(User).filter(User.id == post.user_id).first()
results.append(PostRead(id=post.id, title=post.title, content=post.content, user_id=user.id, username=user.username))
return results