WTForms, SQLAlchemy
This commit is contained in:
parent
5f328d82d3
commit
03e4c63d38
14 changed files with 227 additions and 22 deletions
|
@ -1,4 +1,5 @@
|
|||
from typing import Optional, List
|
||||
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from . import models
|
||||
|
@ -18,7 +19,7 @@ def get_user(
|
|||
def get_users(
|
||||
db: Session,
|
||||
skip: int = 0,
|
||||
limit: int = 100) -> List[Optional[models.User]]:
|
||||
limit: int = 100) -> List[models.User]:
|
||||
|
||||
return db \
|
||||
.query(models.User) \
|
||||
|
@ -29,7 +30,7 @@ def get_users(
|
|||
|
||||
def create_user(
|
||||
db: Session,
|
||||
user: schemas.User) -> models.User:
|
||||
user: schemas.UserCreate) -> models.User:
|
||||
|
||||
user_model = models.User(**user.dict())
|
||||
db.add(user_model)
|
||||
|
|
|
@ -1,7 +1,10 @@
|
|||
from typing import Generator
|
||||
from typing import AsyncGenerator
|
||||
|
||||
from pydantic import BaseSettings
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy_utils import database_exists
|
||||
from sqlalchemy_utils import create_database
|
||||
from sqlalchemy.orm import Session, sessionmaker
|
||||
from sqlalchemy.ext.declarative import declarative_base
|
||||
|
||||
|
@ -15,22 +18,25 @@ class SqlSettings(BaseSettings):
|
|||
|
||||
sql_settings = SqlSettings()
|
||||
|
||||
|
||||
db_url = (
|
||||
'mysql://{db_user}:{db_password}@'
|
||||
'{db_host}:{db_port}/${db_database}'
|
||||
'{db_host}:{db_port}/{db_database}'
|
||||
).format(**sql_settings.dict())
|
||||
|
||||
|
||||
engine = create_engine(db_url)
|
||||
if not database_exists(db_url):
|
||||
create_database(db_url)
|
||||
|
||||
SessionLocal = sessionmaker(
|
||||
autocommit=False,
|
||||
autoflush=False,
|
||||
bind=engine,
|
||||
)
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
async def get_db() -> AsyncGenerator[Session, None]:
|
||||
"""FastAPI dependency
|
||||
returning database Session object.
|
||||
Code is copied from the official docs
|
||||
|
|
|
@ -7,6 +7,6 @@ class User(Base):
|
|||
__tablename__ = 'users'
|
||||
|
||||
id = Column(Integer, primary_key=True)
|
||||
email = Column(String)
|
||||
name = Column(String)
|
||||
email = Column(String(32))
|
||||
name = Column(String(32))
|
||||
age = Column(Integer)
|
||||
|
|
|
@ -1,11 +1,14 @@
|
|||
from pydantic import BaseModel
|
||||
|
||||
|
||||
class User(BaseModel):
|
||||
id: int
|
||||
class UserCreate(BaseModel):
|
||||
email: str
|
||||
name: str
|
||||
age: int
|
||||
|
||||
|
||||
class User(UserCreate):
|
||||
id: int
|
||||
|
||||
class Config:
|
||||
orm_mode = True
|
||||
|
|
Loading…
Add table
Reference in a new issue