List and Read on frontend, fullecrud on back
This commit is contained in:
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -1,7 +1,11 @@
|
||||
from beanie import PydanticObjectId
|
||||
from beanie.odm.enums import SortDirection
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from typing import TypeVar, List, Generic
|
||||
from fastapi_paginate import Page, Params, add_pagination
|
||||
from fastapi_paginate.ext.motor import paginate
|
||||
|
||||
from typing import TypeVar, List, Generic, Any, Dict
|
||||
|
||||
|
||||
T = TypeVar('T')
|
||||
@@ -10,7 +14,21 @@ V = TypeVar('V')
|
||||
W = TypeVar('W')
|
||||
|
||||
|
||||
def parse_sort(sort_by):
|
||||
fields = []
|
||||
for field in sort_by.split(','):
|
||||
dir, col = field.split('(')
|
||||
fields.append((col[:-1], 1 if dir == 'asc' else -1))
|
||||
|
||||
return fields
|
||||
|
||||
|
||||
def parse_query(query) -> Dict[Any, Any]:
|
||||
return {}
|
||||
|
||||
|
||||
def get_crud_router(model, model_create, model_read, model_update):
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@router.post("/", response_description="{} added to the database".format(model.__name__))
|
||||
@@ -22,12 +40,17 @@ def get_crud_router(model, model_create, model_read, model_update):
|
||||
@router.get("/{id}", response_description="{} record retrieved".format(model.__name__))
|
||||
async def read_id(id: PydanticObjectId) -> model_read:
|
||||
item = await model.get(id)
|
||||
return item
|
||||
return model_read(**item.dict())
|
||||
|
||||
@router.get("/", response_description="{} records retrieved".format(model.__name__))
|
||||
async def read_list() -> List[model_read]:
|
||||
item = await model.find_all().to_list()
|
||||
return item
|
||||
@router.get("/", response_model=Page[model_read], response_description="{} records retrieved".format(model.__name__))
|
||||
async def read_list(size: int = 50, page: int = 1, sort_by: str = None, query: str = None) -> Page[model_read]:
|
||||
sort = parse_sort(sort_by)
|
||||
query = parse_query(query)
|
||||
# limit=limit, skip=offset,
|
||||
|
||||
collection = model.get_motor_collection()
|
||||
items = paginate(collection, query, Params(**{'size': size, 'page': page}), sort=sort)
|
||||
return await items
|
||||
|
||||
@router.put("/{id}", response_description="{} record updated".format(model.__name__))
|
||||
async def update(id: PydanticObjectId, req: model_update) -> model_read:
|
||||
@@ -44,7 +67,7 @@ def get_crud_router(model, model_create, model_read, model_update):
|
||||
)
|
||||
|
||||
await item.update(update_query)
|
||||
return item
|
||||
return model_read(**item.dict())
|
||||
|
||||
@router.delete("/{id}", response_description="{} record deleted from the database".format(model.__name__))
|
||||
async def delete(id: PydanticObjectId) -> dict:
|
||||
@@ -61,4 +84,7 @@ def get_crud_router(model, model_create, model_read, model_update):
|
||||
"message": "{} deleted successfully".format(model.__name__)
|
||||
}
|
||||
|
||||
add_pagination(router)
|
||||
return router
|
||||
|
||||
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -18,3 +18,6 @@ class Entity(Document):
|
||||
address: str
|
||||
created_at: datetime = Field(default=datetime.utcnow(), nullable=False)
|
||||
updated_at: datetime = Field(default_factory=datetime.utcnow, nullable=False)
|
||||
#
|
||||
# class Settings:
|
||||
# name = "entities"
|
||||
|
||||
@@ -4,13 +4,14 @@ from datetime import datetime
|
||||
from pydantic import BaseModel
|
||||
|
||||
from .models import Entity, EntityType
|
||||
from ..core.schemas import Writer
|
||||
|
||||
|
||||
class EntityRead(Entity):
|
||||
pass
|
||||
|
||||
|
||||
class EntityCreate(BaseModel):
|
||||
class EntityCreate(Writer):
|
||||
type: EntityType
|
||||
name: str
|
||||
address: str
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi import Depends, Request
|
||||
|
||||
from .contract import contract_router
|
||||
from .db import init_db
|
||||
|
||||
Binary file not shown.
Binary file not shown.
@@ -1,10 +1,14 @@
|
||||
import uuid
|
||||
from typing import Any, Dict, Generic, Optional
|
||||
from bson import ObjectId
|
||||
|
||||
from fastapi import Depends
|
||||
from fastapi_users import BaseUserManager, UUIDIDMixin, models, exceptions, schemas
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, models, exceptions, schemas
|
||||
from fastapi_users.authentication import BearerTransport, AuthenticationBackend
|
||||
from fastapi_users.authentication.strategy.db import AccessTokenDatabase, DatabaseStrategy
|
||||
|
||||
from .models import User, get_user_db, AccessToken, get_access_token_db
|
||||
|
||||
from .models import User, get_user_db
|
||||
SECRET = "SECRET"
|
||||
|
||||
|
||||
@@ -66,6 +70,44 @@ class UserManager(UUIDIDMixin, BaseUserManager[User, uuid.UUID]):
|
||||
|
||||
return created_user
|
||||
|
||||
def parse_id(self, value: Any) -> uuid.UUID:
|
||||
if isinstance(value, ObjectId):
|
||||
return value
|
||||
if isinstance(value, uuid.UUID):
|
||||
return value
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except ValueError as e:
|
||||
raise exceptions.InvalidID() from e
|
||||
|
||||
|
||||
async def get_user_manager(user_db=Depends(get_user_db)):
|
||||
yield UserManager(user_db)
|
||||
yield UserManager(user_db)
|
||||
|
||||
|
||||
def get_database_strategy(
|
||||
access_token_db: AccessTokenDatabase[AccessToken] = Depends(get_access_token_db),
|
||||
) -> DatabaseStrategy:
|
||||
return DatabaseStrategy(access_token_db, lifetime_seconds=3600)
|
||||
|
||||
|
||||
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
||||
|
||||
|
||||
auth_backend = AuthenticationBackend(
|
||||
name="db",
|
||||
transport=bearer_transport,
|
||||
get_strategy=get_database_strategy,
|
||||
)
|
||||
|
||||
|
||||
fastapi_users = FastAPIUsers[User, uuid.UUID](
|
||||
get_user_manager,
|
||||
[auth_backend],
|
||||
)
|
||||
|
||||
get_current_user = fastapi_users.current_user(active=True)
|
||||
|
||||
|
||||
def get_auth_router():
|
||||
return fastapi_users.get_auth_router(auth_backend)
|
||||
|
||||
@@ -1,45 +1,13 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from fastapi import Depends, Request
|
||||
from fastapi_users import BaseUserManager, FastAPIUsers, UUIDIDMixin, models, exceptions
|
||||
from fastapi_users.authentication import BearerTransport, AuthenticationBackend
|
||||
from fastapi_users.authentication.strategy.db import AccessTokenDatabase, DatabaseStrategy
|
||||
from fastapi import Depends
|
||||
|
||||
from beanie import PydanticObjectId
|
||||
|
||||
from fastapi import APIRouter, HTTPException
|
||||
from typing import List
|
||||
|
||||
from .models import User, AccessToken, get_user_db, get_access_token_db
|
||||
from .models import User
|
||||
from .schemas import UserRead, UserUpdate, UserCreate
|
||||
from .manager import get_user_manager
|
||||
|
||||
|
||||
def get_database_strategy(
|
||||
access_token_db: AccessTokenDatabase[AccessToken] = Depends(get_access_token_db),
|
||||
) -> DatabaseStrategy:
|
||||
return DatabaseStrategy(access_token_db, lifetime_seconds=3600)
|
||||
|
||||
|
||||
bearer_transport = BearerTransport(tokenUrl="auth/jwt/login")
|
||||
|
||||
|
||||
auth_backend = AuthenticationBackend(
|
||||
name="db",
|
||||
transport=bearer_transport,
|
||||
get_strategy=get_database_strategy,
|
||||
)
|
||||
|
||||
|
||||
fastapi_users = FastAPIUsers[User, uuid.UUID](
|
||||
get_user_manager,
|
||||
[auth_backend],
|
||||
)
|
||||
|
||||
|
||||
def get_auth_router():
|
||||
return fastapi_users.get_auth_router(auth_backend)
|
||||
from .manager import get_user_manager, get_current_user, get_auth_router
|
||||
|
||||
|
||||
router = APIRouter()
|
||||
@@ -51,10 +19,16 @@ async def create(user: UserCreate, user_manager=Depends(get_user_manager)) -> di
|
||||
return {"message": "User added successfully"}
|
||||
|
||||
|
||||
@router.get("/me", response_description="User record retrieved")
|
||||
async def read_me(user=Depends(get_current_user)) -> UserRead:
|
||||
user = await User.get(user.id)
|
||||
return UserRead(**user.dict())
|
||||
|
||||
|
||||
@router.get("/{id}", response_description="User record retrieved")
|
||||
async def read_id(id: PydanticObjectId) -> UserRead:
|
||||
user = await User.get(id)
|
||||
return user
|
||||
return UserRead(**user.dict())
|
||||
|
||||
|
||||
@router.get("/", response_model=List[UserRead], response_description="User records retrieved")
|
||||
|
||||
Reference in New Issue
Block a user