mirror of
https://github.com/fastapi-users/fastapi-users.git
synced 2025-11-01 18:48:14 +08:00
Implement working SQLAlchemy DB adapter
This commit is contained in:
@ -1,6 +1,6 @@
|
||||
from typing import List
|
||||
|
||||
from ..models import UserDB
|
||||
from fastapi_users.models import UserDB
|
||||
|
||||
|
||||
class UserDBInterface:
|
||||
|
||||
44
fastapi_users/db/sqlalchemy.py
Normal file
44
fastapi_users/db/sqlalchemy.py
Normal file
@ -0,0 +1,44 @@
|
||||
from typing import List
|
||||
|
||||
from databases import Database
|
||||
from sqlalchemy import Boolean, Column, String
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
from fastapi_users.db import UserDBInterface
|
||||
from fastapi_users.models import UserDB
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class User(Base):
|
||||
__tablename__ = 'user'
|
||||
|
||||
id = Column(String, primary_key=True)
|
||||
email = Column(String, unique=True, index=True)
|
||||
hashed_password = Column(String)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superuser = Column(Boolean, default=False)
|
||||
|
||||
|
||||
users = User.__table__
|
||||
|
||||
|
||||
class SQLAlchemyUserDB(UserDBInterface):
|
||||
|
||||
database: Database
|
||||
|
||||
def __init__(self, database):
|
||||
self.database = database
|
||||
|
||||
async def list(self) -> List[UserDB]:
|
||||
query = users.select()
|
||||
return await self.database.fetch_all(query)
|
||||
|
||||
async def get_by_email(self, email: str) -> UserDB:
|
||||
query = users.select().where(User.email == email)
|
||||
return await self.database.fetch_one(query)
|
||||
|
||||
async def create(self, user: UserDB) -> UserDB:
|
||||
query = users.insert().values(**user.dict())
|
||||
await self.database.execute(query)
|
||||
return user
|
||||
@ -1,17 +1,20 @@
|
||||
import uuid
|
||||
from typing import Optional
|
||||
|
||||
import pydantic
|
||||
from pydantic import BaseModel
|
||||
from pydantic.types import EmailStr
|
||||
|
||||
|
||||
class UserBase(BaseModel):
|
||||
id: str = uuid.uuid4
|
||||
id: str = None
|
||||
email: Optional[EmailStr] = None
|
||||
is_active: Optional[bool] = True
|
||||
is_superuser: Optional[bool] = False
|
||||
first_name: Optional[str] = None
|
||||
last_name: Optional[str] = None
|
||||
|
||||
@pydantic.validator('id', pre=True, always=True)
|
||||
def default_id(cls, v):
|
||||
return v or str(uuid.uuid4())
|
||||
|
||||
|
||||
class UserCreate(UserBase):
|
||||
|
||||
@ -1,8 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
from .db import UserDBInterface
|
||||
from .models import UserCreate, UserDB
|
||||
from .password import get_password_hash
|
||||
from fastapi_users.db import UserDBInterface
|
||||
from fastapi_users.models import UserCreate, UserDB
|
||||
from fastapi_users.password import get_password_hash
|
||||
|
||||
|
||||
class UserRouter:
|
||||
|
||||
Reference in New Issue
Block a user