Skip to content

Commit

Permalink
Dashboard fixes (#140)
Browse files Browse the repository at this point in the history
* small fixes and initial alembic scripts

* Add timestamp to callresponse
  • Loading branch information
rubenpeters91 authored Oct 30, 2024
1 parent e1c96d8 commit 6adea35
Show file tree
Hide file tree
Showing 13 changed files with 366 additions and 16 deletions.
11 changes: 11 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0

## [Unreleased]

## [1.4.6] - 2024-10-29

### Fixed
- Removed TTL in patient list in calling dashboard and also show patient that were called today to prevent patients from disappearing during calls
- Corrected database column types so databases are identical over different environments

### Added
- Added Alembic for database migrations
- Added a timestamp for call response, so we can track when patients were called


## [1.4.5] - 2024-10-21

### Fixed
Expand Down
113 changes: 113 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,113 @@
# A generic, single database configuration.

[alembic]
# path to migration scripts
# Use forward slashes (/) also on windows to provide an os agnostic path
script_location = alembic

# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
# Uncomment the line below if you want the files to be prepended with date and time
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
# for all available tokens
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s

# sys.path path, will be prepended to sys.path if present.
# defaults to the current working directory.
prepend_sys_path = .

# timezone to use when rendering the date within the migration file
# as well as the filename.
# If specified, requires the python>=3.9 or backports.zoneinfo library.
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
# string value is passed to ZoneInfo()
# leave blank for localtime
# timezone =

# max length of characters to apply to the "slug" field
# truncate_slug_length = 40

# set to 'true' to run the environment during
# the 'revision' command, regardless of autogenerate
# revision_environment = false

# set to 'true' to allow .pyc and .pyo files without
# a source .py file to be detected as revisions in the
# versions/ directory
# sourceless = false

# version location specification; This defaults
# to alembic/versions. When using multiple version
# directories, initial revisions must be specified with --version-path.
# The path separator used here should be the separator specified by "version_path_separator" below.
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions

# version path separator; As mentioned above, this is the character used to split
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
# Valid values for version_path_separator are:
#
# version_path_separator = :
# version_path_separator = ;
# version_path_separator = space
# version_path_separator = newline
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.

# set to 'true' to search source files recursively
# in each "version_locations" directory
# new in Alembic version 1.10
# recursive_version_locations = false

# the output encoding used when revision files
# are written from script.py.mako
# output_encoding = utf-8

sqlalchemy.url =


[post_write_hooks]
hooks = ruff, ruff_format

# lint with attempts to fix using "ruff"
ruff.type = exec
ruff.executable = %(here)s/.venv/bin/ruff
ruff.options = check --fix REVISION_SCRIPT_FILENAME

# format using "ruff" - use the exec runner, execute a binary
ruff_format.type = exec
ruff_format.executable = %(here)s/.venv/bin/ruff
ruff_format.options = format REVISION_SCRIPT_FILENAME

# Logging configuration
[loggers]
keys = root,sqlalchemy,alembic

[handlers]
keys = console

[formatters]
keys = generic

[logger_root]
level = WARN
handlers = console
qualname =

[logger_sqlalchemy]
level = WARN
handlers =
qualname = sqlalchemy.engine

[logger_alembic]
level = INFO
handlers =
qualname = alembic

[handler_console]
class = StreamHandler
args = (sys.stderr,)
level = NOTSET
formatter = generic

[formatter_generic]
format = %(levelname)-5.5s [%(name)s] %(message)s
datefmt = %H:%M:%S
14 changes: 14 additions & 0 deletions alembic/README
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
Generic single-database configuration.

Used to run database migrations.

To generate migration scripts use:
```
alembic revision --autogenerate -m "message"
```

Then to apply the migrations run:
```
alembic upgrade head
```
Though this should be part of the CI/CD or deploy pipeline
80 changes: 80 additions & 0 deletions alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,80 @@
from logging.config import fileConfig

from alembic import context

from noshow.database.connection import get_connection_string, get_engine
from noshow.database.models import Base

# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config

# Interpret the config file for Python logging.
# This line sets up loggers basically.
if config.config_file_name is not None:
fileConfig(config.config_file_name)

# add your model's MetaData object here
# for 'autogenerate' support
# from myapp import mymodel
target_metadata = Base.metadata
target_metadata.schema = "noshow"


# other values from the config, defined by the needs of env.py,
# can be acquired:
# my_important_option = config.get_main_option("my_important_option")
# ... etc.
CONNECT_STRING = get_connection_string()


def run_migrations_offline() -> None:
"""Run migrations in 'offline' mode.
This configures the context with just a URL
and not an Engine, though an Engine is acceptable
here as well. By skipping the Engine creation
we don't even need a DBAPI to be available.
Calls to context.execute() here emit the given string to the
script output.
"""
context.configure(
url=CONNECT_STRING,
target_metadata=target_metadata,
literal_binds=True,
dialect_opts={"paramstyle": "named"},
include_schemas=True,
version_table_schema=target_metadata.schema,
)

with context.begin_transaction():
context.run_migrations()


def run_migrations_online() -> None:
"""Run migrations in 'online' mode.
In this scenario we need to create an Engine
and associate a connection with the context.
"""
connectable = get_engine(CONNECT_STRING)

with connectable.connect() as connection:
context.configure(
connection=connection,
target_metadata=target_metadata,
include_schemas=True,
version_table_schema=target_metadata.schema,
)

with context.begin_transaction():
context.run_migrations()


if context.is_offline_mode():
run_migrations_offline()
else:
run_migrations_online()
26 changes: 26 additions & 0 deletions alembic/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
"""${message}

Revision ID: ${up_revision}
Revises: ${down_revision | comma,n}
Create Date: ${create_date}

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
${imports if imports else ""}

# revision identifiers, used by Alembic.
revision: str = ${repr(up_revision)}
down_revision: Union[str, None] = ${repr(down_revision)}
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}


def upgrade() -> None:
${upgrades if upgrades else "pass"}


def downgrade() -> None:
${downgrades if downgrades else "pass"}
34 changes: 34 additions & 0 deletions alembic/versions/20f444146781_add_timestamp.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
"""add timestamp
Revision ID: 20f444146781
Revises:
Create Date: 2024-10-30 09:56:46.886479
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

# revision identifiers, used by Alembic.
revision: str = "20f444146781"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.add_column(
"apicallresponse",
sa.Column("timestamp", sa.DateTime(), nullable=True),
schema="noshow",
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column("apicallresponse", "timestamp", schema="noshow")
# ### end Alembic commands ###
4 changes: 3 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"

[project]
name = "noshow"
version = "1.4.5"
version = "1.4.6"
authors = [
{ name="Ruben Peters", email="[email protected]" },
{ name="Eric Wolters", email="[email protected]" }
Expand Down Expand Up @@ -54,6 +54,8 @@ dev-dependencies = [
"uvicorn~=0.28.0",
"pytest-asyncio~=0.23.6",
"pytest-cov>=5.0.0",
"alembic>=1.13.3",
"ruff>=0.7.1",
]

[tool.isort]
Expand Down
16 changes: 8 additions & 8 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ diskcache==5.6.3
distro==1.9.0
dpath==2.2.0
dulwich==0.22.3
dvc==3.55.2
dvc==3.56.0
dvc-data==3.16.6
dvc-http==2.32.0
dvc-objects==5.1.0
Expand All @@ -45,12 +45,12 @@ dvc-studio-client==0.21.0
dvc-task==0.40.2
dvclive==3.48.0
entrypoints==0.4
fastapi==0.115.2
fastapi==0.115.3
filelock==3.16.1
flatten-dict==0.4.2
flufl-lock==8.1.0
fonttools==4.54.1
frozenlist==1.4.1
frozenlist==1.5.0
fsspec==2024.10.0
funcy==2.0
gitdb==4.0.11
Expand All @@ -76,15 +76,15 @@ narwhals==1.10.0
networkx==3.4.2
numpy==1.26.4
omegaconf==2.3.0
orjson==3.10.9 ; implementation_name == 'cpython'
orjson==3.10.10 ; implementation_name == 'cpython'
packaging==24.1
pandas==2.2.3
pathspec==0.12.1
pillow==10.4.0
platformdirs==3.11.0
prompt-toolkit==3.0.48
propcache==0.2.0
protobuf==5.28.2
protobuf==5.28.3
psutil==6.1.0
pyarrow==14.0.2
pycparser==2.22
Expand All @@ -106,7 +106,7 @@ pyyaml==6.0.2
referencing==0.35.1
relplot==1.0
requests==2.32.3
rich==13.9.2
rich==13.9.3
rpds-py==0.20.0
ruamel-yaml==0.18.6
ruamel-yaml-clib==0.2.12 ; python_full_version < '3.13' and platform_python_implementation == 'CPython'
Expand All @@ -124,7 +124,7 @@ smmap==5.0.1
sniffio==1.3.1
sqlalchemy==2.0.36
sqltrie==0.11.1
starlette==0.40.0
starlette==0.41.0
streamlit==1.39.0
tabulate==0.9.0
tenacity==9.0.0
Expand All @@ -142,5 +142,5 @@ vine==5.1.0
voluptuous==0.15.2
watchdog==5.0.3 ; platform_system != 'Darwin'
wcwidth==0.2.13
yarl==1.15.5
yarl==1.16.0
zc-lockfile==3.0.post1
8 changes: 7 additions & 1 deletion run/calling_dash.py
Original file line number Diff line number Diff line change
Expand Up @@ -245,12 +245,18 @@ def main():
),
type="primary",
)
if current_response.timestamp is not None:
st.caption(
f"Laatst opgeslagen om: {current_response.timestamp:%Y-%m-%d %H:%M:%S}"
)
st.button(
"Vorige",
on_click=previous_preds,
)
st.divider()
st.write(f"Laatste update: {last_updated:%Y-%m-%d %H:%M:%S}")
st.caption(
f"Laatste voorspellingen gegenereerd om: {last_updated:%Y-%m-%d %H:%M:%S}"
)


if __name__ == "__main__":
Expand Down
Loading

0 comments on commit 6adea35

Please sign in to comment.