Importing RJSF lib with first application

This commit is contained in:
2025-04-07 22:54:05 +02:00
parent f93a59b27e
commit 661841ceef
19 changed files with 662 additions and 24 deletions

View File

@@ -1,19 +1,19 @@
import os
from datetime import datetime
from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
from beanie import Document, PydanticObjectId
from pydantic import Field, computed_field
from hub.user import User
from hub.auth import AccessToken
MONGO_USERNAME = os.getenv("MONGO_INITDB_ROOT_USERNAME")
MONGO_PASSWORD = os.getenv("MONGO_INITDB_ROOT_PASSWORD")
class CrudDocument(Document):
_id: str
created_at: datetime = Field(default=datetime.utcnow(), nullable=False, title="Créé le")
created_by: PydanticObjectId = Field()
updated_at: datetime = Field(default_factory=datetime.utcnow, nullable=False, title="Modifié le")
updated_by: PydanticObjectId = Field()
DATABASE_URL = f"mongodb://{MONGO_USERNAME}:{MONGO_PASSWORD}@mongo:27017"
@computed_field
def label(self) -> str:
return self.compute_label()
async def init_db():
client = AsyncIOMotorClient(DATABASE_URL, uuidRepresentation="standard")
await init_beanie(database=client.hub,
document_models=[User, AccessToken],
allow_index_dropping=True)
def compute_label(self) -> str:
return ""

View File

@@ -90,3 +90,6 @@ cookie_transport = CookieTransportOauth(cookie_name="rpkapiusersauth")
auth_backend = AuthenticationBackend(name="db", transport=cookie_transport, get_strategy=get_database_strategy, )
google_oauth_router = fastapi_users.get_oauth_router(google_oauth_client, auth_backend, SECRET, is_verified_by_default=True)
discord_oauth_router = fastapi_users.get_oauth_router(discord_oauth_client, auth_backend, SECRET, is_verified_by_default=True)
get_current_user = fastapi_users.current_user(active=True)
get_current_superuser = fastapi_users.current_user(active=True, superuser=True)

21
api/rpk-api/hub/db.py Normal file
View File

@@ -0,0 +1,21 @@
import os
from beanie import init_beanie
from motor.motor_asyncio import AsyncIOMotorClient
from hub.user import User
from hub.auth import AccessToken
from hub.firm import Firm
MONGO_USERNAME = os.getenv("MONGO_INITDB_ROOT_USERNAME")
MONGO_PASSWORD = os.getenv("MONGO_INITDB_ROOT_PASSWORD")
DATABASE_URL = f"mongodb://{MONGO_USERNAME}:{MONGO_PASSWORD}@mongo:27017"
async def init_db():
client = AsyncIOMotorClient(DATABASE_URL, uuidRepresentation="standard")
await init_beanie(database=client.hub,
document_models=[User, AccessToken, Firm],
allow_index_dropping=True)

View File

@@ -0,0 +1,28 @@
from beanie import PydanticObjectId
from pydantic import Field, BaseModel
from pymongo import IndexModel
from hub import CrudDocument
class Firm(CrudDocument):
name: str = Field()
instance: str = Field()
owner: PydanticObjectId = Field()
def compute_label(self) -> str:
return self.name
class Settings:
indexes = [
IndexModel(["name", "instance"], unique=True),
]
class FirmRead(BaseModel):
instance: str = Field()
name: str = Field()
class FirmCreate(FirmRead):
pass
class FirmUpdate(FirmRead):
pass

View File

@@ -0,0 +1,72 @@
from beanie import PydanticObjectId
from fastapi import APIRouter, Depends, HTTPException
from hub.auth import get_current_user
from hub.firm import Firm, FirmRead, FirmCreate, FirmUpdate
model = Firm
model_read = FirmRead
model_create = FirmCreate
model_update = FirmUpdate
router = APIRouter()
@router.post("/", response_description="{} added to the database".format(model.__name__))
async def create(item: model_create, user=Depends(get_current_user)) -> dict:
exists = await Firm.find_one({"name": item.name, "instance": item.instance})
if exists:
raise HTTPException(status_code=400, detail="Firm already exists")
item.created_by = user.id
item.updated_by = user.id
item.owner = user.id
o = await model(**item.model_dump()).create()
return model_read(**o.model_dump())
@router.get("/{id}", response_description="{} record retrieved".format(model.__name__))
async def read_id(id: PydanticObjectId, user=Depends(get_current_user)) -> model_read:
item = await model.get(id)
return model_read(**item.model_dump())
@router.put("/{id}", response_description="{} record updated".format(model.__name__))
async def update(id: PydanticObjectId, req: model_update, user=Depends(get_current_user)) -> model_read:
item = await model.get(id)
if not item:
raise HTTPException(
status_code=404,
detail="{} record not found!".format(model.__name__)
)
if item.owner != user.id:
raise HTTPException(
status_code=403,
detail="Insufficient credentials to modify {} record".format(model.__name__)
)
req = {k: v for k, v in req.model_dump().items() if v is not None}
update_query = {"$set": {
field: value for field, value in req.items()
}}
await item.update(update_query)
return model_read(**item.dict())
@router.delete("/{id}", response_description="{} record deleted from the database".format(model.__name__))
async def delete(id: PydanticObjectId, user=Depends(get_current_user)) -> dict:
item = await model.get(id)
if not item:
raise HTTPException(
status_code=404,
detail="{} record not found!".format(model.__name__)
)
if item.owner != user.id:
raise HTTPException(
status_code=403,
detail="Insufficient credentials delete {} record".format(model.__name__)
)
await item.delete()
return {
"message": "{} deleted successfully".format(model.__name__)
}