add multi stuff POST endpoint

This commit is contained in:
Jakub Miazek 2022-04-30 15:34:54 +02:00
parent d54c418830
commit e77fbe95c1
2 changed files with 72 additions and 59 deletions

View File

@ -1,25 +1,31 @@
from typing import List from typing import List
from fastapi import APIRouter, Depends, status
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.ext.asyncio import AsyncSession from sqlalchemy.ext.asyncio import AsyncSession
from the_app.database import get_db from the_app.database import get_db
from the_app.models.stuff import Stuff from the_app.models.stuff import Stuff
from the_app.schemas.stuff import StuffResponse, StuffSchema from the_app.schemas.stuff import StuffResponse, StuffSchema
from the_app.utils import get_logger
router = APIRouter(prefix="/v1/stuff") router = APIRouter(prefix="/v1/stuff")
logger = get_logger(__name__)
@router.post("/add_many", status_code=status.HTTP_201_CREATED) @router.post("/add_many", status_code=status.HTTP_201_CREATED)
async def create_multi_stuff(payload: List[StuffSchema], db_session: AsyncSession = Depends(get_db)): async def create_multi_stuff(payload: List[StuffSchema], db_session: AsyncSession = Depends(get_db)):
stuff_instances = [ try:
Stuff( stuff_instances = [Stuff(name=stuf.name, description=stuf.description) for stuf in payload]
name=stuf.name, description=stuf.description db_session.add_all(stuff_instances)
) await db_session.commit()
for stuf in payload except SQLAlchemyError as ex:
] # logger.exception(ex)
db_session.add_all(stuff_instances) raise HTTPException(status_code=status.HTTP_422_UNPROCESSABLE_ENTITY, detail=repr(ex))
await db_session.commit() else:
return True logger.info(f"{len(stuff_instances)} instances of Stuff inserted into database.")
return True
@router.post("", status_code=status.HTTP_201_CREATED, response_model=StuffResponse) @router.post("", status_code=status.HTTP_201_CREATED, response_model=StuffResponse)

View File

@ -1,18 +1,24 @@
from sqlalchemy import (Column, ForeignKeyConstraint, Integer, from sqlalchemy import (
PrimaryKeyConstraint, String, Table, Text, Column,
UniqueConstraint, ForeignKey) ForeignKey,
ForeignKeyConstraint,
Integer,
PrimaryKeyConstraint,
String,
Table,
Text,
UniqueConstraint,
)
from sqlalchemy.orm import relationship from sqlalchemy.orm import relationship
from the_app.models.base import Base from the_app.models.base import Base
metadata = Base.metadata metadata = Base.metadata
class Character(Base): class Character(Base):
__tablename__ = 'character' __tablename__ = "character"
__table_args__ = ( __table_args__ = (PrimaryKeyConstraint("id", name="character_pkey"), {"schema": "shakespeare"})
PrimaryKeyConstraint('id', name='character_pkey'),
{'schema': 'shakespeare'}
)
id = Column(String(32)) id = Column(String(32))
name = Column(String(64), nullable=False) name = Column(String(64), nullable=False)
@ -20,16 +26,13 @@ class Character(Base):
abbrev = Column(String(32)) abbrev = Column(String(32))
description = Column(String(2056)) description = Column(String(2056))
work = relationship('Work', secondary='shakespeare.character_work', back_populates='character') work = relationship("Work", secondary="shakespeare.character_work", back_populates="character")
paragraph = relationship('Paragraph', back_populates='character') paragraph = relationship("Paragraph", back_populates="character")
class Wordform(Base): class Wordform(Base):
__tablename__ = 'wordform' __tablename__ = "wordform"
__table_args__ = ( __table_args__ = (PrimaryKeyConstraint("id", name="wordform_pkey"), {"schema": "shakespeare"})
PrimaryKeyConstraint('id', name='wordform_pkey'),
{'schema': 'shakespeare'}
)
id = Column(Integer) id = Column(Integer)
plain_text = Column(String(64), nullable=False) plain_text = Column(String(64), nullable=False)
@ -39,11 +42,8 @@ class Wordform(Base):
class Work(Base): class Work(Base):
__tablename__ = 'work' __tablename__ = "work"
__table_args__ = ( __table_args__ = (PrimaryKeyConstraint("id", name="work_pkey"), {"schema": "shakespeare"})
PrimaryKeyConstraint('id', name='work_pkey'),
{'schema': 'shakespeare'}
)
id = Column(String(32)) id = Column(String(32))
title = Column(String(32), nullable=False) title = Column(String(32), nullable=False)
@ -55,55 +55,62 @@ class Work(Base):
total_paragraphs = Column(Integer, nullable=False) total_paragraphs = Column(Integer, nullable=False)
notes = Column(Text) notes = Column(Text)
character = relationship('Character', secondary='shakespeare.character_work', back_populates='work') character = relationship("Character", secondary="shakespeare.character_work", back_populates="work")
chapter = relationship('Chapter', back_populates='work') chapter = relationship("Chapter", back_populates="work")
paragraph = relationship('Paragraph', back_populates='work') paragraph = relationship("Paragraph", back_populates="work")
class Chapter(Base): class Chapter(Base):
__tablename__ = 'chapter' __tablename__ = "chapter"
__table_args__ = ( __table_args__ = (
ForeignKeyConstraint(['work_id'], ['shakespeare.work.id'], name='chapter_work_id_fkey'), ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="chapter_work_id_fkey"),
PrimaryKeyConstraint('id', name='chapter_pkey'), PrimaryKeyConstraint("id", name="chapter_pkey"),
UniqueConstraint('work_id', 'section_number', 'chapter_number', name='chapter_work_id_section_number_chapter_number_key'), UniqueConstraint(
{'schema': 'shakespeare'} "work_id", "section_number", "chapter_number", name="chapter_work_id_section_number_chapter_number_key"
),
{"schema": "shakespeare"},
) )
id = Column(Integer) id = Column(Integer)
work_id = Column(ForeignKey('shakespeare.work.id'), nullable=False) work_id = Column(ForeignKey("shakespeare.work.id"), nullable=False)
section_number = Column(Integer, nullable=False) section_number = Column(Integer, nullable=False)
chapter_number = Column(Integer, nullable=False) chapter_number = Column(Integer, nullable=False)
description = Column(String(256), nullable=False) description = Column(String(256), nullable=False)
work = relationship('Work', back_populates='chapter') work = relationship("Work", back_populates="chapter")
paragraph = relationship('Paragraph', back_populates='chapter') paragraph = relationship("Paragraph", back_populates="chapter")
t_character_work = Table( t_character_work = Table(
'character_work', metadata, "character_work",
Column('character_id', ForeignKey('shakespeare.character.id'), nullable=False), metadata,
Column('work_id', ForeignKey('shakespeare.work.id'), nullable=False), Column("character_id", ForeignKey("shakespeare.character.id"), nullable=False),
ForeignKeyConstraint(['character_id'], ['shakespeare.character.id'], name='character_work_character_id_fkey'), Column("work_id", ForeignKey("shakespeare.work.id"), nullable=False),
ForeignKeyConstraint(['work_id'], ['shakespeare.work.id'], name='character_work_work_id_fkey'), ForeignKeyConstraint(["character_id"], ["shakespeare.character.id"], name="character_work_character_id_fkey"),
PrimaryKeyConstraint('character_id', 'work_id', name='character_work_pkey'), ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="character_work_work_id_fkey"),
schema='shakespeare' PrimaryKeyConstraint("character_id", "work_id", name="character_work_pkey"),
schema="shakespeare",
) )
class Paragraph(Base): class Paragraph(Base):
__tablename__ = 'paragraph' __tablename__ = "paragraph"
__table_args__ = ( __table_args__ = (
ForeignKeyConstraint(['character_id'], ['shakespeare.character.id'], name='paragraph_character_id_fkey'), ForeignKeyConstraint(["character_id"], ["shakespeare.character.id"], name="paragraph_character_id_fkey"),
ForeignKeyConstraint(['work_id', 'section_number', 'chapter_number'], ['shakespeare.chapter.work_id', 'shakespeare.chapter.section_number', 'shakespeare.chapter.chapter_number'], name='paragraph_chapter_fkey'), ForeignKeyConstraint(
ForeignKeyConstraint(['work_id'], ['shakespeare.work.id'], name='paragraph_work_id_fkey'), ["work_id", "section_number", "chapter_number"],
PrimaryKeyConstraint('id', name='paragraph_pkey'), ["shakespeare.chapter.work_id", "shakespeare.chapter.section_number", "shakespeare.chapter.chapter_number"],
{'schema': 'shakespeare'} name="paragraph_chapter_fkey",
),
ForeignKeyConstraint(["work_id"], ["shakespeare.work.id"], name="paragraph_work_id_fkey"),
PrimaryKeyConstraint("id", name="paragraph_pkey"),
{"schema": "shakespeare"},
) )
id = Column(Integer) id = Column(Integer)
work_id = Column(ForeignKey('shakespeare.work.id'), nullable=False) work_id = Column(ForeignKey("shakespeare.work.id"), nullable=False)
paragraph_num = Column(Integer, nullable=False) paragraph_num = Column(Integer, nullable=False)
character_id = Column(ForeignKey('shakespeare.character.id'), nullable=False) character_id = Column(ForeignKey("shakespeare.character.id"), nullable=False)
plain_text = Column(Text, nullable=False) plain_text = Column(Text, nullable=False)
phonetic_text = Column(Text, nullable=False) phonetic_text = Column(Text, nullable=False)
stem_text = Column(Text, nullable=False) stem_text = Column(Text, nullable=False)
@ -113,6 +120,6 @@ class Paragraph(Base):
char_count = Column(Integer, nullable=False) char_count = Column(Integer, nullable=False)
word_count = Column(Integer, nullable=False) word_count = Column(Integer, nullable=False)
character = relationship('Character', back_populates='paragraph') character = relationship("Character", back_populates="paragraph")
chapter = relationship('Chapter', back_populates='paragraph') chapter = relationship("Chapter", back_populates="paragraph")
work = relationship('Work', back_populates='paragraph') work = relationship("Work", back_populates="paragraph")