Skip to content

Commit

Permalink
Added PATCH method for tweets
Browse files Browse the repository at this point in the history
* Added relationship in DB between user and tweet
* Check if the data is null before checking the database if the row
  exists
  • Loading branch information
rabinadk1 committed Jan 22, 2022
1 parent 9ceb67a commit 2263c53
Show file tree
Hide file tree
Showing 5 changed files with 97 additions and 23 deletions.
10 changes: 8 additions & 2 deletions server/app/auth/models.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Optional
from typing import List, Optional

from pydantic import BaseModel, EmailStr, PositiveInt, constr
from sqlmodel import Field, SQLModel
from sqlmodel import Field, Relationship, SQLModel

# Data Models

Expand Down Expand Up @@ -57,5 +57,11 @@ class UserUpdate(SQLModel):


class User(UserBase, table=True):

id: Optional[PositiveInt] = Field(default=None, primary_key=True)
hashed_password: str

tweets: List["Tweet"] = Relationship(back_populates="modifier")


# from app.tweets.models import Tweet
4 changes: 2 additions & 2 deletions server/app/auth/routes.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
response_model=UserRead,
responses={401: {"description": "Authentication Error"}},
)
async def get_users_me(current_user: UserRead = Depends(get_current_user)):
async def get_users_me(current_user: User = Depends(get_current_user)):
"""
Get current user
"""
Expand Down Expand Up @@ -90,7 +90,7 @@ def update(
Update current user
"""

# Exclude the ones not sent by client
# Exclude the nones
user_dict = user.dict(exclude_none=True)

if len(user_dict) == 0:
Expand Down
14 changes: 10 additions & 4 deletions server/app/heroes/routes.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from typing import List

from fastapi import Depends
from fastapi import Depends, HTTPException
from pydantic import NonNegativeInt, PositiveInt, conint
from sqlmodel import Session, select

Expand Down Expand Up @@ -49,19 +49,25 @@ def read_hero(hero_id: PositiveInt, session: Session = Depends(get_session)):
@router.patch(
"/{hero_id}",
response_model=HeroRead,
responses={404: {"description": "Hero Not found"}},
responses={
404: {"description": "Hero Not found"},
400: {"description": "No Valid Data to Update"},
},
)
def update_hero(
hero_id: PositiveInt, hero: HeroUpdate, session: Session = Depends(get_session)
):
"""
Update a hero by id.
"""
db_hero = get_or_404(session, Hero, hero_id)

# Exclude the ones not sent by the client
hero_data = hero.dict(exclude_unset=True)

if len(hero_data) == 0:
raise HTTPException(status_code=400, detail="No Valid Data to Update")

db_hero = get_or_404(session, Hero, hero_id)

for key, value in hero_data.items():
setattr(db_hero, key, value)

Expand Down
47 changes: 35 additions & 12 deletions server/app/tweets/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,42 @@
from typing import Optional

from pydantic import PositiveInt
from sqlmodel import Field, SQLModel
from sqlmodel import Field, Relationship, SQLModel

from app.auth.models import User

# Data Models


class Overview(SQLModel):
covid_stats: int
vaccination: int
covid_politics: int
humour: int
lockdown: int
civic_views: int
life_during_pandemic: int
covid_waves_and_variants: int
misinformation: int
created_at: date


class TweetUpdate(SQLModel):
text: Optional[str] = None
covid_stats: Optional[bool] = None
vaccination: Optional[bool] = None
covid_politics: Optional[bool] = None
humour: Optional[bool] = None
lockdown: Optional[bool] = None
civic_views: Optional[bool] = None
life_during_pandemic: Optional[bool] = None
covid_waves_and_variants: Optional[bool] = None
misinformation: Optional[bool] = None


# Table Models


class Tweet(SQLModel, table=True):
id: Optional[PositiveInt] = Field(default=None, primary_key=True)
text: str
Expand All @@ -22,15 +53,7 @@ class Tweet(SQLModel, table=True):
covid_waves_and_variants: bool
misinformation: bool

modifier_id: Optional[PositiveInt] = Field(default=None, foreign_key="user.id")
modifier: Optional[User] = Relationship(back_populates="tweets")

class Overview(SQLModel):
covid_stats: int
vaccination: int
covid_politics: int
humour: int
lockdown: int
civic_views: int
life_during_pandemic: int
covid_waves_and_variants: int
misinformation: int
created_at: date
modified_at: Optional[datetime] = Field(default=None)
45 changes: 42 additions & 3 deletions server/app/tweets/routes.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
from datetime import datetime, timezone
from typing import List

from fastapi import Depends
from fastapi import Depends, HTTPException
from pydantic import NonNegativeInt, PositiveInt, conint
from sqlmodel import Integer, Session, cast, func, select

from app.database import get_or_404, get_session
from app.auth.helper_functions import get_current_user
from app.auth.models import User
from app.database import get_or_404, get_session, save_and_refresh

from . import router
from .models import Overview, Tweet
from .models import Overview, Tweet, TweetUpdate


@router.get("/overview", response_model=List[Overview])
Expand Down Expand Up @@ -60,3 +63,39 @@ def read_tweet(tweet_id: PositiveInt, session: Session = Depends(get_session)):
"""
tweet = get_or_404(session, Tweet, tweet_id)
return tweet


@router.patch(
"/{tweet_id}",
response_model=Tweet,
responses={
404: {"description": "Tweet Not found"},
400: {"description": "No Valid Data to Update"},
},
)
def update_tweet(
tweet_id: PositiveInt,
tweet: TweetUpdate,
db_user: User = Depends(get_current_user),
session: Session = Depends(get_session),
):
"""
Update a tweet by id.
"""

# Exclude the nones
tweet_data = tweet.dict(exclude_none=True)

if len(tweet_data) == 0:
raise HTTPException(status_code=400, detail="No Valid Data to Update")

db_tweet = get_or_404(session, Tweet, tweet_id)

for key, value in tweet_data.items():
setattr(db_tweet, key, value)

db_tweet.modified_at = datetime.now(timezone.utc)
db_tweet.modifier = db_user

save_and_refresh(session, db_tweet)
return db_tweet

0 comments on commit 2263c53

Please sign in to comment.