mirror of
https://github.com/fastapi-users/fastapi-users.git
synced 2025-11-01 01:48:46 +08:00
Add database abstraction
This commit is contained in:
19
fastapi_users/db/__init__.py
Normal file
19
fastapi_users/db/__init__.py
Normal file
@ -0,0 +1,19 @@
|
||||
from typing import List
|
||||
|
||||
from ..models import UserDB
|
||||
|
||||
|
||||
class UserDBInterface:
|
||||
"""
|
||||
Common interface exposing methods to list, get, create and update users in
|
||||
the database.
|
||||
"""
|
||||
|
||||
async def list(self) -> List[UserDB]:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def get_by_email(self, email: str) -> UserDB:
|
||||
raise NotImplementedError()
|
||||
|
||||
async def create(self, user: UserDB) -> UserDB:
|
||||
raise NotImplementedError()
|
||||
@ -1,7 +1,8 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import BaseModel
|
||||
from pydantic.types import EmailStr
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
|
||||
@ -1,12 +1,20 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .db import UserDBInterface
|
||||
from .models import UserCreate, UserDB
|
||||
from .password import get_password_hash
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
class UserRouter:
|
||||
|
||||
@router.post('/register')
|
||||
async def register(user: UserCreate):
|
||||
hashed_password = get_password_hash(user.password)
|
||||
return UserDB(**user.dict(), hashed_password=hashed_password)
|
||||
def __new__(cls, userDB: UserDBInterface) -> APIRouter:
|
||||
router = APIRouter()
|
||||
|
||||
@router.post('/register')
|
||||
async def register(user: UserCreate):
|
||||
hashed_password = get_password_hash(user.password)
|
||||
db_user = UserDB(**user.dict(), hashed_password=hashed_password)
|
||||
created_user = await userDB.create(db_user)
|
||||
return created_user
|
||||
|
||||
return router
|
||||
|
||||
Reference in New Issue
Block a user