Importing RJSF lib with first application
This commit is contained in:
@@ -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 ""
|
||||
|
||||
@@ -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
21
api/rpk-api/hub/db.py
Normal 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)
|
||||
28
api/rpk-api/hub/firm/__init__.py
Normal file
28
api/rpk-api/hub/firm/__init__.py
Normal 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
|
||||
72
api/rpk-api/hub/firm/routes.py
Normal file
72
api/rpk-api/hub/firm/routes.py
Normal 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__)
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
|
||||
from hub import init_db as hub_init_db
|
||||
from hub.db import init_db as hub_init_db
|
||||
from hub.auth import auth_router, register_router, password_router, verification_router, users_router, \
|
||||
google_oauth_router, discord_oauth_router
|
||||
from hub.firm.routes import router as firm_router
|
||||
|
||||
if __name__ == '__main__':
|
||||
import uvicorn
|
||||
@@ -28,3 +28,4 @@ app.include_router(discord_oauth_router, prefix="/auth/discord", tags=["Auth"])
|
||||
app.include_router(verification_router, prefix="/auth/verification", tags=["Auth"], )
|
||||
app.include_router(users_router, prefix="/users", tags=["Users"], )
|
||||
app.include_router(password_router, prefix="/users", tags=["Users"], )
|
||||
app.include_router(firm_router, prefix="/firms", tags=["Firms"], )
|
||||
|
||||
Reference in New Issue
Block a user