List and Read on frontend, fullecrud on back
This commit is contained in:
160
back/.gitignore
vendored
Normal file
160
back/.gitignore
vendored
Normal file
@@ -0,0 +1,160 @@
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
share/python-wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
MANIFEST
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
*.py,cover
|
||||
.hypothesis/
|
||||
.pytest_cache/
|
||||
cover/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
db.sqlite3
|
||||
db.sqlite3-journal
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
.pybuilder/
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# IPython
|
||||
profile_default/
|
||||
ipython_config.py
|
||||
|
||||
# pyenv
|
||||
# For a library or package, you might want to ignore these files since the code is
|
||||
# intended to run in multiple environments; otherwise, check them in:
|
||||
# .python-version
|
||||
|
||||
# pipenv
|
||||
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
|
||||
# However, in case of collaboration, if having platform-specific dependencies or dependencies
|
||||
# having no cross-platform support, pipenv may install dependencies that don't work, or not
|
||||
# install all needed dependencies.
|
||||
#Pipfile.lock
|
||||
|
||||
# poetry
|
||||
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
|
||||
# This is especially recommended for binary packages to ensure reproducibility, and is more
|
||||
# commonly ignored for libraries.
|
||||
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
|
||||
#poetry.lock
|
||||
|
||||
# pdm
|
||||
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
|
||||
#pdm.lock
|
||||
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
|
||||
# in version control.
|
||||
# https://pdm.fming.dev/#use-with-ide
|
||||
.pdm.toml
|
||||
|
||||
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
|
||||
__pypackages__/
|
||||
|
||||
# Celery stuff
|
||||
celerybeat-schedule
|
||||
celerybeat.pid
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# Environments
|
||||
.env
|
||||
.venv
|
||||
env/
|
||||
venv/
|
||||
ENV/
|
||||
env.bak/
|
||||
venv.bak/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
.dmypy.json
|
||||
dmypy.json
|
||||
|
||||
# Pyre type checker
|
||||
.pyre/
|
||||
|
||||
# pytype static type analyzer
|
||||
.pytype/
|
||||
|
||||
# Cython debug symbols
|
||||
cython_debug/
|
||||
|
||||
# PyCharm
|
||||
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
|
||||
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
|
||||
# and can be added to the global gitignore or merged into this file. For a more nuclear
|
||||
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
|
||||
#.idea/
|
||||
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")
|
||||
|
||||
@@ -2,4 +2,5 @@ fastapi==0.88.0
|
||||
fastapi_users==10.2.1
|
||||
fastapi_users_db_beanie==1.1.2
|
||||
motor==3.1.1
|
||||
fastapi-paginate==0.1.0
|
||||
uvicorn
|
||||
Reference in New Issue
Block a user