prompt
stringlengths
45
17.8k
completion
stringlengths
6
107
api
stringlengths
12
42
from datetime import date from fastapi import FastAPI, Query from sqlmodel import Session, create_engine, select from .datatypes import ArtmuseumAddress, ArtmuseumTimeLabel from .db.crud import init_db from .db.models import ArtmuseumExhibition, PhilharmoniaConcert sql_engine = create_engine( "sqlite:///database.db", connect_args={"check_same_thread": False} ) app = FastAPI( title="Murmansk Culture API", # description="", version="0.0.1", contact={ "name": "<NAME>", "url": "https://github.com/anorlovsky", "email": "<EMAIL>", }, redoc_url="/", docs_url=None, ) @app.on_event("startup") def on_startup(): init_db(sql_engine) @app.get( "/artmuseum", response_model=list[ArtmuseumExhibition], description="Возвращает список текущих и ближайших выставок [Мурманского областного художественного музея](https://artmmuseum.ru/)", ) async def get_artmuseum_exhibitions( time: ArtmuseumTimeLabel = Query( None, description='Вернуть только текущие (`"now"`) или только ближайшие (`"soon"`) выставки', ) ): with Session(sql_engine) as session: if time is None: stmt =
select(ArtmuseumExhibition)
sqlmodel.select
from datetime import date from fastapi import FastAPI, Query from sqlmodel import Session, create_engine, select from .datatypes import ArtmuseumAddress, ArtmuseumTimeLabel from .db.crud import init_db from .db.models import ArtmuseumExhibition, PhilharmoniaConcert sql_engine = create_engine( "sqlite:///database.db", connect_args={"check_same_thread": False} ) app = FastAPI( title="Murmansk Culture API", # description="", version="0.0.1", contact={ "name": "<NAME>", "url": "https://github.com/anorlovsky", "email": "<EMAIL>", }, redoc_url="/", docs_url=None, ) @app.on_event("startup") def on_startup(): init_db(sql_engine) @app.get( "/artmuseum", response_model=list[ArtmuseumExhibition], description="Возвращает список текущих и ближайших выставок [Мурманского областного художественного музея](https://artmmuseum.ru/)", ) async def get_artmuseum_exhibitions( time: ArtmuseumTimeLabel = Query( None, description='Вернуть только текущие (`"now"`) или только ближайшие (`"soon"`) выставки', ) ): with Session(sql_engine) as session: if time is None: stmt = select(ArtmuseumExhibition) elif time == ArtmuseumTimeLabel.NOW: stmt = select(ArtmuseumExhibition).where( ArtmuseumExhibition.start_date <= date.today() ) elif time == ArtmuseumTimeLabel.SOON: stmt = select(ArtmuseumExhibition).where( ArtmuseumExhibition.start_date > date.today() ) return session.exec(stmt).all() @app.get( "/philharmonia", response_model=list[PhilharmoniaConcert], description="Возвращает список ближайших концертов [Мурманской областной филармонии](https://www.murmansound.ru)", ) async def get_philharmonia_concerts(): with Session(sql_engine) as session: return session.exec(
select(PhilharmoniaConcert)
sqlmodel.select
from datetime import date from fastapi import FastAPI, Query from sqlmodel import Session, create_engine, select from .datatypes import ArtmuseumAddress, ArtmuseumTimeLabel from .db.crud import init_db from .db.models import ArtmuseumExhibition, PhilharmoniaConcert sql_engine = create_engine( "sqlite:///database.db", connect_args={"check_same_thread": False} ) app = FastAPI( title="Murmansk Culture API", # description="", version="0.0.1", contact={ "name": "<NAME>", "url": "https://github.com/anorlovsky", "email": "<EMAIL>", }, redoc_url="/", docs_url=None, ) @app.on_event("startup") def on_startup(): init_db(sql_engine) @app.get( "/artmuseum", response_model=list[ArtmuseumExhibition], description="Возвращает список текущих и ближайших выставок [Мурманского областного художественного музея](https://artmmuseum.ru/)", ) async def get_artmuseum_exhibitions( time: ArtmuseumTimeLabel = Query( None, description='Вернуть только текущие (`"now"`) или только ближайшие (`"soon"`) выставки', ) ): with Session(sql_engine) as session: if time is None: stmt = select(ArtmuseumExhibition) elif time == ArtmuseumTimeLabel.NOW: stmt =
select(ArtmuseumExhibition)
sqlmodel.select
from datetime import date from fastapi import FastAPI, Query from sqlmodel import Session, create_engine, select from .datatypes import ArtmuseumAddress, ArtmuseumTimeLabel from .db.crud import init_db from .db.models import ArtmuseumExhibition, PhilharmoniaConcert sql_engine = create_engine( "sqlite:///database.db", connect_args={"check_same_thread": False} ) app = FastAPI( title="Murmansk Culture API", # description="", version="0.0.1", contact={ "name": "<NAME>", "url": "https://github.com/anorlovsky", "email": "<EMAIL>", }, redoc_url="/", docs_url=None, ) @app.on_event("startup") def on_startup(): init_db(sql_engine) @app.get( "/artmuseum", response_model=list[ArtmuseumExhibition], description="Возвращает список текущих и ближайших выставок [Мурманского областного художественного музея](https://artmmuseum.ru/)", ) async def get_artmuseum_exhibitions( time: ArtmuseumTimeLabel = Query( None, description='Вернуть только текущие (`"now"`) или только ближайшие (`"soon"`) выставки', ) ): with Session(sql_engine) as session: if time is None: stmt = select(ArtmuseumExhibition) elif time == ArtmuseumTimeLabel.NOW: stmt = select(ArtmuseumExhibition).where( ArtmuseumExhibition.start_date <= date.today() ) elif time == ArtmuseumTimeLabel.SOON: stmt =
select(ArtmuseumExhibition)
sqlmodel.select
from uuid import UUID from sqlalchemy import event from sqlalchemy.schema import Column, ForeignKey, UniqueConstraint from sqlmodel import Field, Relationship from sqlmodel.sql.sqltypes import GUID from joj.horse.models.base import DomainURLORMModel, url_pre_save from joj.horse.models.domain import Domain from joj.horse.schemas.domain_invitation import DomainInvitationDetail class DomainInvitation(DomainURLORMModel, DomainInvitationDetail, table=True): # type: ignore[call-arg] __tablename__ = "domain_invitations" __table_args__ = ( UniqueConstraint("domain_id", "url"), UniqueConstraint("domain_id", "code"), ) domain_id: UUID = Field( sa_column=Column( GUID, ForeignKey("domains.id", ondelete="CASCADE"), nullable=False ) ) domain: "Domain" =
Relationship(back_populates="invitations")
sqlmodel.Relationship
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str =
Field(primary_key=True)
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str =
Field(primary_key=True)
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str =
Field(foreign_key="document.id")
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str =
Field(primary_key=True)
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str = Field(primary_key=True) name: str description: Optional[str] class EntityMention(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str = Field(primary_key=True) name: str description: Optional[str] class EntityMention(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) text: str score: Optional[float] label: str start: int end: int paragraph_id: str =
Field(foreign_key="paragraph.id")
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str = Field(primary_key=True) name: str description: Optional[str] class EntityMention(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) text: str score: Optional[float] label: str start: int end: int paragraph_id: str = Field(foreign_key="paragraph.id") kb_id: Optional[str] =
Field(foreign_key="entity.id")
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str = Field(primary_key=True) name: str description: Optional[str] class EntityMention(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) text: str score: Optional[float] label: str start: int end: int paragraph_id: str = Field(foreign_key="paragraph.id") kb_id: Optional[str] = Field(foreign_key="entity.id") class EntityFeature(SQLModel, table=True): id: int =
Field(primary_key=True)
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with Session(self.engine) as session: return session.exec(stmt, params=params).all() class DatabaseWorker(th.Thread): def __init__(self, uri: str, queue: queue.Queue, batch: int = None, timeout: int = 10 ): super().__init__() self.q = queue self.db = None self.uri = uri self.timeout = timeout self.batch = batch def run(self): self.db = Database(self.uri) while True: cache = [] try: cache.append(self.q.get(timeout=self.timeout)) if self.batch: if len(cache) % self.batch == 0: self.db.create_all(cache) cache = [] else: cache = [] except queue.Empty: self.db.create_all(cache) break # ~~~ Models ~~~~~~~~~~~~~~~~~ class Document(SQLModel, table=True): id: str = Field(primary_key=True) name: str href: str date: dt.datetime text: Optional[str] = None date_collected: dt.datetime collected_by: str class Paragraph(SQLModel, table=True): id: str = Field(primary_key=True) text: str document_id: str = Field(foreign_key="document.id") sentiment: str sent_score: float class Entity(SQLModel, table=True): id: str = Field(primary_key=True) name: str description: Optional[str] class EntityMention(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) text: str score: Optional[float] label: str start: int end: int paragraph_id: str = Field(foreign_key="paragraph.id") kb_id: Optional[str] = Field(foreign_key="entity.id") class EntityFeature(SQLModel, table=True): id: int = Field(primary_key=True) kb_id: str =
Field(foreign_key="entity.id")
sqlmodel.Field
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine =
create_engine(uri)
sqlmodel.create_engine
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri)
SQLModel.metadata.create_all(self.engine)
sqlmodel.SQLModel.metadata.create_all
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with
Session(self.engine)
sqlmodel.Session
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with
Session(self.engine)
sqlmodel.Session
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt = select(model).where(getattr(model, key) == value) print(stmt) return self.exec(stmt) def exec(self, stmt: str, params = {}): with
Session(self.engine)
sqlmodel.Session
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt = select(model).where(model.id == id) return session.exec(stmt).first() def get_by_field(self, key: str, value: Any, model: SQLModel): stmt =
select(model)
sqlmodel.select
from typing import Optional, Dict, List, Any, Union import datetime as dt from sqlmodel import Field, Session, SQLModel, create_engine, select import threading as th import queue # ~~~ Database ~~~~~~~~~~~~~~~ class Database: def __init__(self, uri: str): self.engine = create_engine(uri) SQLModel.metadata.create_all(self.engine) def create_all(self, items: List[SQLModel]): with Session(self.engine) as session: for item in items: session.add(item) session.commit() def get_by_id(self, id: Union[str, int], model: SQLModel): with Session(self.engine) as session: stmt =
select(model)
sqlmodel.select
# A file containing fixtures for testing # Fixtures defined here are available for the whole scope from fastapi.testclient import TestClient import pytest import os from ..main import app, session from sqlmodel import SQLModel, Session, create_engine from sqlmodel.pool import StaticPool from ..utils import get_session db_name = "test_db.sqlite" test_con = f"sqlite:///{db_name}" test_engine = create_engine( test_con, connect_args={"check_same_thread": False}, echo=True ) @pytest.fixture(name="create_db", scope="session") def create_db(): # setup
SQLModel.metadata.create_all(test_engine)
sqlmodel.SQLModel.metadata.create_all
# A file containing fixtures for testing # Fixtures defined here are available for the whole scope from fastapi.testclient import TestClient import pytest import os from ..main import app, session from sqlmodel import SQLModel, Session, create_engine from sqlmodel.pool import StaticPool from ..utils import get_session db_name = "test_db.sqlite" test_con = f"sqlite:///{db_name}" test_engine = create_engine( test_con, connect_args={"check_same_thread": False}, echo=True ) @pytest.fixture(name="create_db", scope="session") def create_db(): # setup SQLModel.metadata.create_all(test_engine) yield # teardown os.remove(db_name) @pytest.fixture(name="session") def session_fixture(create_db): create_db with
Session(test_engine)
sqlmodel.Session
from sqlmodel import Session from .database import create_db_and_tables, engine from .hero_model import Hero from .team_model import Team def create_heroes(): with
Session(engine)
sqlmodel.Session
from sqlalchemy.engine import Engine from sqlmodel import create_engine, Session, SQLModel from sqlmodel.engine.create import _FutureEngine from typing import Union, Optional from pyemits.common.validation import raise_if_incorrect_type, raise_if_not_all_value_contains, \ raise_if_not_all_element_type_uniform, check_all_element_type_uniform, raise_if_value_not_contains from typing import List class DBConnectionBase: """ References ---------- for users who want to know the differences between Engine, Connection, Session https://stackoverflow.com/questions/34322471/sqlalchemy-engine-connection-and-session-difference """ def __init__(self, db_engine: Union[Engine, _FutureEngine]): self._db_engine = db_engine
SQLModel.metadata.create_all(self._db_engine)
sqlmodel.SQLModel.metadata.create_all
from sqlalchemy.engine import Engine from sqlmodel import create_engine, Session, SQLModel from sqlmodel.engine.create import _FutureEngine from typing import Union, Optional from pyemits.common.validation import raise_if_incorrect_type, raise_if_not_all_value_contains, \ raise_if_not_all_element_type_uniform, check_all_element_type_uniform, raise_if_value_not_contains from typing import List class DBConnectionBase: """ References ---------- for users who want to know the differences between Engine, Connection, Session https://stackoverflow.com/questions/34322471/sqlalchemy-engine-connection-and-session-difference """ def __init__(self, db_engine: Union[Engine, _FutureEngine]): self._db_engine = db_engine SQLModel.metadata.create_all(self._db_engine) @classmethod def from_db_user(cls, db_type, db_driver, host, user, password, port, db, charset='utf8', echo=True): engine =
create_engine(f"{db_type}+{db_driver}://{user}:{password}@{host}:{port}/{db}", echo=echo)
sqlmodel.create_engine
from sqlalchemy.engine import Engine from sqlmodel import create_engine, Session, SQLModel from sqlmodel.engine.create import _FutureEngine from typing import Union, Optional from pyemits.common.validation import raise_if_incorrect_type, raise_if_not_all_value_contains, \ raise_if_not_all_element_type_uniform, check_all_element_type_uniform, raise_if_value_not_contains from typing import List class DBConnectionBase: """ References ---------- for users who want to know the differences between Engine, Connection, Session https://stackoverflow.com/questions/34322471/sqlalchemy-engine-connection-and-session-difference """ def __init__(self, db_engine: Union[Engine, _FutureEngine]): self._db_engine = db_engine SQLModel.metadata.create_all(self._db_engine) @classmethod def from_db_user(cls, db_type, db_driver, host, user, password, port, db, charset='utf8', echo=True): engine = create_engine(f"{db_type}+{db_driver}://{user}:{password}@{host}:{port}/{db}", echo=echo) return cls(engine) @classmethod def from_full_db_path(cls, full_db_path, echo=True): engine =
create_engine(f"{full_db_path}", echo=echo)
sqlmodel.create_engine
from sqlalchemy.engine import Engine from sqlmodel import create_engine, Session, SQLModel from sqlmodel.engine.create import _FutureEngine from typing import Union, Optional from pyemits.common.validation import raise_if_incorrect_type, raise_if_not_all_value_contains, \ raise_if_not_all_element_type_uniform, check_all_element_type_uniform, raise_if_value_not_contains from typing import List class DBConnectionBase: """ References ---------- for users who want to know the differences between Engine, Connection, Session https://stackoverflow.com/questions/34322471/sqlalchemy-engine-connection-and-session-difference """ def __init__(self, db_engine: Union[Engine, _FutureEngine]): self._db_engine = db_engine SQLModel.metadata.create_all(self._db_engine) @classmethod def from_db_user(cls, db_type, db_driver, host, user, password, port, db, charset='utf8', echo=True): engine = create_engine(f"{db_type}+{db_driver}://{user}:{password}@{host}:{port}/{db}", echo=echo) return cls(engine) @classmethod def from_full_db_path(cls, full_db_path, echo=True): engine = create_engine(f"{full_db_path}", echo=echo) return cls(engine) def get_db_engine(self): return self._db_engine def execute(self, sql, always_commit=False, fetch: Optional[Union[int, str]] = None): with
Session(self._db_engine)
sqlmodel.Session
"""add verified result to application Revision ID: d8a156ffaeae Revises: <KEY> Create Date: 2022-03-30 16:00:13.195216 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = "d8a156ffaeae" down_revision = "<KEY>" branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "job_applicant", sa.Column("verified",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from datetime import date from typing import List, Optional from api.ecoindex.models.responses import ApiEcoindex from api.models.enums import Version from sqlalchemy.ext.asyncio.session import AsyncSession from sqlmodel import select from db.helper import date_filter async def get_host_list_db( session: AsyncSession, version: Optional[Version] = Version.v1, q: Optional[str] = None, date_from: Optional[date] = None, date_to: Optional[date] = None, page: Optional[int] = 1, size: Optional[int] = 50, ) -> List[str]: statement = (
select(ApiEcoindex.host)
sqlmodel.select
from datetime import datetime, date from decimal import Decimal from typing import Optional, List from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ...db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class HistoryTravelReimburse(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import asyncio import os from decimal import Decimal from typing import Optional from pydantic import condecimal from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlmodel import Field, SQLModel, select class Restaurant(SQLModel, table=True): id: int =
Field(default=None, primary_key=True)
sqlmodel.Field
import asyncio import os from decimal import Decimal from typing import Optional from pydantic import condecimal from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlmodel import Field, SQLModel, select class Restaurant(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str =
Field(index=True)
sqlmodel.Field
import asyncio import os from decimal import Decimal from typing import Optional from pydantic import condecimal from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlmodel import Field, SQLModel, select class Restaurant(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str = Field(index=True) address: str currency: str class MenuItem(SQLModel, table=True): id: int =
Field(default=None, primary_key=True)
sqlmodel.Field
import asyncio import os from decimal import Decimal from typing import Optional from pydantic import condecimal from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlmodel import Field, SQLModel, select class Restaurant(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str = Field(index=True) address: str currency: str class MenuItem(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str price: condecimal(decimal_places=2) restaurant_id: Optional[int] =
Field(default=None, foreign_key="restaurant.id")
sqlmodel.Field
import asyncio import os from decimal import Decimal from typing import Optional from pydantic import condecimal from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine from sqlmodel import Field, SQLModel, select class Restaurant(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str = Field(index=True) address: str currency: str class MenuItem(SQLModel, table=True): id: int = Field(default=None, primary_key=True) name: str price: condecimal(decimal_places=2) restaurant_id: Optional[int] = Field(default=None, foreign_key="restaurant.id") async def main() -> None: db_url = os.environ.get("RESTAURANT_DB_URL", "sqlite+aiosqlite:///my_db") db_engine = create_async_engine(db_url) async with db_engine.begin() as conn: await conn.run_sync(SQLModel.metadata.create_all) async with AsyncSession(db_engine, expire_on_commit=False) as session: # Writing restaurant = Restaurant( name="Second best Pizza in town", address="Foo street 1", currency="EUR" ) session.add(restaurant) await session.commit() pizza1 = MenuItem(name="Margherita", price=10.50, restaurant_id=restaurant.id) pizza2 = MenuItem(name="2xPineapple", price=16.80, restaurant_id=restaurant.id) session.add_all((pizza1, pizza2)) await session.commit() # Reading query = (
select(MenuItem)
sqlmodel.select
"""init_db Revision ID: 23799b5136c5 Revises: Create Date: 2021-12-11 00:49:58.116933 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '23799b5136c5' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('full_name',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init_db Revision ID: 23799b5136c5 Revises: Create Date: 2021-12-11 00:49:58.116933 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '23799b5136c5' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('email',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init_db Revision ID: 23799b5136c5 Revises: Create Date: 2021-12-11 00:49:58.116933 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '23799b5136c5' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('hashed_password',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""init_db Revision ID: 23799b5136c5 Revises: Create Date: 2021-12-11 00:49:58.116933 """ from alembic import op import sqlalchemy as sa import sqlmodel # revision identifiers, used by Alembic. revision = '23799b5136c5' down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table('user', sa.Column('id', sa.Integer(), nullable=True), sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column('hashed_password', sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column('is_active', sa.Boolean(), nullable=True), sa.Column('is_superuser', sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint('id') ) op.create_index(op.f('ix_user_email'), 'user', ['email'], unique=False) op.create_index(op.f('ix_user_full_name'), 'user', ['full_name'], unique=False) op.create_index(op.f('ix_user_hashed_password'), 'user', ['hashed_password'], unique=False) op.create_index(op.f('ix_user_id'), 'user', ['id'], unique=False) op.create_index(op.f('ix_user_is_active'), 'user', ['is_active'], unique=False) op.create_index(op.f('ix_user_is_superuser'), 'user', ['is_superuser'], unique=False) op.create_table('task', sa.Column('status', sa.Enum('draft', 'in_process', 'delete', 'done', name='taskstatus'), nullable=True), sa.Column('id', sa.Integer(), nullable=True), sa.Column('created_at', sa.DateTime(), nullable=True), sa.Column('title',
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
from sqlmodel import SQLModel, create_engine, Session from victor_api.config import settings engine = create_engine( url=settings.db.url, echo=settings.db.echo, connect_args=settings.db.connect_args ) def get_session(): with Session(engine) as session: yield session def init_db():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from sqlmodel import SQLModel, create_engine, Session from victor_api.config import settings engine = create_engine( url=settings.db.url, echo=settings.db.echo, connect_args=settings.db.connect_args ) def get_session(): with
Session(engine)
sqlmodel.Session
from typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine =
create_engine(sqlite_url, echo=True)
sqlmodel.create_engine
from typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] =
Field(default=None, foreign_key="team.id")
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel, create_engine class Team(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str headquarters: str class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None team_id: Optional[int] = Field(default=None, foreign_key="team.id") sqlite_file_name = "database.db" sqlite_url = f"sqlite:///{sqlite_file_name}" engine = create_engine(sqlite_url, echo=True) def create_db_and_tables():
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
from fastapi import APIRouter, Depends, HTTPException, Query, Path from sqlmodel import Session, select from sqlalchemy.exc import IntegrityError from typing import List, Any import datetime as dt from app.src.common.utils import profiling_api from app.src.models.product import ( Product, ProductRead, ProductCreate, ProductUpdate, ProductReadwithTypeAndTags, ) from app.src.db.engine import get_session from app.src.api.endpoints.product_type import get_producttype_or_404 from app.src.api.endpoints.tags import get_tag_or_404, get_tag_by_name_or_404 from app.src.common.security import get_current_user from app.src.models.app_user import AppUser from app.src.models.tag import Tag from app.src.logger import logger router = APIRouter() async def get_product_or_404( *, session: Session = Depends(get_session), product_id: int = Path(..., ge=1), current_user: AppUser = Depends(get_current_user), ): start_time = dt.datetime.now() try: db_product = session.get(Product, product_id) if db_product: return { "db_product": db_product, "username": current_user.username, "start_time": start_time, } else: logger.error("Product not found") logger.exception("Product not found") raise HTTPException(status_code=404, detail="Product not found") except KeyError: logger.error("Product not found") logger.exception("KeyError: Product not found") raise HTTPException(status_code=400, detail="Product not found") @router.get("/", response_model=List[ProductReadwithTypeAndTags]) async def read_all_products( session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, lte=100), current_user: AppUser = Depends(get_current_user), ) -> Any: """ Retrieve all products """ start_time = dt.datetime.now() products = session.exec(select(Product).offset(offset).limit(limit)).all() profiling_api("Product:get:all", start_time, current_user.username) return products @router.get("/{product_id}", response_model=ProductReadwithTypeAndTags) async def read_product( *, product_id: int, db_product: Product = Depends(get_product_or_404) ): """ Get the product type by id """ # Le righe commentate sotto, sostituite dalla nuova Depends # Nota: il parametro product_id a get_product_or_404 è preso dal path # p = session.get(Product, product_id) # if not p: # raise HTTPException( # status_code=404, # detail="Product type not found" # ) profiling_api( f"Product:read:by_id:{product_id}", db_product["start_time"], db_product["username"], ) return db_product["db_product"] @router.post("/", response_model=ProductRead) async def create_product( *, session: Session = Depends(get_session), product: ProductCreate, current_user: AppUser = Depends(get_current_user), ) -> Any: """ Create a new single product """ start_time = dt.datetime.now() # Controllo esistenza product type _ = await get_producttype_or_404(producttype_id=product.type_id, session=session) # Controllo integrità o altri errori try: db_product = Product.from_orm(product) session.add(db_product) session.commit() profiling_api("Product:insert:single", start_time, current_user.username) except IntegrityError: logger.error("Impossible to create product with same name") logger.exception("Integrity Error: Impossible to create product with same name") raise HTTPException( status_code=404, detail="Impossible to create product with same name" ) session.refresh(db_product) return db_product @router.patch("/update/{product_id}", response_model=ProductRead) async def update_product_by_id( *, product_id: int, session: Session = Depends(get_session), product: ProductUpdate, db_product: Product = Depends(get_product_or_404), ): """ Modify and existing product by id """ # Le righe commentate sotto, sostituite dalla nuova Depends # Nota: il parametro product_id a get_product_or_404 è preso dal path # db_product = session.get(Product, product_id) # if not db_product: # raise HTTPException(status_code=404, detail="Product not found") existing_product = db_product["db_product"] pr_data = product.dict(exclude_unset=True) for key, value in pr_data.items(): setattr(existing_product, key, value) session.add(existing_product) session.commit() session.refresh(existing_product) profiling_api( f"Product:update:by_id:{product_id}", db_product["start_time"], db_product["username"], ) return existing_product @router.patch("/update/by_name/{product_name}", response_model=ProductRead) async def update_product_by_name( *, session: Session = Depends(get_session), product_name: str, product: ProductUpdate, current_user: AppUser = Depends(get_current_user), ): """ Modify an existing product by name """ start_time = dt.datetime.now() db_product = session.exec(
select(Product)
sqlmodel.select
from fastapi import APIRouter, Depends, HTTPException, Query, Path from sqlmodel import Session, select from sqlalchemy.exc import IntegrityError from typing import List, Any import datetime as dt from app.src.common.utils import profiling_api from app.src.models.product import ( Product, ProductRead, ProductCreate, ProductUpdate, ProductReadwithTypeAndTags, ) from app.src.db.engine import get_session from app.src.api.endpoints.product_type import get_producttype_or_404 from app.src.api.endpoints.tags import get_tag_or_404, get_tag_by_name_or_404 from app.src.common.security import get_current_user from app.src.models.app_user import AppUser from app.src.models.tag import Tag from app.src.logger import logger router = APIRouter() async def get_product_or_404( *, session: Session = Depends(get_session), product_id: int = Path(..., ge=1), current_user: AppUser = Depends(get_current_user), ): start_time = dt.datetime.now() try: db_product = session.get(Product, product_id) if db_product: return { "db_product": db_product, "username": current_user.username, "start_time": start_time, } else: logger.error("Product not found") logger.exception("Product not found") raise HTTPException(status_code=404, detail="Product not found") except KeyError: logger.error("Product not found") logger.exception("KeyError: Product not found") raise HTTPException(status_code=400, detail="Product not found") @router.get("/", response_model=List[ProductReadwithTypeAndTags]) async def read_all_products( session: Session = Depends(get_session), offset: int = 0, limit: int = Query(default=100, lte=100), current_user: AppUser = Depends(get_current_user), ) -> Any: """ Retrieve all products """ start_time = dt.datetime.now() products = session.exec(
select(Product)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 =
select(Epic)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 = select(Epic).join(Client) client_to_update = session.exec(statement).one() client_to_update.active = False session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/activate") async def activate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Activate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be activated. session : Session SQL session that is to be used to activate a client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 = select(Epic).join(Client) client_to_update = session.exec(statement).one() client_to_update.active = False session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/activate") async def activate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Activate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be activated. session : Session SQL session that is to be used to activate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = True client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate") async def deactivate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Deactivate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be deactivated. session : Session SQL session that is to be used to deactivate a client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 = select(Epic).join(Client) client_to_update = session.exec(statement).one() client_to_update.active = False session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/activate") async def activate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Activate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be activated. session : Session SQL session that is to be used to activate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = True client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate") async def deactivate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Deactivate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be deactivated. session : Session SQL session that is to be used to deactivate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = False client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate-epics") async def update_clients_and_epics( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client and its epics""" """ Deactivate a client and its epics using the client's ID as a key. Parameters ---------- client_id : int ID of the client to deactivate. session : Session SQL session that is to be used to deactivate the client and its respective epics. Defaults to creating a dependency on the running SQL model session. """ statement1 =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 = select(Epic).join(Client) client_to_update = session.exec(statement).one() client_to_update.active = False session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/activate") async def activate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Activate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be activated. session : Session SQL session that is to be used to activate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = True client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate") async def deactivate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Deactivate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be deactivated. session : Session SQL session that is to be used to deactivate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = False client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate-epics") async def update_clients_and_epics( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client and its epics""" """ Deactivate a client and its epics using the client's ID as a key. Parameters ---------- client_id : int ID of the client to deactivate. session : Session SQL session that is to be used to deactivate the client and its respective epics. Defaults to creating a dependency on the running SQL model session. """ statement1 = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement1).one() client_to_update.is_active = False client_to_update.updated_at = datetime.now() session.add(client_to_update) statement2 =
select(Epic)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = ( select(Client.id, Client.name, Epic.name) .select_from(Client) .join(Epic) .where(Client.id == client_id) ) results = session.exec(statement).all() return results @router.put("/{client_id}/deactivate-client") async def update_clients( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client""" statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.active = False statement2 = select(Epic).join(Client) client_to_update = session.exec(statement).one() client_to_update.active = False session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/activate") async def activate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Activate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be activated. session : Session SQL session that is to be used to activate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = True client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate") async def deactivate_clients( *, client_id: int, session: Session = Depends(get_session), ): """ Deactivate a client using its id as a key. Parameters ---------- client_id : int ID of the client to be deactivated. session : Session SQL session that is to be used to deactivate a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement).one() client_to_update.is_active = False client_to_update.updated_at = datetime.now() session.add(client_to_update) session.commit() session.refresh(client_to_update) return client_to_update @router.put("/{client_id}/deactivate-epics") async def update_clients_and_epics( *, client_id: int, session: Session = Depends(get_session), ): """Deactivate a client and its epics""" """ Deactivate a client and its epics using the client's ID as a key. Parameters ---------- client_id : int ID of the client to deactivate. session : Session SQL session that is to be used to deactivate the client and its respective epics. Defaults to creating a dependency on the running SQL model session. """ statement1 = select(Client).where(Client.id == client_id) client_to_update = session.exec(statement1).one() client_to_update.is_active = False client_to_update.updated_at = datetime.now() session.add(client_to_update) statement2 = select(Epic).where(Epic.client_id == client_id) epics_to_update = session.exec(statement2).all() for epic in epics_to_update: epic.is_active = False session.add(epic) session.commit() return True @router.put("/{client_id}") async def update_clients( *, client_id: int = None, new_client_name: str = None, is_active: bool = None, session: Session = Depends(get_session), ): """ Update a client from a client_id. Parameters ---------- client_id : int ID of the client to update. new_client_name : str New name of the client. session : Session SQL session that is to be used to update a client. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement =
select(Client)
sqlmodel.select
from fastapi import APIRouter, Depends from ..utils import engine, get_session from sqlmodel import Session, select from sqlalchemy.exc import NoResultFound from ..models.client import Client from ..models.epic import Epic from datetime import datetime router = APIRouter(prefix="/api/clients", tags=["client"]) @router.post("/") async def post_client(*, client: Client, session: Session = Depends(get_session)): """ Post a new client. Parameters ---------- client : Client Client that is to be added to the database. session : Session SQL session that is to be used to add the client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == client.name) try: result = session.exec(statement).one() return False except NoResultFound: session.add(client) session.commit() session.refresh(client) return client @router.get("/") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all clients. Parameters ---------- session : Session SQL session that is to be used to get a list of the clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client) results = session.exec(statement).all() return results @router.get("/active") async def read_clients(session: Session = Depends(get_session)): """ Get a list of all active clients. Parameters ---------- session : Session SQL session that is to be used to get a list of all of the active clients. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.is_active == True).order_by(Client.id.asc()) results = session.exec(statement).all() return results @router.get("/{client_id}") async def read_clients( *, client_id: int = None, session: Session = Depends(get_session) ): """ Get a client by client_id. Parameters ---------- client_id : int ID of client that is to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.id == client_id) try: result = session.exec(statement).one() return result except NoResultFound: msg = f"""There is no client with id = {client_id}""" return msg @router.get("/names/{name}") async def read_clients_by_name( *, name: str = None, session: Session = Depends(get_session) ): """ Get a client by client_name. Parameters ---------- name : str Name of client to be read. session : Session SQL session that is to be used to read a client. Defaults to creating a dependency on the running SQL model session. """ statement = select(Client).where(Client.name == name) result = session.exec(statement).one() return result @router.get("/{client_id}/epics/") async def read_clients_epics( client_id: int = None, session: Session = Depends(get_session) ): """ Get epics from a client_id. Parameters ---------- client_id : int ID of client that is to be used to pull epics from. session : Session SQL session that is to be used to pull the epics. Defaults to creating a dependency on the running SQL model session. """ statement = (
select(Client.id, Client.name, Epic.name)
sqlmodel.select
import asyncio import uuid from typing import List, Optional import pytest from fastapi_users import models from pydantic import UUID4 from sqlmodel import Field, Relationship from fastapi_users_db_sqlmodel import SQLModelBaseOAuthAccount, SQLModelBaseUserDB class User(models.BaseUser): first_name: Optional[str] class UserCreate(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate): pass class UserDB(SQLModelBaseUserDB, User, table=True): class Config: orm_mode = True class UserOAuth(User): pass class UserDBOAuth(SQLModelBaseUserDB, table=True): __tablename__ = "user_oauth" oauth_accounts: List["OAuthAccount"] = Relationship( back_populates="user", sa_relationship_kwargs={"lazy": "joined", "cascade": "all, delete"}, ) class OAuthAccount(SQLModelBaseOAuthAccount, table=True): user_id: UUID4 =
Field(foreign_key="user_oauth.id")
sqlmodel.Field
import asyncio import uuid from typing import List, Optional import pytest from fastapi_users import models from pydantic import UUID4 from sqlmodel import Field, Relationship from fastapi_users_db_sqlmodel import SQLModelBaseOAuthAccount, SQLModelBaseUserDB class User(models.BaseUser): first_name: Optional[str] class UserCreate(models.BaseUserCreate): first_name: Optional[str] class UserUpdate(models.BaseUserUpdate): pass class UserDB(SQLModelBaseUserDB, User, table=True): class Config: orm_mode = True class UserOAuth(User): pass class UserDBOAuth(SQLModelBaseUserDB, table=True): __tablename__ = "user_oauth" oauth_accounts: List["OAuthAccount"] = Relationship( back_populates="user", sa_relationship_kwargs={"lazy": "joined", "cascade": "all, delete"}, ) class OAuthAccount(SQLModelBaseOAuthAccount, table=True): user_id: UUID4 = Field(foreign_key="user_oauth.id") user: Optional[UserDBOAuth] =
Relationship(back_populates="oauth_accounts")
sqlmodel.Relationship
from fastapi import Depends from sqlmodel import select from joj.horse import models, schemas from joj.horse.schemas import StandardListResponse from joj.horse.schemas.auth import Authentication from joj.horse.utils.parser import parse_ordering_query, parse_pagination_query from joj.horse.utils.router import MyRouter router = MyRouter() router_name = "problem_groups" router_tag = "problem group" router_prefix = "/api/v1" @router.get("") async def list_problem_groups( ordering: schemas.OrderingQuery = Depends(parse_ordering_query()), pagination: schemas.PaginationQuery = Depends(parse_pagination_query), auth: Authentication = Depends(), ) -> StandardListResponse[schemas.ProblemGroup]: statement =
select(models.ProblemGroup)
sqlmodel.select
from pathlib import Path import pytest from sqlmodel import select from kfs import db @pytest.fixture() def base_dir(tmp_path: Path) -> Path: return tmp_path @pytest.fixture() def sql_file_path(base_dir: Path) -> Path: return base_dir / "kfs.db" @pytest.fixture() def sqlite_url(sql_file_path: Path) -> str: return f"sqlite:///{sql_file_path}" @pytest.fixture(autouse=True) def database(sqlite_url: str) -> None: db.init(sqlite_url) def test_init(sql_file_path: Path) -> None: """After init, the database has been created and the file exists""" assert sql_file_path.exists() def test_database() -> None: with db.get_session() as session: # Create a new file with a tag tag = db.Tag(category="vendor", value="chevron") file = db.File(name="test_file.csv", path="/some/directory", tags=[tag]) session.add(file) session.commit() with db.get_session() as session: # Retrieve the file from database read_file = session.exec(
select(db.File)
sqlmodel.select
"""Anime CRUD controller.""" import sqlmodel from sqlmodel.ext.asyncio import session as aio_session from app.crud import base from app.models import anime class AnimeCRUD(base.BaseCRUD[anime.Anime, anime.AnimeCreate, anime.AnimeUpdate]): """CRUD controller for anime. It contains Create, Read, Update, and Delete methods. """ @classmethod async def get_by_title(cls, session: aio_session.AsyncSession, title: str) -> anime.Anime | None: """Gets an anime by their title. Args: session: The database session. title: The anime's title. """ anime_list = await session.exec(
sqlmodel.select(anime.Anime)
sqlmodel.select
"""Instancia da tabela User e seus metodos""" from typing import Optional, List, TYPE_CHECKING from datetime import datetime from sqlalchemy import UniqueConstraint from sqlmodel import SQLModel, Field, Relationship if TYPE_CHECKING: from .tokens import Token class User(SQLModel, table=True): """Tabela de usuarios""" __table_args__ = (UniqueConstraint("email", "username"),) id: Optional[int] =
Field(primary_key=True, default=None, nullable=False)
sqlmodel.Field
"""Instancia da tabela User e seus metodos""" from typing import Optional, List, TYPE_CHECKING from datetime import datetime from sqlalchemy import UniqueConstraint from sqlmodel import SQLModel, Field, Relationship if TYPE_CHECKING: from .tokens import Token class User(SQLModel, table=True): """Tabela de usuarios""" __table_args__ = (UniqueConstraint("email", "username"),) id: Optional[int] = Field(primary_key=True, default=None, nullable=False) name: str email: str username: str password_hash: str secundary_id: int = 0 is_staff: bool is_active_user: bool last_login: datetime date_joined: datetime token: List["Token"] =
Relationship(back_populates="user")
sqlmodel.Relationship
from typing import Optional from sqlmodel import Field, SQLModel from pydantic import validator from datetime import datetime import numpy as np class Forecast(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel from pydantic import validator from datetime import datetime import numpy as np class Forecast(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) user_id: int =
Field(foreign_key="app_db.appuser.id")
sqlmodel.Field
from typing import Optional from sqlmodel import Field, SQLModel from pydantic import validator from datetime import datetime import numpy as np class Forecast(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) user_id: int = Field(foreign_key="app_db.appuser.id") epic_id: int =
Field(foreign_key="app_db.epic.id")
sqlmodel.Field
from typing import List, Union from fastapi import APIRouter, Request from fastapi.exceptions import HTTPException from sqlmodel import Session, or_, select from ..db import ActiveSession from ..models.content import Content, ContentIncoming, ContentResponse from ..security import AuthenticatedUser, User, get_current_user router = APIRouter() @router.get("/", response_model=List[ContentResponse]) async def list_contents(*, session: Session = ActiveSession): contents = session.exec(
select(Content)
sqlmodel.select
import os import jwt import time import requests from flask import abort from flask import Blueprint from flask import request from flask import jsonify from flask import redirect from flask import current_app from flask import session from urllib.parse import unquote from base64 import b64encode from datetime import datetime from sqlmodel import select from sqlmodel import Session as SQLSession from app.models.user import User bp = Blueprint("auth", __name__) @bp.route("/login") def login(): CLIENT_ID = current_app.config["CLIENT_ID"] REDIRECT_URI = current_app.config["REDIRECT_URI"] USER_STATE = b64encode(os.urandom(64)).decode("utf-8") UAA_AUTHORIZE_URI = current_app.config["UAA_AUTHORIZE_URI"] session["USER_STATE"] = USER_STATE UAA_LOGIN = f"{UAA_AUTHORIZE_URI}?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&state={USER_STATE}" return redirect(UAA_LOGIN) @bp.route("/logout") def logout(): CLIENT_ID = current_app.config["CLIENT_ID"] REDIRECT_URI = current_app.config["REDIRECT_URI"] UAA_LOGOUT_URI = current_app.config["UAA_LOGOUT_URI"] UAA_LGOUT = f"{UAA_LOGOUT_URI}?client_id={CLIENT_ID}&redirect={REDIRECT_URI}" session.clear() requests.post(UAA_LGOUT) return redirect("/") @bp.route("/callback") def callback(): # @url_param {string} code # @url_param {string} status code = request.args.get("code") state = request.args.get("state") if not code or not state: abort(400) UAA_TOKEN_URI = current_app.config["UAA_TOKEN_URI"] data = { "code": code, "grant_type": "authorization_code", "response_type": "token", "client_id": current_app.config["CLIENT_ID"], "client_secret": current_app.config["CLIENT_SECRET"], "redirect_uri": current_app.config["REDIRECT_URI"], } response = requests.post(UAA_TOKEN_URI, data=data) if response.status_code != 200: abort(response.status_code) response = response.json() token = response["access_token"] header = jwt.get_unverified_header(token) session["claims"] = jwt.decode( token, header["alg"], options={"verify_signature": False} ) session["expiry"] = time.time() + (response["expires_in"] * 1000) session["refresh_token"] = response["refresh_token"] session["authenticated"] = True with
SQLSession(current_app.engine)
sqlmodel.Session
import os import jwt import time import requests from flask import abort from flask import Blueprint from flask import request from flask import jsonify from flask import redirect from flask import current_app from flask import session from urllib.parse import unquote from base64 import b64encode from datetime import datetime from sqlmodel import select from sqlmodel import Session as SQLSession from app.models.user import User bp = Blueprint("auth", __name__) @bp.route("/login") def login(): CLIENT_ID = current_app.config["CLIENT_ID"] REDIRECT_URI = current_app.config["REDIRECT_URI"] USER_STATE = b64encode(os.urandom(64)).decode("utf-8") UAA_AUTHORIZE_URI = current_app.config["UAA_AUTHORIZE_URI"] session["USER_STATE"] = USER_STATE UAA_LOGIN = f"{UAA_AUTHORIZE_URI}?client_id={CLIENT_ID}&response_type=code&redirect_uri={REDIRECT_URI}&state={USER_STATE}" return redirect(UAA_LOGIN) @bp.route("/logout") def logout(): CLIENT_ID = current_app.config["CLIENT_ID"] REDIRECT_URI = current_app.config["REDIRECT_URI"] UAA_LOGOUT_URI = current_app.config["UAA_LOGOUT_URI"] UAA_LGOUT = f"{UAA_LOGOUT_URI}?client_id={CLIENT_ID}&redirect={REDIRECT_URI}" session.clear() requests.post(UAA_LGOUT) return redirect("/") @bp.route("/callback") def callback(): # @url_param {string} code # @url_param {string} status code = request.args.get("code") state = request.args.get("state") if not code or not state: abort(400) UAA_TOKEN_URI = current_app.config["UAA_TOKEN_URI"] data = { "code": code, "grant_type": "authorization_code", "response_type": "token", "client_id": current_app.config["CLIENT_ID"], "client_secret": current_app.config["CLIENT_SECRET"], "redirect_uri": current_app.config["REDIRECT_URI"], } response = requests.post(UAA_TOKEN_URI, data=data) if response.status_code != 200: abort(response.status_code) response = response.json() token = response["access_token"] header = jwt.get_unverified_header(token) session["claims"] = jwt.decode( token, header["alg"], options={"verify_signature": False} ) session["expiry"] = time.time() + (response["expires_in"] * 1000) session["refresh_token"] = response["refresh_token"] session["authenticated"] = True with SQLSession(current_app.engine) as s: query =
select(User)
sqlmodel.select
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None def main(): hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Spider-Boy", secret_name="<NAME>") hero_3 = Hero(name="Rusty-Man", secret_name="<NAME>", age=48) host_name = "postgres" if os.environ.get("IS_INSIDE_DOCKER") else "localhost" url = URL.create(drivername="postgresql", username="postgres", password="<PASSWORD>", host=host_name, port=5432) engine =
create_engine(url)
sqlmodel.create_engine
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None def main(): hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Spider-Boy", secret_name="<NAME>") hero_3 = Hero(name="Rusty-Man", secret_name="<NAME>", age=48) host_name = "postgres" if os.environ.get("IS_INSIDE_DOCKER") else "localhost" url = URL.create(drivername="postgresql", username="postgres", password="<PASSWORD>", host=host_name, port=5432) engine = create_engine(url) for _ in range(5): try: SQLModel.metadata.create_all(engine) break except OperationalError: logger.error("Is postgres database running?") time.sleep(2) with
Session(engine)
sqlmodel.Session
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None def main(): hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Spider-Boy", secret_name="<NAME>") hero_3 = Hero(name="Rusty-Man", secret_name="<NAME>", age=48) host_name = "postgres" if os.environ.get("IS_INSIDE_DOCKER") else "localhost" url = URL.create(drivername="postgresql", username="postgres", password="<PASSWORD>", host=host_name, port=5432) engine = create_engine(url) for _ in range(5): try: SQLModel.metadata.create_all(engine) break except OperationalError: logger.error("Is postgres database running?") time.sleep(2) with Session(engine) as session: session.add_all([hero_1, hero_2]) session.add(hero_3) session.commit() with
Session(engine)
sqlmodel.Session
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None def main(): hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Spider-Boy", secret_name="<NAME>") hero_3 = Hero(name="Rusty-Man", secret_name="<NAME>", age=48) host_name = "postgres" if os.environ.get("IS_INSIDE_DOCKER") else "localhost" url = URL.create(drivername="postgresql", username="postgres", password="<PASSWORD>", host=host_name, port=5432) engine = create_engine(url) for _ in range(5): try:
SQLModel.metadata.create_all(engine)
sqlmodel.SQLModel.metadata.create_all
import time import os from typing import Optional from sqlalchemy.exc import OperationalError from sqlalchemy.engine import URL from sqlmodel import Field, Session, SQLModel, create_engine, select from loguru import logger class Hero(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str secret_name: str age: Optional[int] = None def main(): hero_1 = Hero(name="Deadpond", secret_name="<NAME>") hero_2 = Hero(name="Spider-Boy", secret_name="<NAME>") hero_3 = Hero(name="Rusty-Man", secret_name="<NAME>", age=48) host_name = "postgres" if os.environ.get("IS_INSIDE_DOCKER") else "localhost" url = URL.create(drivername="postgresql", username="postgres", password="<PASSWORD>", host=host_name, port=5432) engine = create_engine(url) for _ in range(5): try: SQLModel.metadata.create_all(engine) break except OperationalError: logger.error("Is postgres database running?") time.sleep(2) with Session(engine) as session: session.add_all([hero_1, hero_2]) session.add(hero_3) session.commit() with Session(engine) as session: statement =
select(Hero)
sqlmodel.select
from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ..db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class Procedure(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ..db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class Procedure(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_group_id: int parent_procedure_id: int name: str detail: str icd_9: str icd_10: str class ProcedureGroup(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ..db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class Procedure(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_group_id: int parent_procedure_id: int name: str detail: str icd_9: str icd_10: str class ProcedureGroup(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProcedureDiseaseMap(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ..db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class Procedure(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_group_id: int parent_procedure_id: int name: str detail: str icd_9: str icd_10: str class ProcedureGroup(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProcedureDiseaseMap(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_id: int disease_id: bool require: bool age_min: float age_max: float class HistoryProcedure(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
from datetime import datetime from typing import Optional from fastapi import APIRouter, Depends from sqlmodel import Field, SQLModel from ..db import get_session from sqlalchemy import select from sqlalchemy.ext.asyncio import AsyncSession router = APIRouter() class Procedure(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_group_id: int parent_procedure_id: int name: str detail: str icd_9: str icd_10: str class ProcedureGroup(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) name: str class ProcedureDiseaseMap(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) procedure_id: int disease_id: bool require: bool age_min: float age_max: float class HistoryProcedure(SQLModel, table=True): id: Optional[int] = Field(default=None, primary_key=True) history_id: int procedure_id: int detail: str created_at: datetime updated_at: datetime created_by: int updated_by: Optional[int] = None class HistoryProcedureDoctorMap(SQLModel, table=True): id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field
import asyncio import pytest from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.ext.asyncio.engine import AsyncConnection from sqlmodel.ext.asyncio.session import AsyncSession from basesqlmodel import Base engine = create_async_engine("sqlite+aiosqlite:///:memory:") @pytest.fixture() async def connection() -> AsyncConnection: async with engine.begin() as conn: yield conn await conn.rollback() @pytest.fixture() async def session(connection: AsyncConnection): async with
AsyncSession(connection, expire_on_commit=False)
sqlmodel.ext.asyncio.session.AsyncSession
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("graduation_year", sa.Integer(), nullable=False), sa.Column("major",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("graduation_year", sa.Integer(), nullable=False), sa.Column("major", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("date_of_birth",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("graduation_year", sa.Integer(), nullable=False), sa.Column("major", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("date_of_birth", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("hackathons_attended", sa.Integer(), nullable=False), sa.Column("portfolio_url",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("graduation_year", sa.Integer(), nullable=False), sa.Column("major", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("date_of_birth", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("hackathons_attended", sa.Integer(), nullable=False), sa.Column("portfolio_url", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("vcs_url",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
"""Add participant and application Revision ID: 58d2280520b8 Revises: Create Date: 2022-02-12 07:30:30.427270+00:00 """ import sqlalchemy as sa import sqlmodel from alembic import op # revision identifiers, used by Alembic. revision = "58d2280520b8" down_revision = None branch_labels = None depends_on = None def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "participants", sa.Column("first_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("last_name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("id", sa.Integer(), nullable=False), sa.PrimaryKeyConstraint("id"), ) op.create_table( "applications", sa.Column( "gender", sa.Enum("MALE", "FEMALE", "NON_BINARY", name="gender"), nullable=True, ), sa.Column( "race_ethnicity", sa.Enum( "AMERICAN_INDIAN", "ASIAN", "PACIFIC_ISLANDER", "BLACK", "HISPANIC", "CAUCASIAN", "MULTIPLE_OTHER", name="raceethnicity", ), nullable=True, ), sa.Column("participant_id", sa.Integer(), nullable=False), sa.Column("level_of_study", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("graduation_year", sa.Integer(), nullable=False), sa.Column("major", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("date_of_birth", sqlmodel.sql.sqltypes.AutoString(), nullable=False), sa.Column("hackathons_attended", sa.Integer(), nullable=False), sa.Column("portfolio_url", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column("vcs_url", sqlmodel.sql.sqltypes.AutoString(), nullable=True), sa.Column( "shipping_address",
sqlmodel.sql.sqltypes.AutoString()
sqlmodel.sql.sqltypes.AutoString
import traceback from contextlib import contextmanager from sqlmodel import create_engine, Session from fastapi_dream_core.application_dependencies.application_dependencies_abc import ApplicationDependenciesABC from fastapi_dream_core.utils import logger class DatabaseSQLModel(ApplicationDependenciesABC): def __init__(self, db_url: str, echo_queries: bool = False) -> None: self._engine =
create_engine(db_url, echo=echo_queries)
sqlmodel.create_engine
import traceback from contextlib import contextmanager from sqlmodel import create_engine, Session from fastapi_dream_core.application_dependencies.application_dependencies_abc import ApplicationDependenciesABC from fastapi_dream_core.utils import logger class DatabaseSQLModel(ApplicationDependenciesABC): def __init__(self, db_url: str, echo_queries: bool = False) -> None: self._engine = create_engine(db_url, echo=echo_queries) def readiness(self) -> bool: with
Session(self._engine)
sqlmodel.Session
import traceback from contextlib import contextmanager from sqlmodel import create_engine, Session from fastapi_dream_core.application_dependencies.application_dependencies_abc import ApplicationDependenciesABC from fastapi_dream_core.utils import logger class DatabaseSQLModel(ApplicationDependenciesABC): def __init__(self, db_url: str, echo_queries: bool = False) -> None: self._engine = create_engine(db_url, echo=echo_queries) def readiness(self) -> bool: with Session(self._engine) as session: try: database_status = session.connection().connection.is_valid logger.debug(f"DatabaseSQLModel.readiness = {database_status}") return True except Exception: traceback.print_exc() return False @contextmanager def session(self) -> Session: with
Session(self._engine)
sqlmodel.Session
from typing import Optional from sqlmodel import Field, SQLModel from datetime import datetime class Capacity(SQLModel, table=True): """Create an SQLModel for capcities""" id: Optional[int] =
Field(default=None, primary_key=True)
sqlmodel.Field