Beispiel #1
0
def create_social(fb: int, ig: int, tw: int, sp: int, yt: int):
    dt_now = datetime.now().strftime("%Y%m%d_%H%M%S")
    logging.info(f"INSERT social row ({dt_now},{fb},{ig},{tw},{sp},{yt})")
    social_row = Social(dt=dt_now, fb=fb, ig=ig, tw=tw, sp=sp, yt=yt)
    with Session(engine) as session:
        session.add(social_row)
        session.commit()
Beispiel #2
0
def download(
    ctx,
    path,
    onshape_access_key,
    onshape_secret_key,
    page_uid=None,
):
    create_db_and_tables()
    session = Session(engine)

    mkdocs_config = ctx.obj["mkdocs_config"]
    plugin = mkdocs_config["plugins"]["eva-3d-plugin"]
    downloader = Downloader(onshape_access_key, onshape_secret_key)

    pages = plugin.pages

    if page_uid:
        pages = [page for page in pages if page.meta.onshape.uid == page_uid]

    if path:
        pages = [
            page for page in pages if Path(path) in Path(page.file.src_path).parents
        ]

    results = asyncio.run(download_all(session, downloader, pages))
    result = results[0]
Beispiel #3
0
def check_party_timeout():
    with Session(engine) as db_session:
        # Get parties that are not locked and have timed out
        parties = crud_party.get_multi(
            db_session,
            limit=crud_party.get_count(db_session),
            filters={
                "end_time__le": datetime.datetime.now(),
                "locked": False
            },
        )

        for party in parties:
            webhook_data = {
                "party": party,
                "event": {
                    "name": "on_party_timed_out"
                }
            }
            webhook = schemas.PartyTimedoutWebhook.parse_obj(webhook_data)

            # Send timeout webhook
            send_webhook.delay("http://bot:9080/webhook", webhook.json())

            # Lock party
            crud_party.lock(db_session, db_obj=party)
Beispiel #4
0
def get_previous_social() -> Social:
    with Session(engine) as session:
        statement = select(Social).order_by(
            Social.id.desc()).offset(1).limit(1)
        result = session.exec(statement).one_or_none()
    logging.info(f"SELECT previous social row: {result}")
    return result
Beispiel #5
0
 def set_posting_as_sent(self, sha: str):
     with Session(engine) as session:
         statement = select(Posting).where(Posting.sha == sha)
         posting = session.exec(statement).first()
         posting.sent = True
         session.add(posting)
         session.commit()
Beispiel #6
0
def session_fixture() -> Generator:
    # use an in-memory database for testing
    engine = create_engine("sqlite://",
                           connect_args={"check_same_thread": False},
                           poolclass=StaticPool)
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session
Beispiel #7
0
def create_app(idade: int, nome: str):
    person = Person(nome=nome, idade=idade)

    with Session(engine) as session:
        session.add(person)
        session.commit()
        session.refresh(person)

    return person
def session_scope() -> Session:
    """Provide a transactional scope around a series of operations."""
    db = None
    try:
        db = Session(autocommit=False, autoflush=False,
                     bind=engine)  # create session from SQLModel session
        yield db
    finally:
        db.close()
Beispiel #9
0
 def update_by_id(cls, id, set):
     user = cls.get_by_id(id)
     with Session(engine) as session:
         for k, v in set.items():
             user[k] = v
         session.add(user)
         session.commit()
         session.refresh(user)
     return user
Beispiel #10
0
def select_heroes():
    with Session(engine) as session:
        heroes = session.exec(
            select(Hero).where(
                or_(col(Hero.name) == "Black Lion",
                    col(Hero.age) == 25))
            #   .where(Hero.age == 48)
        ).all()
        print(heroes)
Beispiel #11
0
def session_fixture():
    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(engine)
    with Session(engine) as session:
        yield session
Beispiel #12
0
def main():
    engine = create_engine("sqlite://", echo=True)
    SQLModel.metadata.create_all(engine)

    with Session(engine) as session:
        note = Note(text="The quick brown fox jumps over the lazy dog")
        session.add(note)
        session.commit()

        # https://stackoverflow.com/a/5083472
        session.refresh(note)
        note_id = note.id

    with Session(engine) as session:
        result = session.exec(select(Note).where(Note.id == note_id))
        note = result.one()

    print("")
    print("The note added:", note)
def select_heroes():
    with Session(engine) as session:
        statement = select(Team).where(Team.name == "Preventers")
        result = session.exec(statement)
        team_preventers = result.one()

        print("Preventers heroes:", team_preventers.heroes)
        team_new = TeamCapability(**team_preventers.dict())
        team_new.capability = mode
        print(team_new)
Beispiel #14
0
def create_user(telegram_id: int,
                username: str = None,
                first_name: str = None,
                last_name: str = None):
    logging.info(f"INSERT user: {first_name}")
    user_row = User(telegram_id=telegram_id,
                    username=username,
                    first_name=first_name,
                    last_name=last_name)
    with Session(engine) as session:
        session.add(user_row)
        session.commit()
Beispiel #15
0
def update_hero(hero_id: int, hero: HeroUpdate):
    with Session(engine) as session:
        db_hero = session.get(Hero, hero_id)
        if not db_hero:
            raise HTTPException(status_code=404, detail="Hero not found")
        hero_data = hero.dict(exclude_unset=True)
        for key, value in hero_data.items():
            setattr(db_hero, key, value)
        session.add(db_hero)
        session.commit()
        session.refresh(db_hero)
        return db_hero
Beispiel #16
0
def session_fixture():
    engine = create_engine(
        "sqlite://",
        connect_args={"check_same_thread": False},
        poolclass=StaticPool,
    )
    SQLModel.metadata.create_all(bind=engine)
    with Session(engine) as db:

        test_player = (db.query(models.Player).filter(
            models.Player.discord_id == "1234567890").first())

        if not test_player:
            test_player = models.Player(discord_id="1234567890",
                                        name="TEST PLAYER 1",
                                        discriminator="0001")
            db.add(test_player)
            db.commit()
            db.refresh(test_player)

    with Session(engine) as session:
        yield session
Beispiel #17
0
def load_csv_bom(bom_name, csv_file):
    create_db_and_tables()
    session = Session(engine)
    remove_page_bom(session, bom_name)
    bom_table = BOMTable(name=bom_name)

    for row in csv.DictReader(csv_file, delimiter=",", quotechar='"'):
        session.add(
            BOMItem(
                name=row["Name"],
                material=row["Material"],
                quantity=row["Quantity"],
                bom_table=bom_table,
            )
        )
    session.commit()
Beispiel #18
0
def create_heroes():
    '''Add Hero instances to memory and commit through a session transaction.'''
    heroes = [
        Hero(name="Deadpond", secret_name="Dive Wilson", age=40),
        Hero(name="Spider-Boy", secret_name="Pedro Parqueador", age=25),
        Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48),
        Hero(name="Tarantula", secret_name="Natalia Roman-on", age=32),
        Hero(name="Black Lion", secret_name="Trevor Challa", age=35),
        Hero(name="Dr. Weird", secret_name="Steve Weird", age=36),
        Hero(name="Captain NA", secret_name="Esteban Rogelios", age=93)
    ]

    with Session(engine) as session:
        for hero in heroes:
            session.add(hero)
        session.commit()
Beispiel #19
0
def create_plants():
    plant_1 = Plant(name="Hebe")
    plant_2 = Plant(name="Astilbe")
    plant_3 = Plant(name="Sedum")
    plant_4 = Plant(name="Helenium")
    plant_5 = Plant(name="Heather")

    session = Session(engine)

    session.add(plant_1)
    session.add(plant_2)
    session.add(plant_3)
    session.add(plant_4)
    session.add(plant_5)

    session.commit()

    session.close()
Beispiel #20
0
    def on_config(self, config):
        self.context = {}
        config["version"] = self.config["version"]
        self.session = Session(db.engine)
        db.create_db_and_tables()
        self.pages = []
        self.env = config["theme"].get_env()
        self.env.filters["b64encode"] = escapeb64
        self.env.filters["bom_json"] = self.bom_json
        self.env.filters["md_table"] = self.md_table
        self.env.filters["yes_no"] = self.yes_no
        self.env.filters["slugify"] = slugify

        try:
            config["meta_model_class"] = import_string(self.config["meta_model_class"])
        except ImportError as exc:
            raise PluginError(
                f"Meta Model Class {self.config['meta_model_class']} could not be imported. {exc}"
            ) from exc

        return config
Beispiel #21
0
 def get_session(self) -> Session:
     return Session(self.engine)
Beispiel #22
0
def get_session():  # pragma: no cover
    with Session(engine) as session:
        yield session
Beispiel #23
0
def get_session():
    engine = create_engine(sqlite_url,
                           connect_args={"check_same_thread": False})
    with Session(engine) as session:
        yield session
Beispiel #24
0
def get_pessoa():
    query = select(Pessoa.nome, Pessoa.idade)
    with Session(engine) as session:
        result = session.execute(query).scalars().all()

    return result
Beispiel #25
0
def get_db():
    with Session(engine) as session:
        yield session
Beispiel #26
0
def read_hero(hero_id: int):
    with Session(engine) as session:
        hero = session.get(Hero, hero_id)
        if not hero:
            raise HTTPException(status_code=404, detail="Hero not found")
        return hero
Beispiel #27
0
def read_heroes():
    with Session(engine) as session:
        heroes = session.exec(select(Hero)).all()
        return heroes
Beispiel #28
0
def create_hero(hero: HeroCreate):
    with Session(engine) as session:
        session.add(hero)
        session.commit()
        session.refresh(hero)
        return hero
Beispiel #29
0
    def all_pessoa(self) -> list[Pessoa]:
        query = select(Person)
        with Session(engine) as session:
            result = session.execute(query).scalars().all()

        return result
Beispiel #30
0
from typing import Optional
from sqlmodel import Field, SQLModel
from sqlmodel import create_engine, Session, select


class Hero(SQLModel, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    name: str
    secret_name: str
    age: Optional[int] = None


hero1 = Hero(name="Deadpond", secret_name="Dive Wilson")
hero2 = Hero(name="Spider-Bod", secret_name="Pedro Parqueador")
hero3 = Hero(name="Rusty-Man", secret_name="Tommy Sharp", age=48)

engine = create_engine("sqlite:///database.db", echo=True)
SQLModel.metadata.create_all(engine)

with Session(engine) as session:
    session.add(hero1)
    session.add(hero2)
    session.add(hero3)
    session.commit()

with Session(engine) as session:
    stmt = select(Hero).where(Hero.name == "Spider-Bod")
    hero = session.exec(stmt).first()
    print(hero.name)