list medical card base
This commit is contained in:
110
alembic.ini
Normal file
110
alembic.ini
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
# A generic, single database configuration.
|
||||||
|
|
||||||
|
[alembic]
|
||||||
|
# path to migration scripts
|
||||||
|
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-dateutil library that can be
|
||||||
|
# installed by adding `alembic[tz]` to the pip requirements
|
||||||
|
# string value is passed to dateutil.tz.gettz()
|
||||||
|
# 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 = 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 = postgresql://barbie:redStar4,1@localhost:5432/medical_info_db
|
||||||
|
|
||||||
|
|
||||||
|
[post_write_hooks]
|
||||||
|
# post_write_hooks defines scripts or Python functions that are run
|
||||||
|
# on newly generated revision scripts. See the documentation for further
|
||||||
|
# detail and examples
|
||||||
|
|
||||||
|
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||||
|
# hooks = black
|
||||||
|
# black.type = console_scripts
|
||||||
|
# black.entrypoint = black
|
||||||
|
# black.options = -l 79 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
|
||||||
1
alembic/README
Normal file
1
alembic/README
Normal file
@@ -0,0 +1 @@
|
|||||||
|
Generic single-database configuration.
|
||||||
79
alembic/env.py
Normal file
79
alembic/env.py
Normal file
@@ -0,0 +1,79 @@
|
|||||||
|
from logging.config import fileConfig
|
||||||
|
|
||||||
|
from sqlalchemy import engine_from_config
|
||||||
|
from sqlalchemy import pool
|
||||||
|
|
||||||
|
from alembic import context
|
||||||
|
|
||||||
|
from medical_info.db.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 = mymodel.Base.metadata
|
||||||
|
target_metadata = Base.metadata
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
|
||||||
|
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.
|
||||||
|
|
||||||
|
"""
|
||||||
|
url = config.get_main_option("sqlalchemy.url")
|
||||||
|
context.configure(
|
||||||
|
url=url,
|
||||||
|
target_metadata=target_metadata,
|
||||||
|
literal_binds=True,
|
||||||
|
dialect_opts={"paramstyle": "named"},
|
||||||
|
)
|
||||||
|
|
||||||
|
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 = engine_from_config(
|
||||||
|
config.get_section(config.config_ini_section, {}),
|
||||||
|
prefix="sqlalchemy.",
|
||||||
|
poolclass=pool.NullPool,
|
||||||
|
)
|
||||||
|
|
||||||
|
with connectable.connect() as connection:
|
||||||
|
context.configure(
|
||||||
|
connection=connection, target_metadata=target_metadata
|
||||||
|
)
|
||||||
|
|
||||||
|
with context.begin_transaction():
|
||||||
|
context.run_migrations()
|
||||||
|
|
||||||
|
|
||||||
|
if context.is_offline_mode():
|
||||||
|
run_migrations_offline()
|
||||||
|
else:
|
||||||
|
run_migrations_online()
|
||||||
24
alembic/script.py.mako
Normal file
24
alembic/script.py.mako
Normal file
@@ -0,0 +1,24 @@
|
|||||||
|
"""${message}
|
||||||
|
|
||||||
|
Revision ID: ${up_revision}
|
||||||
|
Revises: ${down_revision | comma,n}
|
||||||
|
Create Date: ${create_date}
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
${imports if imports else ""}
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = ${repr(up_revision)}
|
||||||
|
down_revision = ${repr(down_revision)}
|
||||||
|
branch_labels = ${repr(branch_labels)}
|
||||||
|
depends_on = ${repr(depends_on)}
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
${upgrades if upgrades else "pass"}
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
${downgrades if downgrades else "pass"}
|
||||||
70
alembic/versions/8282d5b2badc_initial.py
Normal file
70
alembic/versions/8282d5b2badc_initial.py
Normal file
@@ -0,0 +1,70 @@
|
|||||||
|
"""initial
|
||||||
|
|
||||||
|
Revision ID: 8282d5b2badc
|
||||||
|
Revises:
|
||||||
|
Create Date: 2023-07-21 22:53:46.768440
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects import postgresql
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = '8282d5b2badc'
|
||||||
|
down_revision = None
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.create_table('medical_cards',
|
||||||
|
sa.Column('number', sa.String(length=100), nullable=False),
|
||||||
|
sa.Column('confidant_persons', postgresql.ARRAY(sa.UUID()), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_medical_cards_id'), 'medical_cards', ['id'], unique=False)
|
||||||
|
op.create_table('checkups',
|
||||||
|
sa.Column('medical_card_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('medic_id', sa.UUID(), nullable=True),
|
||||||
|
sa.Column('claims', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('allergies', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('diseases', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('medicines', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('disease_process', sa.Text(), nullable=True),
|
||||||
|
sa.Column('visual_inspection', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('dental_formula', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.Column('dental_formula_ext', postgresql.JSONB(astext_type=sa.Text()), nullable=True),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['medical_card_id'], ['medical_cards.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_checkups_id'), 'checkups', ['id'], unique=False)
|
||||||
|
op.create_table('health_maps',
|
||||||
|
sa.Column('comment', sa.Text(), nullable=True),
|
||||||
|
sa.Column('attachments', postgresql.ARRAY(sa.String()), nullable=True),
|
||||||
|
sa.Column('medical_card_id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('id', sa.UUID(), nullable=False),
|
||||||
|
sa.Column('created_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.Column('updated_at', sa.TIMESTAMP(), nullable=False),
|
||||||
|
sa.ForeignKeyConstraint(['medical_card_id'], ['medical_cards.id'], ),
|
||||||
|
sa.PrimaryKeyConstraint('id')
|
||||||
|
)
|
||||||
|
op.create_index(op.f('ix_health_maps_id'), 'health_maps', ['id'], unique=False)
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_index(op.f('ix_health_maps_id'), table_name='health_maps')
|
||||||
|
op.drop_table('health_maps')
|
||||||
|
op.drop_index(op.f('ix_checkups_id'), table_name='checkups')
|
||||||
|
op.drop_table('checkups')
|
||||||
|
op.drop_index(op.f('ix_medical_cards_id'), table_name='medical_cards')
|
||||||
|
op.drop_table('medical_cards')
|
||||||
|
# ### end Alembic commands ###
|
||||||
28
alembic/versions/aa4d531271c0_add_person_id.py
Normal file
28
alembic/versions/aa4d531271c0_add_person_id.py
Normal file
@@ -0,0 +1,28 @@
|
|||||||
|
"""add person_id
|
||||||
|
|
||||||
|
Revision ID: aa4d531271c0
|
||||||
|
Revises: 8282d5b2badc
|
||||||
|
Create Date: 2023-07-22 00:58:19.689019
|
||||||
|
|
||||||
|
"""
|
||||||
|
from alembic import op
|
||||||
|
import sqlalchemy as sa
|
||||||
|
|
||||||
|
|
||||||
|
# revision identifiers, used by Alembic.
|
||||||
|
revision = 'aa4d531271c0'
|
||||||
|
down_revision = '8282d5b2badc'
|
||||||
|
branch_labels = None
|
||||||
|
depends_on = None
|
||||||
|
|
||||||
|
|
||||||
|
def upgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.add_column('medical_cards', sa.Column('person_id', sa.UUID(), nullable=False))
|
||||||
|
# ### end Alembic commands ###
|
||||||
|
|
||||||
|
|
||||||
|
def downgrade() -> None:
|
||||||
|
# ### commands auto generated by Alembic - please adjust! ###
|
||||||
|
op.drop_column('medical_cards', 'person_id')
|
||||||
|
# ### end Alembic commands ###
|
||||||
11
notes.txt
11
notes.txt
@@ -1,3 +1,14 @@
|
|||||||
export PYTHONPATH='/home/dd/astra/medical_information/src'
|
export PYTHONPATH='/home/dd/astra/medical_information/src'
|
||||||
|
export POSTGRES_DB='medical_info_db'
|
||||||
|
CREATE DATABASE medical_info_db;
|
||||||
|
|
||||||
|
alembic revision --autogenerate -m 'initial'
|
||||||
|
|
||||||
|
alembic init alembic
|
||||||
|
в alembic.ini правим sqlalchemy.url
|
||||||
|
alembic revision -m "add columns to checkup table"
|
||||||
|
alembic revision --autogenerate -m "person, address, contact, document v1"
|
||||||
|
|
||||||
|
alembic upgrade ae1 (можно часть версии, лишь бы однозначно указывала)
|
||||||
|
|
||||||
uvicorn --reload --port 8000 medical_info.main:app
|
uvicorn --reload --port 8000 medical_info.main:app
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
import uuid
|
|
||||||
from typing import Any
|
|
||||||
import datetime
|
|
||||||
|
|
||||||
import sqlalchemy as sa
|
|
||||||
from sqlalchemy.dialects.postgresql import UUID, ARRAY
|
|
||||||
from sqlalchemy.ext.declarative import declarative_base
|
|
||||||
from sqlalchemy.orm import relationship, DeclarativeBase
|
|
||||||
from sqlalchemy.sql.schema import ForeignKey
|
|
||||||
|
|
||||||
class Base(DeclarativeBase):
|
|
||||||
pass
|
|
||||||
|
|
||||||
class BaseModel(Base):
|
|
||||||
__abstract__ = True
|
|
||||||
|
|
||||||
id = sa.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
|
|
||||||
created_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now())
|
|
||||||
updated_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now(), onupdate=datetime.datetime.now())
|
|
||||||
|
|
||||||
class MedicalCard(BaseModel):
|
|
||||||
number = sa.Column(sa.String(100), nullable=False)
|
|
||||||
checkups = relationship('Checkup', back_populates='medical_card')
|
|
||||||
confidant_persons = sa.Column(ARRAY(UUID(as_uuid=True)))
|
|
||||||
|
|
||||||
|
|
||||||
class Checkup(BaseModel):
|
|
||||||
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
|
||||||
medical_card = relationship('MedicalCard', back_populates='medical_cards')
|
|
||||||
medic_id = sa.Column(UUID(as_uuid=True))
|
|
||||||
claims = sa.Column(ARRAY(String)) # жалобы
|
|
||||||
allergies = sa.Column(ARRAY(String)) # аллергологический анамнез
|
|
||||||
diseases = sa.Column(ARRAY(String)) # перенесенные и сопутствующие заболевания
|
|
||||||
medicines = sa.Column(ARRAY(String)) # принимаемые лекарственные препараты
|
|
||||||
disease_process = sa.Column(sa.Text) # Развитие настоящего заболевания
|
|
||||||
visual_inspection = sa.Column(ARRAY(String)) # внешний осмотр
|
|
||||||
33
src/medical_info/config.py
Normal file
33
src/medical_info/config.py
Normal file
@@ -0,0 +1,33 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from typing import Optional
|
||||||
|
from os import getenv
|
||||||
|
from pydantic import BaseSettings, PostgresDsn
|
||||||
|
|
||||||
|
class Settings(BaseSettings):
|
||||||
|
database_url: Optional[PostgresDsn]
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def get_settings() -> Settings:
|
||||||
|
settings = Settings() # type: ignore
|
||||||
|
|
||||||
|
if (db := getenv("POSTGRES_DB")) is not None:
|
||||||
|
# settings.database_url = PostgresDsn.build(
|
||||||
|
# scheme="postgresql",
|
||||||
|
# user=settings.database_url.user,
|
||||||
|
# password=settings.database_url.password,
|
||||||
|
# host=settings.database_url.host,
|
||||||
|
# port=settings.database_url.port,
|
||||||
|
# path=f"/{db}",
|
||||||
|
# )
|
||||||
|
settings.database_url = PostgresDsn.build(
|
||||||
|
scheme="postgresql",
|
||||||
|
user='barbie',
|
||||||
|
password='redStar4,1',
|
||||||
|
host='localhost',
|
||||||
|
port='5432',
|
||||||
|
path=f"/{db}",
|
||||||
|
)
|
||||||
|
elif (db := getenv("CONNECTION_STRING")) is not None:
|
||||||
|
settings.database_url = getenv("CONNECTION_STRING")
|
||||||
|
|
||||||
|
return settings
|
||||||
53
src/medical_info/db/models.py
Normal file
53
src/medical_info/db/models.py
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
import uuid
|
||||||
|
from typing import Any
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
import sqlalchemy as sa
|
||||||
|
from sqlalchemy.dialects.postgresql import UUID, ARRAY, JSONB
|
||||||
|
from sqlalchemy.ext.declarative import declarative_base
|
||||||
|
from sqlalchemy.orm import relationship, DeclarativeBase
|
||||||
|
from sqlalchemy.sql.schema import ForeignKey
|
||||||
|
|
||||||
|
class Base(DeclarativeBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
class BaseModel(Base):
|
||||||
|
__abstract__ = True
|
||||||
|
|
||||||
|
id = sa.Column(UUID(as_uuid=True), primary_key=True, default=uuid.uuid4, index=True)
|
||||||
|
created_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now())
|
||||||
|
updated_at = sa.Column(sa.TIMESTAMP, nullable=False, default=datetime.datetime.now(), onupdate=datetime.datetime.now())
|
||||||
|
|
||||||
|
class MedicalCard(BaseModel):
|
||||||
|
__tablename__ = 'medical_cards'
|
||||||
|
|
||||||
|
number = sa.Column(sa.String(100), nullable=False)
|
||||||
|
checkups = relationship('Checkup', back_populates='medical_card')
|
||||||
|
health_maps = relationship('HealthMap', back_populates='medical_card')
|
||||||
|
confidant_persons = sa.Column(ARRAY(UUID(as_uuid=True)))
|
||||||
|
person_id = sa.Column(UUID(as_uuid=True), nullable=False)
|
||||||
|
|
||||||
|
|
||||||
|
class Checkup(BaseModel):
|
||||||
|
__tablename__ = 'checkups'
|
||||||
|
|
||||||
|
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
||||||
|
medical_card = relationship('MedicalCard', back_populates='checkups')
|
||||||
|
medic_id = sa.Column(UUID(as_uuid=True))
|
||||||
|
claims = sa.Column(ARRAY(sa.String)) # жалобы
|
||||||
|
allergies = sa.Column(ARRAY(sa.String)) # аллергологический анамнез
|
||||||
|
diseases = sa.Column(ARRAY(sa.String)) # перенесенные и сопутствующие заболевания
|
||||||
|
medicines = sa.Column(ARRAY(sa.String)) # принимаемые лекарственные препараты
|
||||||
|
disease_process = sa.Column(sa.Text) # Развитие настоящего заболевания
|
||||||
|
visual_inspection = sa.Column(ARRAY(sa.String)) # внешний осмотр
|
||||||
|
|
||||||
|
dental_formula = sa.Column(JSONB)
|
||||||
|
dental_formula_ext = sa.Column(JSONB)
|
||||||
|
|
||||||
|
class HealthMap(BaseModel):
|
||||||
|
__tablename__ = 'health_maps'
|
||||||
|
|
||||||
|
comment = sa.Column(sa.Text)
|
||||||
|
attachments = sa.Column(ARRAY(sa.String))
|
||||||
|
medical_card_id = sa.Column(UUID(as_uuid=True), sa.ForeignKey("medical_cards.id"), nullable=False)
|
||||||
|
medical_card = relationship('MedicalCard', back_populates='health_maps')
|
||||||
1
src/medical_info/db/schemas/__init__.py
Normal file
1
src/medical_info/db/schemas/__init__.py
Normal file
@@ -0,0 +1 @@
|
|||||||
|
from .medical_card import *
|
||||||
11
src/medical_info/db/schemas/medical_card.py
Normal file
11
src/medical_info/db/schemas/medical_card.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
class MedicalCard(BaseModel):
|
||||||
|
number: str
|
||||||
|
person_id: str
|
||||||
|
|
||||||
|
class Config:
|
||||||
|
orm_mode = True
|
||||||
|
|
||||||
|
class MedicalCardCreate(BaseModel):
|
||||||
|
person_id: str
|
||||||
23
src/medical_info/db/session.py
Normal file
23
src/medical_info/db/session.py
Normal file
@@ -0,0 +1,23 @@
|
|||||||
|
from functools import lru_cache
|
||||||
|
from typing import Generator
|
||||||
|
|
||||||
|
from sqlalchemy import create_engine
|
||||||
|
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||||
|
|
||||||
|
from medical_info.config import get_settings
|
||||||
|
|
||||||
|
engine = create_engine(get_settings().database_url, pool_pre_ping=True)
|
||||||
|
|
||||||
|
@lru_cache
|
||||||
|
def create_session() -> scoped_session:
|
||||||
|
Session = scoped_session(
|
||||||
|
sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
|
)
|
||||||
|
return Session
|
||||||
|
|
||||||
|
def get_session() -> Generator[scoped_session, None, None]:
|
||||||
|
Session = create_session()
|
||||||
|
try:
|
||||||
|
yield Session
|
||||||
|
finally:
|
||||||
|
Session.remove()
|
||||||
@@ -1,9 +1,16 @@
|
|||||||
from fastapi import Depends
|
from fastapi import Depends
|
||||||
from fastapi.routing import APIRouter
|
from fastapi.routing import APIRouter
|
||||||
|
from typing import List
|
||||||
|
|
||||||
|
from medical_info.db import models
|
||||||
|
from medical_info.db.schemas import MedicalCard
|
||||||
|
from medical_info.services import MedicalCardService, get_medical_cards_service
|
||||||
|
|
||||||
router = APIRouter(prefix='/medical_cards')
|
router = APIRouter(prefix='/medical_cards')
|
||||||
|
|
||||||
@router.get('/')
|
@router.get('/', response_model=List[MedicalCard])
|
||||||
def list_persons():
|
def list_medical_cards(
|
||||||
return "ok"
|
medical_cards_service: MedicalCardService = Depends(get_medical_cards_service)
|
||||||
|
) -> List[models.MedicalCard]:
|
||||||
|
return medical_cards_service.list()
|
||||||
|
|
||||||
|
|||||||
11
src/medical_info/services/__init__.py
Normal file
11
src/medical_info/services/__init__.py
Normal file
@@ -0,0 +1,11 @@
|
|||||||
|
from fastapi import Depends
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from medical_info.db.session import get_session
|
||||||
|
|
||||||
|
from .medical_cards import MedicalCardService
|
||||||
|
|
||||||
|
def get_medical_cards_service(db_session: Session = Depends(get_session)) -> MedicalCardService:
|
||||||
|
return MedicalCardService(db_session)
|
||||||
|
|
||||||
|
__all__ = ('get_medical_cards_service')
|
||||||
52
src/medical_info/services/base.py
Normal file
52
src/medical_info/services/base.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
from typing import Any, Generic, List, Optional, Type, TypeVar
|
||||||
|
|
||||||
|
import sqlalchemy
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from starlette.exceptions import HTTPException
|
||||||
|
|
||||||
|
from medical_info.db.models import Base
|
||||||
|
|
||||||
|
ModelType = TypeVar('ModelType', bound=Base)
|
||||||
|
CreateSchemaType = TypeVar('CreateSchemaType', bound=BaseModel)
|
||||||
|
UpdateSchemaType = TypeVar('UpdateSchemaType', bound=BaseModel)
|
||||||
|
|
||||||
|
class BaseService(Generic[ModelType, CreateSchemaType, UpdateSchemaType]):
|
||||||
|
def __init__(self, model: Type[ModelType], db_session: Session):
|
||||||
|
self.model = model
|
||||||
|
self.db_session = db_session
|
||||||
|
|
||||||
|
def get(self, id: Any) -> Optional[ModelType]:
|
||||||
|
obj: Optional[ModelType] = self.db_session.get(self.model, id)
|
||||||
|
if obj is None:
|
||||||
|
raise HTTPException(status_code=404, detail='NotFound')
|
||||||
|
return obj
|
||||||
|
|
||||||
|
def list(self) -> List[ModelType]:
|
||||||
|
objs: List[ModelType] = self.db_session.query(self.model).all()
|
||||||
|
return objs
|
||||||
|
|
||||||
|
def create(self, obj: CreateSchemaType) -> ModelType:
|
||||||
|
db_obj: ModelType = self.model(**obj.dict())
|
||||||
|
self.db_session.add(db_obj)
|
||||||
|
try:
|
||||||
|
self.db_session.commit()
|
||||||
|
except sqlalchemy.exc.IntegrityError as e:
|
||||||
|
self.db_session.rollback()
|
||||||
|
if 'duplicate key' in str(e):
|
||||||
|
raise HTTPException(status_code=409, detail='Conflict Error')
|
||||||
|
else:
|
||||||
|
raise e
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def update(self, id: Any, obj: UpdateSchemaType) -> Optional[ModelType]:
|
||||||
|
db_obj = self.get(id)
|
||||||
|
for column, value in obj.dict(exclude_unset=True).items():
|
||||||
|
setattr(db_obj, column, value)
|
||||||
|
self.db_session.commit()
|
||||||
|
return db_obj
|
||||||
|
|
||||||
|
def delete(self, id: Any) -> None:
|
||||||
|
db_obj = self.db_session.get(self.model, id)
|
||||||
|
self.db_session.delete(db_obj)
|
||||||
|
self.db_session.commit()
|
||||||
9
src/medical_info/services/medical_cards.py
Normal file
9
src/medical_info/services/medical_cards.py
Normal file
@@ -0,0 +1,9 @@
|
|||||||
|
from typing import Any
|
||||||
|
from medical_info.db.models import MedicalCard
|
||||||
|
from medical_info.db.schemas import MedicalCardCreate
|
||||||
|
from medical_info.services.base import BaseService
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
class MedicalCardService(BaseService[MedicalCard, MedicalCardCreate, Any]):
|
||||||
|
def __init__(self, db_session: Session):
|
||||||
|
super(MedicalCardService, self).__init__(MedicalCard, db_session)
|
||||||
Reference in New Issue
Block a user