prompt
stringlengths 45
17.8k
| completion
stringlengths 6
107
| api
stringlengths 12
42
|
---|---|---|
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task)).one()
task = query.task
status = query.status
assert result.exit_code == 0
assert task == task
assert status == 'to do'
def test_add_status():
"""Test status"""
task = 'Test status'
status = 'dif'
result = runner.invoke(app, ['add', task, '--status', status])
assert result.exit_code == 1
assert 'status must be "to do" or "doing"\n' in result.stdout
def test_add_due_date():
"""Test due date"""
task = 'Test due date'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--due-date', date])
assert result.exit_code == 1
assert f'due date must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_reminder():
"""Test reminder"""
task = 'Test reminder'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', date])
assert result.exit_code == 1
assert f'reminder must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_due_date_reminder():
"""Test due-date and reminder"""
task = 'Test due-date and reminder'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', reminder,
'--due-date', due_date])
assert result.exit_code == 1
assert f'reminder must be smaller than {due_date}\n' in \
result.stdout
def test_add_full_entry():
"""Test add full task"""
task = 'something'
project = 'test project'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=1), '%Y-%m-%d')
status = 'doing'
tag = 'tag'
result = runner.invoke(app, ['add', task,
'--project', project,
'--due-date', due_date,
'--reminder', reminder,
'--status', status,
'--tag', tag])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task,
ToDo.project == project,
ToDo.status == status,
ToDo.tag == tag)).one()
assert query is not None
def test_start():
"""Test start"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo.status).where(ToDo.id ==
todo_id)).one()
assert query == 'doing'
def test_start_running():
"""Test start when running"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 1
assert 'The Timer must be stopped first' in result.stdout
def test_stop():
"""Test stop"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 0
def test_stop_no_run():
"""Test stop with no run"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 1
def test_duration():
"""test duration"""
todo_id = 1
with | Session(engine) | sqlmodel.Session |
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec( | select(ToDo) | sqlmodel.select |
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task)).one()
task = query.task
status = query.status
assert result.exit_code == 0
assert task == task
assert status == 'to do'
def test_add_status():
"""Test status"""
task = 'Test status'
status = 'dif'
result = runner.invoke(app, ['add', task, '--status', status])
assert result.exit_code == 1
assert 'status must be "to do" or "doing"\n' in result.stdout
def test_add_due_date():
"""Test due date"""
task = 'Test due date'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--due-date', date])
assert result.exit_code == 1
assert f'due date must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_reminder():
"""Test reminder"""
task = 'Test reminder'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', date])
assert result.exit_code == 1
assert f'reminder must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_due_date_reminder():
"""Test due-date and reminder"""
task = 'Test due-date and reminder'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', reminder,
'--due-date', due_date])
assert result.exit_code == 1
assert f'reminder must be smaller than {due_date}\n' in \
result.stdout
def test_add_full_entry():
"""Test add full task"""
task = 'something'
project = 'test project'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=1), '%Y-%m-%d')
status = 'doing'
tag = 'tag'
result = runner.invoke(app, ['add', task,
'--project', project,
'--due-date', due_date,
'--reminder', reminder,
'--status', status,
'--tag', tag])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec( | select(ToDo) | sqlmodel.select |
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task)).one()
task = query.task
status = query.status
assert result.exit_code == 0
assert task == task
assert status == 'to do'
def test_add_status():
"""Test status"""
task = 'Test status'
status = 'dif'
result = runner.invoke(app, ['add', task, '--status', status])
assert result.exit_code == 1
assert 'status must be "to do" or "doing"\n' in result.stdout
def test_add_due_date():
"""Test due date"""
task = 'Test due date'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--due-date', date])
assert result.exit_code == 1
assert f'due date must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_reminder():
"""Test reminder"""
task = 'Test reminder'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', date])
assert result.exit_code == 1
assert f'reminder must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_due_date_reminder():
"""Test due-date and reminder"""
task = 'Test due-date and reminder'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', reminder,
'--due-date', due_date])
assert result.exit_code == 1
assert f'reminder must be smaller than {due_date}\n' in \
result.stdout
def test_add_full_entry():
"""Test add full task"""
task = 'something'
project = 'test project'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=1), '%Y-%m-%d')
status = 'doing'
tag = 'tag'
result = runner.invoke(app, ['add', task,
'--project', project,
'--due-date', due_date,
'--reminder', reminder,
'--status', status,
'--tag', tag])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task,
ToDo.project == project,
ToDo.status == status,
ToDo.tag == tag)).one()
assert query is not None
def test_start():
"""Test start"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec( | select(ToDo.status) | sqlmodel.select |
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task)).one()
task = query.task
status = query.status
assert result.exit_code == 0
assert task == task
assert status == 'to do'
def test_add_status():
"""Test status"""
task = 'Test status'
status = 'dif'
result = runner.invoke(app, ['add', task, '--status', status])
assert result.exit_code == 1
assert 'status must be "to do" or "doing"\n' in result.stdout
def test_add_due_date():
"""Test due date"""
task = 'Test due date'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--due-date', date])
assert result.exit_code == 1
assert f'due date must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_reminder():
"""Test reminder"""
task = 'Test reminder'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', date])
assert result.exit_code == 1
assert f'reminder must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_due_date_reminder():
"""Test due-date and reminder"""
task = 'Test due-date and reminder'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', reminder,
'--due-date', due_date])
assert result.exit_code == 1
assert f'reminder must be smaller than {due_date}\n' in \
result.stdout
def test_add_full_entry():
"""Test add full task"""
task = 'something'
project = 'test project'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=1), '%Y-%m-%d')
status = 'doing'
tag = 'tag'
result = runner.invoke(app, ['add', task,
'--project', project,
'--due-date', due_date,
'--reminder', reminder,
'--status', status,
'--tag', tag])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task,
ToDo.project == project,
ToDo.status == status,
ToDo.tag == tag)).one()
assert query is not None
def test_start():
"""Test start"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo.status).where(ToDo.id ==
todo_id)).one()
assert query == 'doing'
def test_start_running():
"""Test start when running"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 1
assert 'The Timer must be stopped first' in result.stdout
def test_stop():
"""Test stop"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 0
def test_stop_no_run():
"""Test stop with no run"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 1
def test_duration():
"""test duration"""
todo_id = 1
with Session(engine) as session:
todo = session.exec( | select(ToDo.duration) | sqlmodel.select |
from typer.testing import CliRunner
import os
from timerdo.main import app, sqlite_file_name
from timerdo.tables import ToDo, Timer
from sqlmodel import create_engine, Session, select
from datetime import datetime, timedelta
try:
os.rename('/home/cmts/.config/timerdo/timerdo_db.db',
'/home/cmts/.config/timerdo/timerdo_db_moved.db')
except FileNotFoundError:
pass
sqlite_url = f'sqlite:///{sqlite_file_name}'
engine = create_engine(sqlite_url, echo=True)
runner = CliRunner()
def test_add_none():
"""Test add function with no argument"""
result = runner.invoke(app, ['add'])
assert result.exit_code == 2
def test_add_task():
"""Test add function with task argument"""
task = 'test add'
result = runner.invoke(app, ['add', task])
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task)).one()
task = query.task
status = query.status
assert result.exit_code == 0
assert task == task
assert status == 'to do'
def test_add_status():
"""Test status"""
task = 'Test status'
status = 'dif'
result = runner.invoke(app, ['add', task, '--status', status])
assert result.exit_code == 1
assert 'status must be "to do" or "doing"\n' in result.stdout
def test_add_due_date():
"""Test due date"""
task = 'Test due date'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--due-date', date])
assert result.exit_code == 1
assert f'due date must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_reminder():
"""Test reminder"""
task = 'Test reminder'
date = datetime.strftime(datetime.now(), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', date])
assert result.exit_code == 1
assert f'reminder must be grater than {datetime.today().date()}\n' in \
result.stdout
def test_add_due_date_reminder():
"""Test due-date and reminder"""
task = 'Test due-date and reminder'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
result = runner.invoke(app, ['add', task, '--reminder', reminder,
'--due-date', due_date])
assert result.exit_code == 1
assert f'reminder must be smaller than {due_date}\n' in \
result.stdout
def test_add_full_entry():
"""Test add full task"""
task = 'something'
project = 'test project'
due_date = datetime.strftime(
datetime.now() + timedelta(days=2), '%Y-%m-%d')
reminder = datetime.strftime(
datetime.now() + timedelta(days=1), '%Y-%m-%d')
status = 'doing'
tag = 'tag'
result = runner.invoke(app, ['add', task,
'--project', project,
'--due-date', due_date,
'--reminder', reminder,
'--status', status,
'--tag', tag])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo).where(ToDo.task == task,
ToDo.project == project,
ToDo.status == status,
ToDo.tag == tag)).one()
assert query is not None
def test_start():
"""Test start"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 0
with Session(engine) as session:
query = session.exec(select(ToDo.status).where(ToDo.id ==
todo_id)).one()
assert query == 'doing'
def test_start_running():
"""Test start when running"""
todo_id = '1'
result = runner.invoke(app, ['start', todo_id])
assert result.exit_code == 1
assert 'The Timer must be stopped first' in result.stdout
def test_stop():
"""Test stop"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 0
def test_stop_no_run():
"""Test stop with no run"""
result = runner.invoke(app, ['stop'])
assert result.exit_code == 1
def test_duration():
"""test duration"""
todo_id = 1
with Session(engine) as session:
todo = session.exec(select(ToDo.duration).where(ToDo.id ==
todo_id)).one()
timer = session.exec( | select(Timer.duration) | sqlmodel.select |
from pathlib import Path
from typing import List
import nonebot
import pytest
from nonebug import App
from .utils import make_fake_event, make_fake_message
@pytest.mark.asyncio
async def test_db(app: App):
"""测试数据库"""
from sqlmodel import select
from nonebot_plugin_datastore.db import create_session, init_db
from .example import Example, test
nonebot.load_plugin("tests.example")
await init_db()
async with create_session() as session:
session.add(Example(message="test"))
await session.commit()
async with create_session() as session:
statement = | select(Example) | sqlmodel.select |
from pathlib import Path
from typing import List
import nonebot
import pytest
from nonebug import App
from .utils import make_fake_event, make_fake_message
@pytest.mark.asyncio
async def test_db(app: App):
"""测试数据库"""
from sqlmodel import select
from nonebot_plugin_datastore.db import create_session, init_db
from .example import Example, test
nonebot.load_plugin("tests.example")
await init_db()
async with create_session() as session:
session.add(Example(message="test"))
await session.commit()
async with create_session() as session:
statement = select(Example)
examples: List[Example] = (await session.exec(statement)).all() # type: ignore
assert len(examples) == 1
assert examples[0].message == "test"
message = make_fake_message()("/test")
event = make_fake_event(_message=message)()
async with app.test_matcher(test) as ctx:
bot = ctx.create_bot()
ctx.receive_event(bot, event)
async with create_session() as session:
statement = | select(Example) | sqlmodel.select |
from datetime import timedelta
from enum import Enum
from tkinter import *
from tkinter import ttk
import typer
from sqlmodel import Session
class Status(str, Enum):
"""Status"""
to_do = 'to do'
doing = 'doing'
done = 'done'
def round_timedelta(delta: timedelta):
"""round timedelta object"""
seconds = round(delta.total_seconds())
if seconds >= 3600:
hours = round(seconds/3600)
seconds += - hours*3600
else:
hours = 0
if seconds >= 60:
minutes = round(seconds/60)
seconds += - minutes * 60
else:
minutes = 0
if hours < 10:
hours = '0' + str(hours)
if minutes < 10:
minutes = '0' + str(minutes)
return f'{hours}:{minutes}'
def list_query(engine, query):
"""Calculate duration of a task"""
with | Session(engine) | sqlmodel.Session |
from fastapi import *
from sqlmodel import Session, select, SQLModel
from sqlalchemy.exc import OperationalError
from backend.models.timelog import TimeLog
from backend.models.calendar import Calendar
from backend.utils import (
engine,
sqlite3_engine,
create_db,
tags_metadata,
execute_sample_sql,
)
from backend.api import (
user,
timelog,
forecast,
epic,
epic_area,
client,
rate,
team,
role,
sponsor,
capacity,
demand,
)
import csv
app = FastAPI(title="timeflow app API", openapi_tags=tags_metadata)
session = | Session(engine) | sqlmodel.Session |
from fastapi import *
from sqlmodel import Session, select, SQLModel
from sqlalchemy.exc import OperationalError
from backend.models.timelog import TimeLog
from backend.models.calendar import Calendar
from backend.utils import (
engine,
sqlite3_engine,
create_db,
tags_metadata,
execute_sample_sql,
)
from backend.api import (
user,
timelog,
forecast,
epic,
epic_area,
client,
rate,
team,
role,
sponsor,
capacity,
demand,
)
import csv
app = FastAPI(title="timeflow app API", openapi_tags=tags_metadata)
session = Session(engine)
app.include_router(timelog.router)
app.include_router(forecast.router)
app.include_router(user.router)
app.include_router(epic.router)
app.include_router(epic_area.router)
app.include_router(client.router)
app.include_router(rate.router)
app.include_router(team.router)
app.include_router(role.router)
app.include_router(sponsor.router)
app.include_router(capacity.router)
app.include_router(demand.router)
@app.on_event("startup")
def on_startup():
try:
statement = | select(TimeLog) | sqlmodel.select |
from fastapi import *
from sqlmodel import Session, select, SQLModel
from sqlalchemy.exc import OperationalError
from backend.models.timelog import TimeLog
from backend.models.calendar import Calendar
from backend.utils import (
engine,
sqlite3_engine,
create_db,
tags_metadata,
execute_sample_sql,
)
from backend.api import (
user,
timelog,
forecast,
epic,
epic_area,
client,
rate,
team,
role,
sponsor,
capacity,
demand,
)
import csv
app = FastAPI(title="timeflow app API", openapi_tags=tags_metadata)
session = Session(engine)
app.include_router(timelog.router)
app.include_router(forecast.router)
app.include_router(user.router)
app.include_router(epic.router)
app.include_router(epic_area.router)
app.include_router(client.router)
app.include_router(rate.router)
app.include_router(team.router)
app.include_router(role.router)
app.include_router(sponsor.router)
app.include_router(capacity.router)
app.include_router(demand.router)
@app.on_event("startup")
def on_startup():
try:
statement = select(TimeLog)
results = session.exec(statement)
except OperationalError:
create_db()
execute_sample_sql(session)
@app.on_event("startup")
def implement_calendar_table():
try:
statement = | select(Calendar.year_name) | sqlmodel.select |
"""
Database related APIs.
"""
import logging
from typing import List
from fastapi import APIRouter, Depends
from sqlmodel import Session, select
from datajunction.models.database import Database
from datajunction.utils import get_session
_logger = logging.getLogger(__name__)
router = APIRouter()
@router.get("/databases/", response_model=List[Database])
def read_databases(*, session: Session = Depends(get_session)) -> List[Database]:
"""
List the available databases.
"""
return session.exec( | select(Database) | sqlmodel.select |
import json
from sfm.utils import validate_signature, calc_signature
from sfm.dependencies import get_db
from sfm.models import WorkItemCreate, Project, CommitCreate, WorkItem, WorkItemUpdate
from typing import List, Optional
from sqlmodel import Session, select, and_
from fastapi import APIRouter, HTTPException, Depends, Path, Header, Request, Query
from opencensus.ext.azure.log_exporter import AzureLogHandler
from sfm.config import get_settings
from sfm.logger import create_logger
from .github_functions import (
webhook_project_processor,
deployment_processor,
pull_request_processor,
populate_past_github,
defect_processor,
reopened_processor,
unlabeled_processor,
)
app_settings = get_settings()
logger = create_logger(__name__)
router = APIRouter()
def fetch_github_payload(request):
raw = request.body()
signature = request.headers.get("X-Hub-Signature-256")
proj_auth_token = validate_signature(signature, raw)
payload = request.json()
event_type = request.headers.get("X-Github-Event")
return payload, event_type, proj_auth_token
@router.post("/github_webhooks/") # pragma: no cover
async def webhook_handler(request: Request, db: Session = Depends(get_db)):
"""
## Github Webhook Handler
Awaits incoming payload from Github Webhooks and parses the data.
Currently, endpoint processes two different event types: "Deployment" and "Pull Request".
The payload data is parsed and data needed to calculate the DORA metrics is stored in the db tables.
"""
if app_settings.GITHUB_WEBHOOK_SECRET in ["", "XXXXXXXXXXX"]:
raise HTTPException(
status_code=412,
detail="Missing github webhook secret. Please specify GITHUB_WEBHOOK_SECRET and try again",
)
# if app_settings.ENV != "test":
payload, event_type, proj_auth_token = fetch_github_payload(request)
# gather common payload object properties
if event_type != "push": # push events are the exception to common properties
repository = payload.get("repository")
else: # TODO: pull in push event information
pass
if event_type != "repository":
project_name = repository.get("name")
print("THE PROJECT NAME: ", project_name)
project_db = db.exec(
select(Project).where(Project.name == project_name)
).first()
if not project_db:
logger.debug("A matching project was not found in the database")
raise HTTPException(
status_code=404, detail="Matching project not found in db"
)
if event_type == "repository":
action = payload.get("action")
webhook_project_processor(db, repository, action)
elif event_type == "deployment":
deployment = payload.get("deployment")
deployment_processor(db, deployment, project_db, proj_auth_token)
elif event_type == "pull_request":
pull_request = payload.get("pull_request")
if (
pull_request["head"]["repo"]["default_branch"] == "main"
): # process only pull requests to main
pull_request_processor(db, pull_request, project_db, proj_auth_token)
elif event_type == "issues":
action = payload.get("action")
issue = payload.get("issue")
if action == "closed":
defect_processor(db, issue, project_db, proj_auth_token, closed=True)
elif action == "labeled" and "production defect" in [
lbl["name"] for lbl in issue["labels"]
]:
defect_processor(db, issue, project_db, proj_auth_token, closed=False)
elif action == "reopened":
reopened_processor(db, issue, proj_auth_token)
elif action == "unlabeled" and "production defect" not in [
lbl["name"] for lbl in issue["labels"]
]:
unlabeled_processor(db, issue, proj_auth_token)
else:
logger.debug("Issues event type passed that is unhandled")
else:
logger.warning("Event type not handled")
return {"code": "event type not handled"}
# raise HTTPException(status_code=404, detail="Event type not handled.")
return {"code": "success"}
@router.get("/github_populate")
def populate_past_data(
org: str,
db: Session = Depends(get_db),
include_only_list: Optional[List[str]] = Query(None),
):
"""
## Github Backpopulate
Queries the GitHub API to populate projects and work items that already exist in specified repos.
"include_only_list" is a list of repo names (as strings) that you wish use to populate the database.
If "include_only_list" is populated, only projects in this list will be populated
"""
proj_intended_not_found = populate_past_github(db, org, include_only_list)
in_database = db.exec( | select(Project) | sqlmodel.select |
import json
from sfm.utils import validate_signature, calc_signature
from sfm.dependencies import get_db
from sfm.models import WorkItemCreate, Project, CommitCreate, WorkItem, WorkItemUpdate
from typing import List, Optional
from sqlmodel import Session, select, and_
from fastapi import APIRouter, HTTPException, Depends, Path, Header, Request, Query
from opencensus.ext.azure.log_exporter import AzureLogHandler
from sfm.config import get_settings
from sfm.logger import create_logger
from .github_functions import (
webhook_project_processor,
deployment_processor,
pull_request_processor,
populate_past_github,
defect_processor,
reopened_processor,
unlabeled_processor,
)
app_settings = get_settings()
logger = create_logger(__name__)
router = APIRouter()
def fetch_github_payload(request):
raw = request.body()
signature = request.headers.get("X-Hub-Signature-256")
proj_auth_token = validate_signature(signature, raw)
payload = request.json()
event_type = request.headers.get("X-Github-Event")
return payload, event_type, proj_auth_token
@router.post("/github_webhooks/") # pragma: no cover
async def webhook_handler(request: Request, db: Session = Depends(get_db)):
"""
## Github Webhook Handler
Awaits incoming payload from Github Webhooks and parses the data.
Currently, endpoint processes two different event types: "Deployment" and "Pull Request".
The payload data is parsed and data needed to calculate the DORA metrics is stored in the db tables.
"""
if app_settings.GITHUB_WEBHOOK_SECRET in ["", "XXXXXXXXXXX"]:
raise HTTPException(
status_code=412,
detail="Missing github webhook secret. Please specify GITHUB_WEBHOOK_SECRET and try again",
)
# if app_settings.ENV != "test":
payload, event_type, proj_auth_token = fetch_github_payload(request)
# gather common payload object properties
if event_type != "push": # push events are the exception to common properties
repository = payload.get("repository")
else: # TODO: pull in push event information
pass
if event_type != "repository":
project_name = repository.get("name")
print("THE PROJECT NAME: ", project_name)
project_db = db.exec(
| select(Project) | sqlmodel.select |
import typing as ty
from nepali_dictionary.common.db import Dictionary
from sqlmodel import Session, select
class SearchService:
def search(self, query: str, session: ty.Type[Session], engine) -> ty.Optional[dict]:
with session(engine) as s:
statement = | select(Dictionary) | sqlmodel.select |
from __future__ import annotations
import inspect
from functools import wraps
from typing import Any, List, Type, TypeVar
from fastapi.encoders import jsonable_encoder
from sqlmodel import SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
Self = TypeVar("Self", bound="Base")
class InvalidTable(RuntimeError):
"""Raised when calling a method coupled to SQLAlchemy operations.
It should be called only by SQLModel objects that are tables.
"""
def is_table(cls: Type[Self]) -> bool:
base_is_table = False
for base in cls.__bases__:
config = getattr(base, "__config__")
if config and getattr(config, "table", False):
base_is_table = True
break
return getattr(cls.__config__, "table", False) and not base_is_table
def validate_table(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
cls = self if inspect.isclass(self) else self.__class__
if not is_table(cls):
raise InvalidTable(
f'"{cls.__name__}" is not a table. '
"Add the class parameter `table=True` or don't use with this object."
)
return func(self, *args, **kwargs)
return wrapper
class Base(SQLModel):
@classmethod
@validate_table
async def get(
cls: Type[Self], session: AsyncSession, *args: Any, **kwargs: Any
) -> Self:
result = await session.execute( | select(cls) | sqlmodel.select |
from __future__ import annotations
import inspect
from functools import wraps
from typing import Any, List, Type, TypeVar
from fastapi.encoders import jsonable_encoder
from sqlmodel import SQLModel, select
from sqlmodel.ext.asyncio.session import AsyncSession
Self = TypeVar("Self", bound="Base")
class InvalidTable(RuntimeError):
"""Raised when calling a method coupled to SQLAlchemy operations.
It should be called only by SQLModel objects that are tables.
"""
def is_table(cls: Type[Self]) -> bool:
base_is_table = False
for base in cls.__bases__:
config = getattr(base, "__config__")
if config and getattr(config, "table", False):
base_is_table = True
break
return getattr(cls.__config__, "table", False) and not base_is_table
def validate_table(func):
@wraps(func)
def wrapper(self, *args, **kwargs):
cls = self if inspect.isclass(self) else self.__class__
if not is_table(cls):
raise InvalidTable(
f'"{cls.__name__}" is not a table. '
"Add the class parameter `table=True` or don't use with this object."
)
return func(self, *args, **kwargs)
return wrapper
class Base(SQLModel):
@classmethod
@validate_table
async def get(
cls: Type[Self], session: AsyncSession, *args: Any, **kwargs: Any
) -> Self:
result = await session.execute(select(cls).filter(*args).filter_by(**kwargs))
return result.scalars().first()
@classmethod
@validate_table
async def get_multi(
cls: Type[Self],
session: AsyncSession,
*args,
offset: int = 0,
limit: int = 100,
**kwargs,
) -> List[Self]:
result = await session.execute(
| select(cls) | sqlmodel.select |
from typing import Optional
from pydantic import EmailStr
from sqlmodel import Field, SQLModel
# define your database tables (models) here
class User(SQLModel, table=True):
id: Optional[int] = | Field(default=None, nullable=False, primary_key=True) | sqlmodel.Field |
from typing import Optional
from pydantic import EmailStr
from sqlmodel import Field, SQLModel
# define your database tables (models) here
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, nullable=False, primary_key=True)
name: str = | Field(nullable=False) | sqlmodel.Field |
from typing import Optional
from pydantic import EmailStr
from sqlmodel import Field, SQLModel
# define your database tables (models) here
class User(SQLModel, table=True):
id: Optional[int] = Field(default=None, nullable=False, primary_key=True)
name: str = Field(nullable=False)
email: EmailStr = Field(
nullable=False,
)
password: str = | Field(nullable=False) | sqlmodel.Field |
from unittest.mock import patch
from sqlmodel import create_engine
from ...conftest import get_testing_print_function
def test_tutorial(clear_sqlmodel):
from docs_src.tutorial.where import tutorial002 as mod
mod.sqlite_url = "sqlite://"
mod.engine = | create_engine(mod.sqlite_url) | sqlmodel.create_engine |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = | Field(foreign_key="organization.id") | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = | Field(default="http") | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = | Relationship(back_populates="server") | sqlmodel.Relationship |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = | Relationship(back_populates="server") | sqlmodel.Relationship |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = | Field(default=None, foreign_key="server.id") | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = Field(default=None, foreign_key="server.id")
server: Optional[Server] = | Relationship(back_populates="server_log") | sqlmodel.Relationship |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = Field(default=None, foreign_key="server.id")
server: Optional[Server] = Relationship(back_populates="server_log")
response_code: Optional[int]
response_time: Optional[int]
ipaddress: Optional[str]
url: str
error: Optional[str]
class ServerReport(SQLModel, table=True):
id: int = | Field(primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = Field(default=None, foreign_key="server.id")
server: Optional[Server] = Relationship(back_populates="server_log")
response_code: Optional[int]
response_time: Optional[int]
ipaddress: Optional[str]
url: str
error: Optional[str]
class ServerReport(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = | Field(default=None, foreign_key="server.id") | sqlmodel.Field |
from sqlmodel import SQLModel, Field, JSON, Relationship, VARCHAR
from pydantic import BaseModel
from datetime import datetime
from typing import List, Optional
from sqlalchemy import String, Column
class ServerCatagoryLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
catagory_id: Optional[int] = Field(
default=None, foreign_key="catagory.id", primary_key=True
)
class ServerOrganizationLink(SQLModel, table=True):
server_id: Optional[int] = Field(
default=None, foreign_key="server.id", primary_key=True
)
organization_id: Optional[int] = Field(
default=None, foreign_key="organization.id", primary_key=True
)
class Catagory(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
meta_ref: str = Field(sa_column=Column("meta_ref", String(255), unique=True))
color: str
servers: List["Server"] = Relationship(
back_populates="catagories", link_model=ServerCatagoryLink
)
class SaveCatagory(SQLModel):
title: str
color: str
class Organization(SQLModel, table=True):
id: int = Field(primary_key=True)
title: str = Field(sa_column=Column("title", String(255), unique=True))
parent_id: Optional[int] = Field(foreign_key="organization.id")
ref_title: str
description: str
servers: List["Server"] = Relationship(
back_populates="organizations", link_model=ServerOrganizationLink
)
class Server(SQLModel, table=True):
id: int = Field(primary_key=True)
scheme: str = Field(default="http")
domain_name: str = Field(sa_column=Column("domain_name", String(255), unique=True))
path: Optional[str]
agency: Optional[int]
organization: Optional[str]
status: str = "LOADING"
server_log: List["ServerLog"] = Relationship(back_populates="server")
server_reports: List["ServerReport"] = Relationship(back_populates="server")
clicks: int = 0
ipaddress: Optional[str]
response_time: Optional[int] = None
last_checked: Optional[datetime]
catagories: List["Catagory"] = Relationship(
back_populates="servers", link_model=ServerCatagoryLink
)
organizations: List["Organization"] = Relationship(
back_populates="servers", link_model=ServerOrganizationLink
)
class Config:
arbitrary_types_allowed = True
class ServerLog(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = Field(default=None, foreign_key="server.id")
server: Optional[Server] = Relationship(back_populates="server_log")
response_code: Optional[int]
response_time: Optional[int]
ipaddress: Optional[str]
url: str
error: Optional[str]
class ServerReport(SQLModel, table=True):
id: int = Field(primary_key=True)
datetime: datetime
server_id: Optional[int] = Field(default=None, foreign_key="server.id")
server: Optional[Server] = | Relationship(back_populates="server_reports") | sqlmodel.Relationship |
from unittest.mock import patch
from sqlmodel import create_engine
from ...conftest import get_testing_print_function
expected_calls = [
[
[
{
"id": 7,
"name": "Captain North America",
"secret_name": "<NAME>",
"age": 93,
}
]
]
]
def test_tutorial(clear_sqlmodel):
from docs_src.tutorial.offset_and_limit import tutorial003 as mod
mod.sqlite_url = "sqlite://"
mod.engine = | create_engine(mod.sqlite_url) | sqlmodel.create_engine |
from sqlmodel import create_engine
from pyflarum.database.session import FlarumDatabase
from pyflarum.database.flarum.core.users import DB_User
ENGINE = | create_engine('sqlite:///tests/database/database.db') | sqlmodel.create_engine |
from sqlmodel import SQLModel, create_engine
from sqlalchemy.orm import sessionmaker
from opencensus.ext.azure.log_exporter import AzureLogHandler
from sfm.logger import create_logger
from sfm.config import get_settings
import psycopg2
# def generate_db_string(ENV: str, DBHOST: str, DBNAME: str, DBUSER: str, DBPASS: str):
# """Take in env variables and generate correct db string."""
# # if ENV == "test":
# # return "sqlite://" # in-memory database for unit tests
# if ENV == "local":
# return "postgres+asyncpg://postgres:postgres@db:5432/sfm" # local sqlite for local development
# if ENV == "development" or "production":
# # need all four parameters available
# if "unset" in [DBNAME, DBPASS]:
# raise ValueError(
# "Missing database parameter in the environment. Please specify DBHOST, DBNAME, DBUSER, and DBPASS"
# )
# conn = "host={0} user={1} dbname={2} password={3} sslmode={4}".format(
# DBHOST, DBUSER, DBNAME, DBPASS, "require"
# )
# conn = f"postgresql+asyncpg://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}"
# # return conn
# return conn
app_settings = get_settings()
# CONN_STR = generate_db_string(
# app_settings.ENV,
# app_settings.DBHOST,
# app_settings.DBNAME,
# app_settings.DBUSER,
# app_settings.DBPASS,
# )
# check_same_thread = false only works in sqlite, not postgres or others
# if "sqlite" in CONN_STR:
# # print("Using a sqlite database")
# connect_args = {"check_same_thread": False}
# engine = create_engine(CONN_STR, connect_args=connect_args)
# else:
logger = create_logger(__name__)
engine = | create_engine(app_settings.DATABASE_URL, echo=False) | sqlmodel.create_engine |
from typing import Callable
from sqlmodel import select, Session
from . import BaseRepository, engine
from ..models import ProfileDB, UserDB
from app.shared.exc import (
EmailAlreadyTakenError,
UserDoesNotExist,
UsernameAlreadyTakenError)
class UserRepository(BaseRepository):
model = UserDB
@classmethod
def create_with_profile(cls, **kwargs) -> UserDB:
user = cls.model(**kwargs)
user.profile = ProfileDB()
user.profile.create_gravatar()
user.save()
return user
@classmethod
def get_all_ilike_username(cls,
search_for: str
) -> list[UserDB]:
with | Session(engine) | sqlmodel.Session |
from typing import Callable
from sqlmodel import select, Session
from . import BaseRepository, engine
from ..models import ProfileDB, UserDB
from app.shared.exc import (
EmailAlreadyTakenError,
UserDoesNotExist,
UsernameAlreadyTakenError)
class UserRepository(BaseRepository):
model = UserDB
@classmethod
def create_with_profile(cls, **kwargs) -> UserDB:
user = cls.model(**kwargs)
user.profile = ProfileDB()
user.profile.create_gravatar()
user.save()
return user
@classmethod
def get_all_ilike_username(cls,
search_for: str
) -> list[UserDB]:
with Session(engine) as session:
return session.exec( | select(cls.model) | sqlmodel.select |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = | Field(default=None, foreign_key="meter.id") | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = | Field() | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = | Field(default=0.0) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = | Field() | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = | Field() | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = Field()
class LabelAssignment(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = Field()
class LabelAssignment(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
label_id: Optional[int] = | Field(default=None, foreign_key="label.id") | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = Field()
class LabelAssignment(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
label_id: Optional[int] = Field(default=None, foreign_key="label.id")
meter_id: Optional[int] = | Field(default=None, foreign_key="meter.id") | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = Field()
class LabelAssignment(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
label_id: Optional[int] = Field(default=None, foreign_key="label.id")
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
start_time: datetime = | Field() | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, SQLModel
from datetime import datetime
class Meter(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
serial_number: str
class Measurement(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
capture_time: datetime = Field()
voltage_phase_1: float = Field(default=0.0)
voltage_phase_2: float = Field(default=0.0)
voltage_phase_3: float = Field(default=0.0)
power: float = Field(default=0.0)
thd_1: float = Field(default=0.0)
thd_2: float = Field(default=0.0)
thd_3: float = Field(default=0.0)
thd_4: float = Field(default=0.0)
thd_5: float = Field(default=0.0)
thd_6: float = Field(default=0.0)
thd_7: float = Field(default=0.0)
thd_8: float = Field(default=0.0)
thd_9: float = Field(default=0.0)
thd_10: float = Field(default=0.0)
class Label(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field()
color: str = Field()
class LabelAssignment(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
label_id: Optional[int] = Field(default=None, foreign_key="label.id")
meter_id: Optional[int] = Field(default=None, foreign_key="meter.id")
start_time: datetime = Field()
end_time: datetime = | Field() | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = | Field(default=None, primary_key=True, foreign_key='users.id') | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = | Field(default=None, primary_key=True, foreign_key='tags.id') | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = | Field(default=False) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = | Field(max_length=100) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = | Field(max_length=100) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = | Field(max_length=50) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = | Field(max_length=100) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = | Field(max_length=100) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = | Field(default=None, foreign_key='tags.id') | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = | Relationship(back_populates='children') | sqlmodel.Relationship |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = | Field(default=False) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = | Field(default=False) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = | Field(default=0) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = | Field(default=None, foreign_key='discussions.id') | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = Field(default=None, foreign_key='discussions.id')
"""The ID of the last posted discussion in this tag."""
last_posted_discussion: t.Optional['DB_Discussion'] = | Relationship(back_populates='tags') | sqlmodel.Relationship |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = Field(default=None, foreign_key='discussions.id')
"""The ID of the last posted discussion in this tag."""
last_posted_discussion: t.Optional['DB_Discussion'] = Relationship(back_populates='tags')
"""The last posted discussion in this tag."""
last_posted_user_id: t.Optional[int] = | Field(default=None, foreign_key='users.id') | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = Field(default=None, foreign_key='discussions.id')
"""The ID of the last posted discussion in this tag."""
last_posted_discussion: t.Optional['DB_Discussion'] = Relationship(back_populates='tags')
"""The last posted discussion in this tag."""
last_posted_user_id: t.Optional[int] = Field(default=None, foreign_key='users.id')
"""The ID of the user that last posted in this tag."""
last_posted_user: t.Optional['DB_User'] = | Relationship(back_populates='tags') | sqlmodel.Relationship |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = Field(default=None, foreign_key='discussions.id')
"""The ID of the last posted discussion in this tag."""
last_posted_discussion: t.Optional['DB_Discussion'] = Relationship(back_populates='tags')
"""The last posted discussion in this tag."""
last_posted_user_id: t.Optional[int] = Field(default=None, foreign_key='users.id')
"""The ID of the user that last posted in this tag."""
last_posted_user: t.Optional['DB_User'] = Relationship(back_populates='tags')
"""The user that last posted in this tag."""
icon: t.Optional[str] = | Field(max_length=100) | sqlmodel.Field |
import typing as t
if t.TYPE_CHECKING:
from ..core.discussions import DB_Discussion
from ..core.users import DB_User
from datetime import datetime
from sqlmodel import SQLModel, Field, Relationship
class DB_TagUser(SQLModel, table=True):
"""
Represents a tag-to-user relationship in the database.
"""
__tablename__ = 'tag_user'
user_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='users.id')
"""The ID of the user."""
tag_id: t.Optional[int] = Field(default=None, primary_key=True, foreign_key='tags.id')
"""The ID of the tag."""
marked_as_read_at: t.Optional[datetime]
"""When the user marked the tag as read?"""
is_hidden: bool = Field(default=False)
"""?"""
class DB_Tag(SQLModel, table=True):
"""
Represents a tag in the database.
"""
__tablename__ = 'tags'
id: t.Optional[int] = Field(default=None, primary_key=True)
"""The ID of the tag. This is handled by the database."""
name: str = Field(max_length=100)
"""The name of the tag."""
slug: str = Field(max_length=100)
"""The tag's slug (will be used in URL)."""
description: t.Optional[t.Text]
"""The description of the tag."""
color: t.Optional[str] = Field(max_length=50)
"""The tag's color."""
background_path: t.Optional[str] = Field(max_length=100)
"""?"""
background_mode: t.Optional[str] = Field(max_length=100)
"""?"""
position: t.Optional[int]
"""The tag's position in the tag tree."""
parent_id: t.Optional[int] = Field(default=None, foreign_key='tags.id')
"""The ID of the parent tag."""
parent_tag: t.Optional['DB_Tag'] = Relationship(back_populates='children')
"""The tag's parent tag."""
default_sort: t.Optional[str]
"""The default sorting behaviour of the tag."""
is_restricted: bool = Field(default=False)
"""Whether or not the tag is restricted."""
is_hidden: bool = Field(default=False)
"""Whether or not the tag is hidden."""
discussion_count: int = Field(default=0)
"""How many discussions are tagged with this tag?"""
last_posted_at: t.Optional[datetime]
"""The datetime when was the last discussion posted in this tag."""
last_posted_discussion_id: t.Optional[int] = Field(default=None, foreign_key='discussions.id')
"""The ID of the last posted discussion in this tag."""
last_posted_discussion: t.Optional['DB_Discussion'] = Relationship(back_populates='tags')
"""The last posted discussion in this tag."""
last_posted_user_id: t.Optional[int] = Field(default=None, foreign_key='users.id')
"""The ID of the user that last posted in this tag."""
last_posted_user: t.Optional['DB_User'] = Relationship(back_populates='tags')
"""The user that last posted in this tag."""
icon: t.Optional[str] = Field(max_length=100)
"""The [FontAwesome](https://fontawesome.com/v5.15/icons?d=gallery&m=free) icon for the tag."""
users: t.List['DB_User'] = | Relationship(back_populates='tags', link_model=DB_TagUser) | sqlmodel.Relationship |
import os
import re
from pathlib import Path
from typing import List, Optional
import tmdbsimple as tmdb
from dotenv import load_dotenv
from models import (
Collection,
Genre,
Movie,
ProductionCompany,
ProductionCountry,
SpokenLanguage,
)
from sqlalchemy import extract
from sqlalchemy.exc import NoResultFound
from sqlmodel import Session, SQLModel, select
load_dotenv()
YEAR_PATTERN = re.compile(r"(\s\(\d{4}\))")
def create_model_obj(o: dict, model_type: SQLModel, session: Session) -> SQLModel:
obj = model_type(**o)
return obj
def create_model_objs(
data: dict, model_type: SQLModel, session: Session
) -> List[SQLModel]:
objs = []
for o in data:
obj = create_model_obj(o, model_type, session)
objs.append(obj)
return objs
def tmdb_info_to_movie(info: dict, session: Session) -> Movie:
relationship_keys = {
"genres",
"belongs_to_collection",
"production_companies",
"production_countries",
"spoken_languages",
}
movie_info = {k: v for k, v in info.items() if k not in relationship_keys}
genres = create_model_objs(info["genres"], Genre, session)
collection = None
if info["belongs_to_collection"]:
collection = create_model_obj(
info["belongs_to_collection"], Collection, session
)
production_companies = create_model_objs(
info["production_companies"], ProductionCompany, session
)
production_countries = create_model_objs(
info["production_countries"], ProductionCountry, session
)
# languages
spoken_languages = create_model_objs(
info["spoken_languages"], SpokenLanguage, session
)
# create movie
movie = Movie(**movie_info)
movie.genres = genres
movie.collection = collection
movie.production_companies = production_companies
movie.production_countries = production_countries
movie.spoken_languages = spoken_languages
session.add(movie)
session.commit()
session.refresh(movie)
return movie
tmdb.API_KEY = os.getenv("TMDB_API_KEY", None)
def split_movie_path_title_and_year(path: str):
movie_path = Path(path)
movie_name = movie_path.stem
year = None
match = YEAR_PATTERN.search(movie_name)
if match:
year = match.group().strip(" ()")
movie_name = movie_name.replace(match.group(), "")
return movie_name, year
def get_movie_from_path(path: str, session: Session) -> Optional[Movie]:
movie = None
movie_name, year = split_movie_path_title_and_year(path)
# lookup in db
statement = | select(Movie) | sqlmodel.select |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
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, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
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 typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
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)
def create_heroes():
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)
hero_4 = Hero(name="Tarantula", secret_name="<NAME>", age=32)
hero_5 = Hero(name="<NAME>", secret_name="<NAME>", age=35)
hero_6 = Hero(name="<NAME>", secret_name="<NAME>", age=36)
hero_7 = Hero(name="Captain North America", secret_name="<NAME>", age=93)
with | Session(engine) | sqlmodel.Session |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
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)
def create_heroes():
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)
hero_4 = Hero(name="Tarantula", secret_name="<NAME>", age=32)
hero_5 = Hero(name="<NAME>", secret_name="<NAME>", age=35)
hero_6 = Hero(name="<NAME>", secret_name="<NAME>", age=36)
hero_7 = Hero(name="Captain North America", secret_name="<NAME>", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with | Session(engine) | sqlmodel.Session |
from typing import Optional
from sqlmodel import Field, Session, SQLModel, create_engine, select
class Hero(SQLModel, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str
secret_name: str
age: Optional[int] = None
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)
def create_heroes():
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)
hero_4 = Hero(name="Tarantula", secret_name="<NAME>", age=32)
hero_5 = Hero(name="<NAME>", secret_name="<NAME>", age=35)
hero_6 = Hero(name="<NAME>", secret_name="<NAME>", age=36)
hero_7 = Hero(name="Captain North America", secret_name="<NAME>", age=93)
with Session(engine) as session:
session.add(hero_1)
session.add(hero_2)
session.add(hero_3)
session.add(hero_4)
session.add(hero_5)
session.add(hero_6)
session.add(hero_7)
session.commit()
def select_heroes():
with Session(engine) as session:
statement = | select(Hero) | sqlmodel.select |
import uuid
from datetime import datetime, timedelta, timezone
from typing import AsyncGenerator
import pytest
from pydantic import UUID4
from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, create_engine
from fastapi_users_db_sqlmodel import SQLModelUserDatabase, SQLModelUserDatabaseAsync
from fastapi_users_db_sqlmodel.access_token import (
SQLModelAccessTokenDatabase,
SQLModelAccessTokenDatabaseAsync,
SQLModelBaseAccessToken,
)
from tests.conftest import UserDB
class AccessToken(SQLModelBaseAccessToken, table=True):
pass
@pytest.fixture
def user_id() -> UUID4:
return uuid.UUID("a9089e5d-2642-406d-a7c0-cbc641aca0ec")
async def init_sync_session(url: str) -> AsyncGenerator[Session, None]:
engine = | create_engine(url, connect_args={"check_same_thread": False}) | sqlmodel.create_engine |
import uuid
from datetime import datetime, timedelta, timezone
from typing import AsyncGenerator
import pytest
from pydantic import UUID4
from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, create_engine
from fastapi_users_db_sqlmodel import SQLModelUserDatabase, SQLModelUserDatabaseAsync
from fastapi_users_db_sqlmodel.access_token import (
SQLModelAccessTokenDatabase,
SQLModelAccessTokenDatabaseAsync,
SQLModelBaseAccessToken,
)
from tests.conftest import UserDB
class AccessToken(SQLModelBaseAccessToken, table=True):
pass
@pytest.fixture
def user_id() -> UUID4:
return uuid.UUID("a9089e5d-2642-406d-a7c0-cbc641aca0ec")
async def init_sync_session(url: str) -> AsyncGenerator[Session, None]:
engine = create_engine(url, connect_args={"check_same_thread": False})
| SQLModel.metadata.create_all(engine) | sqlmodel.SQLModel.metadata.create_all |
import uuid
from datetime import datetime, timedelta, timezone
from typing import AsyncGenerator
import pytest
from pydantic import UUID4
from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, create_engine
from fastapi_users_db_sqlmodel import SQLModelUserDatabase, SQLModelUserDatabaseAsync
from fastapi_users_db_sqlmodel.access_token import (
SQLModelAccessTokenDatabase,
SQLModelAccessTokenDatabaseAsync,
SQLModelBaseAccessToken,
)
from tests.conftest import UserDB
class AccessToken(SQLModelBaseAccessToken, table=True):
pass
@pytest.fixture
def user_id() -> UUID4:
return uuid.UUID("a9089e5d-2642-406d-a7c0-cbc641aca0ec")
async def init_sync_session(url: str) -> AsyncGenerator[Session, None]:
engine = create_engine(url, connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
| SQLModel.metadata.drop_all(engine) | sqlmodel.SQLModel.metadata.drop_all |
import uuid
from datetime import datetime, timedelta, timezone
from typing import AsyncGenerator
import pytest
from pydantic import UUID4
from sqlalchemy import exc
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from sqlmodel import Session, SQLModel, create_engine
from fastapi_users_db_sqlmodel import SQLModelUserDatabase, SQLModelUserDatabaseAsync
from fastapi_users_db_sqlmodel.access_token import (
SQLModelAccessTokenDatabase,
SQLModelAccessTokenDatabaseAsync,
SQLModelBaseAccessToken,
)
from tests.conftest import UserDB
class AccessToken(SQLModelBaseAccessToken, table=True):
pass
@pytest.fixture
def user_id() -> UUID4:
return uuid.UUID("a9089e5d-2642-406d-a7c0-cbc641aca0ec")
async def init_sync_session(url: str) -> AsyncGenerator[Session, None]:
engine = create_engine(url, connect_args={"check_same_thread": False})
SQLModel.metadata.create_all(engine)
with | Session(engine) | sqlmodel.Session |
from sqlmodel import SQLModel
from sqlmodel import Field, Relationship
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from typing import TYPE_CHECKING, Optional, List
if TYPE_CHECKING:
from app.src.models.product import ProductRead
from app.src.models.product import Product
class ProductTypeBase(SQLModel):
name: str
description: str
class ProductType(ProductTypeBase, table=True):
id: Optional[int] = | Field(default=None, primary_key=True) | sqlmodel.Field |
from sqlmodel import SQLModel
from sqlmodel import Field, Relationship
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from typing import TYPE_CHECKING, Optional, List
if TYPE_CHECKING:
from app.src.models.product import ProductRead
from app.src.models.product import Product
class ProductTypeBase(SQLModel):
name: str
description: str
class ProductType(ProductTypeBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(sa_column=Column("name", String, unique=True))
description: Optional[str] = | Field(default=None) | sqlmodel.Field |
from sqlmodel import SQLModel
from sqlmodel import Field, Relationship
from sqlalchemy import String
from sqlalchemy.sql.schema import Column
from typing import TYPE_CHECKING, Optional, List
if TYPE_CHECKING:
from app.src.models.product import ProductRead
from app.src.models.product import Product
class ProductTypeBase(SQLModel):
name: str
description: str
class ProductType(ProductTypeBase, table=True):
id: Optional[int] = Field(default=None, primary_key=True)
name: str = Field(sa_column=Column("name", String, unique=True))
description: Optional[str] = Field(default=None)
products: List["Product"] = | Relationship(back_populates="product_type") | sqlmodel.Relationship |