Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: create initial database setup for project (#49) #80

Merged
merged 12 commits into from
Sep 27, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions backend/.gitignore
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
.env

# Created by https://www.toptal.com/developers/gitignore/api/python
# Edit at https://www.toptal.com/developers/gitignore?templates=python

Expand Down
17 changes: 17 additions & 0 deletions backend/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,11 @@ help:
@echo " ci Install dependencies, run lints and tests"
@echo " docs Generate the documentation"
@echo " serve Run the (development) server"
@echo " migrate Create alembic versions and upgrade"
@echO ""
@echo " alembic-check Run alembic check"
@echo " alembic-autogenerate Autogenerte alembic version"
@echo " alembic-upgrade Upgrade database to head"

.PHONY: deps
deps:
Expand Down Expand Up @@ -75,3 +80,15 @@ docs:
.PHONY: serve
serve:
pipenv run uvicorn app.main:app --host 0.0.0.0 --port 8080 --reload

.PHONY: alembic-check
alembic-check:
alembic check

.PHONY: alembic-autogenerate
alembic-autogenerate:
alembic revision --autogenerate

.PHONY: alembic-upgrade
alembic-upgrade:
alembic upgrade head
22 changes: 19 additions & 3 deletions backend/Pipfile
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,28 @@ name = "pypi"

[packages]
fastapi = "*"
pydantic = "*"
uvicorn = "*"
python-dotenv = "*"
httpx = "*"
install = "*"
pip = "*"
pydantic = {extras = ["email"], version = "*"}
pydantic-settings = "*"
python-dotenv = "*"
requests-mock = "*"
tenacity = "*"
uvicorn = "*"
jose = {extras = ["cryptography"], version = "*"}
passlib = {extras = ["bcrypt"], version = "*"}
psycopg2-binary = "*"
python-dateutil = "*"
sqlalchemy = "*"

[dev-packages]
black = "*"
flake8 = "*"
install = "*"
isort = "*"
mypy = "*"
pip = "*"
pytest = "*"
pytest-asyncio = "*"
pytest-cov = "*"
Expand All @@ -24,6 +35,11 @@ pytest-subprocess = "*"
sphinx = "*"
sphinx-rtd-theme = "*"
starlette = "*"
types-python-jose = "*"
types-passlib = "*"
sqlalchemy-stubs = "*"
faker = "*"
pytest-faker = "*"

[requires]
python_version = "3.10"
633 changes: 458 additions & 175 deletions backend/Pipfile.lock

Large diffs are not rendered by default.

73 changes: 73 additions & 0 deletions backend/alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
[alembic]
# path to migration scripts
script_location = alembic

# template used to generate migration files
# file_template = %%(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.
# string value is passed to dateutil.tz.gettz()
# leave blank for localtime
timezone = Europe/Berlin

# 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
# version_locations = %(here)s/bar %(here)s/bat alembic/versions

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

# 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
94 changes: 94 additions & 0 deletions backend/alembic/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
from __future__ import with_statement

import os

from alembic import context
from dotenv import load_dotenv
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig

# Load environment
env = os.environ
load_dotenv()

# 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.
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 = None

from app.db.base import Base # noqa
import app.models # noqa

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 get_url():
user = os.getenv("POSTGRES_USER", "postgres")
password = os.getenv("POSTGRES_PASSWORD", "")
server = os.getenv("POSTGRES_HOST", "db")
port = os.getenv("POSTGRES_PORT", 5432)
db = os.getenv("POSTGRES_DB", "app")
return f"postgresql://{user}:{password}@{server}:{port}/{db}"


def run_migrations_offline():
"""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 = get_url()
context.configure(
url=url, target_metadata=target_metadata, literal_binds=True, compare_type=True
)

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


def run_migrations_online():
"""Run migrations in 'online' mode.

In this scenario we need to create an Engine
and associate a connection with the context.

"""
configuration = config.get_section(config.config_ini_section)
configuration["sqlalchemy.url"] = get_url()
connectable = engine_from_config(
configuration, prefix="sqlalchemy.", poolclass=pool.NullPool,
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata, compare_type=True
)

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 backend/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 alembic import op
import sqlalchemy as sa
${imports if imports else ""}

import app.models.guid # noqa

# 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():
${upgrades if upgrades else "pass"}


def downgrade():
${downgrades if downgrades else "pass"}
43 changes: 43 additions & 0 deletions backend/alembic/versions/315675882512_.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
"""empty message

Revision ID: 315675882512
Revises:
Create Date: 2023-09-27 14:55:20.332132+02:00

"""
from alembic import op
import sqlalchemy as sa


import app.models.guid # noqa

# revision identifiers, used by Alembic.
revision = '315675882512'
down_revision = None
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('adminmessages',
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('uuid', app.models.guid.GUID(length=36), nullable=False),
sa.Column('title', sa.String(length=255), nullable=False),
sa.Column('text', sa.Text(), nullable=True),
sa.Column('active_start', sa.DateTime(), nullable=False),
sa.Column('active_stop', sa.DateTime(), nullable=False),
sa.Column('enabled', sa.Boolean(), nullable=False),
sa.PrimaryKeyConstraint('id')
)
op.create_index(op.f('ix_adminmessages_id'), 'adminmessages', ['id'], unique=False)
op.create_index(op.f('ix_adminmessages_uuid'), 'adminmessages', ['uuid'], unique=True)
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_adminmessages_uuid'), table_name='adminmessages')
op.drop_index(op.f('ix_adminmessages_id'), table_name='adminmessages')
op.drop_table('adminmessages')
# ### end Alembic commands ###
Empty file added backend/app/api/__init__.py
Empty file.
Empty file.
5 changes: 5 additions & 0 deletions backend/app/api/api_v1/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
from app.api.api_v1.endpoints import adminmsgs
from fastapi import APIRouter

api_router = APIRouter()
api_router.include_router(adminmsgs.router, prefix="/adminmsgs", tags=["adminmsgs"])
Empty file.
20 changes: 20 additions & 0 deletions backend/app/api/api_v1/endpoints/adminmsgs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
from app import crud, models, schemas
from app.api import deps
from fastapi import APIRouter, Depends
from sqlalchemy.orm import Session

router = APIRouter()


@router.get("/", response_model=list[schemas.AdminMessage])
def read_adminmsgs(
db: Session = Depends(deps.get_db),
skip: int = 0,
limit: int = 100,
) -> list[schemas.AdminMessage]:
"""Retrieve all admin messages"""
users = [
schemas.AdminMessage.model_validate(db_obj)
for db_obj in crud.adminmessage.get_multi(db, skip=skip, limit=limit)
]
return users
11 changes: 11 additions & 0 deletions backend/app/api/deps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
from typing import Iterator

from app.db.session import SessionLocal


def get_db() -> Iterator[SessionLocal]: # type: ignore[valid-type]
try:
db = SessionLocal()
yield db
finally:
db.close()
Empty file.
20 changes: 20 additions & 0 deletions backend/app/api/internal/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import subprocess

from app.api.internal.endpoints import proxy, remote
from app.core.config import settings
from fastapi import APIRouter, Response

api_router = APIRouter()

api_router.include_router(proxy.router, prefix="/proxy", tags=["proxy"])
api_router.include_router(remote.router, prefix="/remote", tags=["remote"])


@api_router.get("/version")
async def version():
"""Return REEV software version"""
if settings.REEV_VERSION:
version = settings.REEV_VERSION
else:
version = subprocess.check_output(["git", "describe", "--tags", "--dirty"]).strip()
return Response(content=version)
Empty file.
Loading