First commit.
This commit is contained in:
commit
a3e676a0b0
13 changed files with 346 additions and 0 deletions
22
example_app/app.py
Normal file
22
example_app/app.py
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
from flask import Flask
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker
|
||||
from .models import Base, Author, Book
|
||||
from crudkit import make_blueprint
|
||||
|
||||
engine = create_engine("sqlite:///example.db", echo=True, future=True)
|
||||
SessionLocal = sessionmaker(bind=engine, expire_on_commit=False)
|
||||
|
||||
def session_factory():
|
||||
return SessionLocal()
|
||||
|
||||
registry = {"author": Author, "book": Book}
|
||||
|
||||
def create_app():
|
||||
app = Flask(__name__)
|
||||
Base.metadata.create_all(engine)
|
||||
app.register_blueprint(make_blueprint(session_factory, registry), url_prefix="/api")
|
||||
return app
|
||||
|
||||
if __name__ == "__main__":
|
||||
create_app().run(debug=True)
|
||||
18
example_app/models.py
Normal file
18
example_app/models.py
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
from typing import List
|
||||
from sqlalchemy import String, ForeignKey
|
||||
from sqlalchemy.orm import DeclarativeBase, Mapped, mapped_column, relationship
|
||||
from crudkit import CrudMixin
|
||||
|
||||
class Base(DeclarativeBase):
|
||||
pass
|
||||
|
||||
class Author(CrudMixin, Base):
|
||||
__tablename__ = "author"
|
||||
name: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
books: Mapped[List["Book"]] = relationship(back_populates="author", cascade="all, delete-orphan")
|
||||
|
||||
class Book(CrudMixin, Base):
|
||||
__tablename__ = "book"
|
||||
title: Mapped[str] = mapped_column(String(200), nullable=False)
|
||||
author_id: Mapped[int] = mapped_column(ForeignKey("author.id"), nullable=False)
|
||||
author: Mapped[Author] = relationship(back_populates="books")
|
||||
19
example_app/seed.py
Normal file
19
example_app/seed.py
Normal file
|
|
@ -0,0 +1,19 @@
|
|||
from .app import SessionLocal, engine
|
||||
from .models import Base, Author, Book
|
||||
|
||||
def run():
|
||||
Base.metadata.create_all(engine)
|
||||
s = SessionLocal()
|
||||
a1 = Author(name="Ursula K. Le Guin")
|
||||
a2 = Author(name="Octavia E. Butler")
|
||||
s.add_all([
|
||||
a1, a2,
|
||||
Book(title="The Left Hand of Darkness", author=a1),
|
||||
Book(title="A Wizard of Earthsea", author=a1),
|
||||
Book(title="Parable of the Sower", author=a2),
|
||||
])
|
||||
s.commit()
|
||||
s.close()
|
||||
|
||||
if __name__ == "__main__":
|
||||
run()
|
||||
Loading…
Add table
Add a link
Reference in a new issue