Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 28 additions & 22 deletions .vscode/launch.json
Original file line number Diff line number Diff line change
@@ -1,23 +1,29 @@
{
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"envFile": "${workspaceFolder}/.env",
"env": {
"DATABASE_URI": "${env:DEV_DATABASE_URI}",
},
"args": [
"app.main:app"
],
"jinja": true,
"justMyCode": true
}
]
}
// Use IntelliSense to learn about possible attributes.
// Hover to view descriptions of existing attributes.
// For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387
"version": "0.2.0",
"configurations": [
{
"name": "Python: FastAPI",
"type": "python",
"request": "launch",
"module": "uvicorn",
"envFile": "${workspaceFolder}/.env",
"env": {
"DATABASE_URI": "${env:DEV_DATABASE_URI}"
},
"args": ["app.main:app"],
"jinja": true,
"justMyCode": true
},
{
"name": "Invoke",
"type": "python",
"request": "launch",
"module": "invoke",
"args": ["shell"],
"justMyCode": true
}
]
}
3 changes: 1 addition & 2 deletions app/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,12 @@ class Settings(BaseSettings):
ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
DB_URI: str = ""
DATABASE_URI: str = ""
DEV_DATABASE_URI: str = ""
ADMIN_USER: str = "admin"
ADMIN_PASS: str = "admin"
ADMIN_EMAIL: EmailStr = "admin@admin.com"

class Config:
env_file = ".env", "project.env"
env_file = "project.env", ".env"


@lru_cache
Expand Down
2 changes: 1 addition & 1 deletion app/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@

settings: Settings = get_settings()

DB_URI = settings.DATABASE_URI if settings.DATABASE_URI else settings.DEV_DATABASE_URI
DB_URI = settings.DATABASE_URI if settings.DATABASE_URI else settings.DB_URI

engine = create_engine(DB_URI)

Expand Down
1 change: 1 addition & 0 deletions app/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,6 @@
from .post import Post
from .superuser import SuperUser
from .base_user import BaseUser
from .grocery_item import GroceryItem

from app.database import Base
14 changes: 14 additions & 0 deletions app/model/grocery_item.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from sqlalchemy import Column, Integer, String
from app.database import Base


class GroceryItem(Base):
__tablename__ = "items"

id = Column(Integer, primary_key=True)
name = Column(String(24))
quantity = Column(Integer)
category = Column(String(64), nullable=False)

def __repr__(self) -> str:
return f"<{self.id}: {self.name} ({self.quantity}) {self.category}>"
2 changes: 2 additions & 0 deletions app/router/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,14 @@
from .auth import auth_router
from .post import post_router
from .user import user_router
from .shopping_item import shopping_item_router

router = APIRouter(prefix="/api", tags=["API"])

router.include_router(auth_router)
router.include_router(post_router)
router.include_router(user_router)
router.include_router(shopping_item_router)


@router.get("/list-endpoints/")
Expand Down
55 changes: 55 additions & 0 deletions app/router/shopping_item.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
from fastapi import Depends, APIRouter, status, HTTPException
from sqlalchemy.orm import Session
from sqlalchemy.exc import SQLAlchemyError
from app.logger import log
from app import schema, model
from app.database import get_db


shopping_item_router = APIRouter(prefix="/shopping", tags=["Items"])


@shopping_item_router.get("/items", response_model=schema.ItemsList)
def get_items(
db: Session = Depends(get_db),
):
items = db.query(model.GroceryItem).all()
log(log.INFO, "Grocery items: %s", items)
return schema.ItemsList(items=items)


@shopping_item_router.post(
"/add",
status_code=status.HTTP_201_CREATED,
response_model=schema.GroceryItem,
)
def add_item(item: schema.GroceryItem, db: Session = Depends(get_db)):
new_item = model.GroceryItem(
name=item.name,
quantity=item.quantity,
category=item.category,
)
db.add(new_item)
db.commit()
log(log.INFO, "Item added: %s", new_item)
return new_item


@shopping_item_router.delete(
"/{item_id}",
status_code=status.HTTP_200_OK,
)
def delete_post(
item_id: int,
db: Session = Depends(get_db),
):
item = db.query(model.GroceryItem).filter_by(id=item_id).first()
db.delete(item)
try:
db.commit()
except SQLAlchemyError as e:
log(log.ERROR, "Error while deleting item - %s", e)
raise HTTPException(
status_code=status.HTTP_409_CONFLICT, detail="Error while deleting item"
)
return status.HTTP_200_OK
1 change: 1 addition & 0 deletions app/schema/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@
from .user import BaseUser, User
from .token import Token, TokenData
from .post import Post, BasePost, PostList
from .shopping_item import GroceryItem, ItemsList
14 changes: 14 additions & 0 deletions app/schema/shopping_item.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from pydantic import BaseModel


class GroceryItem(BaseModel):
name: str
quantity: int
category: str

class Config:
orm_mode = True


class ItemsList(BaseModel):
items: list[GroceryItem]
34 changes: 34 additions & 0 deletions migrations/versions/52cdb2557825_message.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""<message>

Revision ID: 52cdb2557825
Revises: 9729f12acebd
Create Date: 2023-05-02 10:50:05.037283

"""
from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision = '52cdb2557825'
down_revision = '9729f12acebd'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('items',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('name', sa.String(length=24), nullable=True),
sa.Column('quantity', sa.Integer(), nullable=True),
sa.Column('category', sa.String(length=64), nullable=False),
sa.PrimaryKeyConstraint('id')
)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('items')
# ### end Alembic commands ###
Loading