Fatsapi sql orm example

Теги: fastapi  python 

Пример построения приложения

.
└── sql_app
    ├── \__init__.py
    ├── crud.py
    ├── database.py
    ├── main.py
    ├── models.py
    └── schemas.py

SQL (Relational) Databases - собственно сам пример

Проблема: как создавать БД (если нет популяции)?

Пример создания бд из модели c помощью create_all:

Yes,sqlalchemy does create a database for you.I confirmed it on windows using this code

from sqlalchemy import create_engine, ForeignKey
from sqlalchemy import Column, Date, Integer, String
from sqlalchemy.ext.declarative import declarative_base

engine = create_engine('sqlite:///C:\\sqlitedbs\\school.db', echo=True)
Base = declarative_base()


class School(Base):

    __tablename__ = "woot"

    id = Column(Integer, primary_key=True)
    name = Column(String)


    def __init__(self, name):

        self.name = name


Base.metadata.create_all(engine)

Другой вариант - через sqlalchemy_utils

from sqlalchemy import create_engine
from sqlalchemy_utils import database_exists, create_database

engine = create_engine("postgres://localhost/mydb")
if not database_exists(engine.url):
    create_database(engine.url)

print(database_exists(engine.url))

Работа с бд ассинхронно

Статья для [fastapi]

Тулзы

fastapi-sqla - A highly opinionated SQLAlchemy extension for FastAPI fastapi-utils FastAPI-SQLAlchemy - FastAPI-SQLAlchemy provides a simple integration between FastAPI and SQLAlchemy in your application. It gives access to useful helpers to facilitate the completion of common tasks. FastAPI-SQLAlchemy - Full-stack, asynchronous Python3 framework.