Skip to content

Commit 44801b8

Browse files
committed
feat: Added a database
1 parent 79b19c8 commit 44801b8

21 files changed

+1096
-174
lines changed

.github/workflows/pipeline.yaml

+2
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@ jobs:
1414
cache: 'poetry'
1515
- name: Install dependencies
1616
run: poetry install --no-interaction --no-ansi
17+
- name: Build and run Docker test container
18+
run: make docker-test-up
1719
- name: Lint
1820
run: make lint-ci
1921
- name: Test

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33
__pycache__/
44
*.py[cod]
55
*$py.class
6-
.coverage
6+
.coverage
7+
.env

Dockerfile

+5-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ FROM python:3.10.6-alpine AS builder
22
WORKDIR /code
33
COPY poetry.lock pyproject.toml /code/
44

5-
RUN apk add build-base libffi-dev curl
5+
RUN apk add --no-cache build-base libffi-dev curl netcat-openbsd
66
ENV POETRY_NO_INTERACTION=1 \
77
POETRY_VIRTUALENVS_IN_PROJECT=1 \
88
POETRY_VIRTUALENVS_CREATE=1 \
@@ -19,9 +19,12 @@ WORKDIR /code
1919

2020
COPY --from=builder /code /code
2121
COPY ./src /code/src
22+
COPY ./alembic.ini /code/alembic.ini
23+
COPY ./alembic /code/alembic
24+
COPY ./docker_start.sh /code/docker_start.sh
2225

2326
RUN addgroup --gid 1000 pyweb
2427
RUN adduser pyweb -h /code -u 1000 -G pyweb -DH
2528
USER 1000
2629

27-
CMD ["/code/.venv/bin/uvicorn", "src.main:app", "--host", "0.0.0.0", "--port", "80"]
30+
CMD ["/bin/sh", "/code/docker_start.sh"]

Makefile

+14-11
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,11 @@
1+
# TODO: Commands could be cleaned up
2+
13
install:
24
poetry install
35
build:
4-
docker build -t pyweb-image .
6+
docker-compose build -t pyweb-image .
57
run:
6-
docker-compose up -d
8+
poetry run uvicorn src.main:app --port 80
79
stop:
810
docker-compose down --volumes
911
lint:
@@ -16,12 +18,13 @@ lint-ci:
1618
poetry run mypy src tests
1719
test:
1820
poetry run pytest --cov=src tests/
19-
run-docker:
20-
docker run -d --name epam-pyweb -p 80:80 pyweb-image
21-
stop-docker:
22-
docker stop epam-pyweb
23-
docker rm epam-pyweb
24-
clean-docker:
25-
docker stop epam-pyweb
26-
docker rm epam-pyweb
27-
docker rmi pyweb-image
21+
docker-run:
22+
docker-compose up -d
23+
docker-stop:
24+
docker-compose down
25+
docker-stop-v:
26+
docker-compose down --volumes
27+
docker-test-up:
28+
docker-compose -f docker-compose.test.yaml up -d --build
29+
docker-test-down:
30+
docker-compose -f docker-compose.test.yaml down --volumes

alembic.ini

+117
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,117 @@
1+
# A generic, single database configuration.
2+
3+
[alembic]
4+
# path to migration scripts
5+
script_location = alembic
6+
7+
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
8+
# Uncomment the line below if you want the files to be prepended with date and time
9+
# see https://alembic.sqlalchemy.org/en/latest/tutorial.html#editing-the-ini-file
10+
# for all available tokens
11+
# file_template = %%(year)d_%%(month).2d_%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
12+
file_template = %%(year)d-%%(month).2d-%%(day).2d_%%(slug)s
13+
14+
# sys.path path, will be prepended to sys.path if present.
15+
# defaults to the current working directory.
16+
prepend_sys_path = .
17+
18+
# timezone to use when rendering the date within the migration file
19+
# as well as the filename.
20+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
21+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
22+
# string value is passed to ZoneInfo()
23+
# leave blank for localtime
24+
# timezone =
25+
26+
# max length of characters to apply to the
27+
# "slug" field
28+
# truncate_slug_length = 40
29+
30+
# set to 'true' to run the environment during
31+
# the 'revision' command, regardless of autogenerate
32+
# revision_environment = false
33+
34+
# set to 'true' to allow .pyc and .pyo files without
35+
# a source .py file to be detected as revisions in the
36+
# versions/ directory
37+
# sourceless = false
38+
39+
# version location specification; This defaults
40+
# to alembic/versions. When using multiple version
41+
# directories, initial revisions must be specified with --version-path.
42+
# The path separator used here should be the separator specified by "version_path_separator" below.
43+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
44+
45+
# version path separator; As mentioned above, this is the character used to split
46+
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
47+
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
48+
# Valid values for version_path_separator are:
49+
#
50+
# version_path_separator = :
51+
# version_path_separator = ;
52+
# version_path_separator = space
53+
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
54+
55+
# set to 'true' to search source files recursively
56+
# in each "version_locations" directory
57+
# new in Alembic version 1.10
58+
# recursive_version_locations = false
59+
60+
# the output encoding used when revision files
61+
# are written from script.py.mako
62+
# output_encoding = utf-8
63+
64+
# sqlalchemy.url = driver://user:pass@localhost/dbname
65+
66+
67+
[post_write_hooks]
68+
# post_write_hooks defines scripts or Python functions that are run
69+
# on newly generated revision scripts. See the documentation for further
70+
# detail and examples
71+
72+
# format using "black" - use the console_scripts runner, against the "black" entrypoint
73+
# hooks = black
74+
# black.type = console_scripts
75+
# black.entrypoint = black
76+
# black.options = -l 79 REVISION_SCRIPT_FILENAME
77+
78+
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
79+
# hooks = ruff
80+
# ruff.type = exec
81+
# ruff.executable = %(here)s/.venv/bin/ruff
82+
# ruff.options = --fix REVISION_SCRIPT_FILENAME
83+
84+
# Logging configuration
85+
[loggers]
86+
keys = root,sqlalchemy,alembic
87+
88+
[handlers]
89+
keys = console
90+
91+
[formatters]
92+
keys = generic
93+
94+
[logger_root]
95+
level = WARN
96+
handlers = console
97+
qualname =
98+
99+
[logger_sqlalchemy]
100+
level = WARN
101+
handlers =
102+
qualname = sqlalchemy.engine
103+
104+
[logger_alembic]
105+
level = INFO
106+
handlers =
107+
qualname = alembic
108+
109+
[handler_console]
110+
class = StreamHandler
111+
args = (sys.stderr,)
112+
level = NOTSET
113+
formatter = generic
114+
115+
[formatter_generic]
116+
format = %(levelname)-5.5s [%(name)s] %(message)s
117+
datefmt = %H:%M:%S

alembic/README

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

alembic/env.py

+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
import os
2+
from logging.config import fileConfig
3+
4+
from dotenv import load_dotenv
5+
from sqlalchemy import create_engine
6+
7+
from alembic import context
8+
from src.database import Base
9+
10+
load_dotenv()
11+
12+
# this is the Alembic Config object, which provides
13+
# access to the values within the .ini file in use.
14+
config = context.config
15+
16+
# Interpret the config file for Python logging.
17+
# This line sets up loggers basically.
18+
if config.config_file_name is not None:
19+
fileConfig(config.config_file_name)
20+
21+
# add your model's MetaData object here
22+
# for 'autogenerate' support
23+
24+
target_metadata = Base.metadata
25+
# target_metadata = None
26+
27+
# other values from the config, defined by the needs of env.py,
28+
# can be acquired:
29+
# my_important_option = config.get_main_option("my_important_option")
30+
# ... etc.
31+
32+
33+
def run_migrations_offline() -> None:
34+
"""Run migrations in 'offline' mode.
35+
36+
This configures the context with just a URL
37+
and not an Engine, though an Engine is acceptable
38+
here as well. By skipping the Engine creation
39+
we don't even need a DBAPI to be available.
40+
41+
Calls to context.execute() here emit the given string to the
42+
script output.
43+
44+
"""
45+
url = config.get_main_option("sqlalchemy.url", os.environ["DATABASE_URL"])
46+
context.configure(
47+
url=url,
48+
target_metadata=target_metadata,
49+
literal_binds=True,
50+
dialect_opts={"paramstyle": "named"},
51+
)
52+
53+
with context.begin_transaction():
54+
context.run_migrations()
55+
56+
57+
def run_migrations_online() -> None:
58+
"""Run migrations in 'online' mode.
59+
60+
In this scenario we need to create an Engine
61+
and associate a connection with the context.
62+
63+
"""
64+
url = os.environ["DATABASE_URL"]
65+
connectable = create_engine(url)
66+
67+
with connectable.connect() as connection:
68+
context.configure(connection=connection, target_metadata=target_metadata)
69+
70+
with context.begin_transaction():
71+
context.run_migrations()
72+
73+
74+
if context.is_offline_mode():
75+
run_migrations_offline()
76+
else:
77+
run_migrations_online()

alembic/script.py.mako

+26
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
${imports if imports else ""}
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = ${repr(up_revision)}
16+
down_revision: Union[str, None] = ${repr(down_revision)}
17+
branch_labels: Union[str, Sequence[str], None] = ${repr(branch_labels)}
18+
depends_on: Union[str, Sequence[str], None] = ${repr(depends_on)}
19+
20+
21+
def upgrade() -> None:
22+
${upgrades if upgrades else "pass"}
23+
24+
25+
def downgrade() -> None:
26+
${downgrades if downgrades else "pass"}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
"""Added projects table
2+
3+
Revision ID: 667fd2bcc9fd
4+
Revises:
5+
Create Date: 2024-02-21 20:06:22.908882
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
import sqlalchemy as sa
11+
12+
from alembic import op
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = "667fd2bcc9fd"
16+
down_revision: Union[str, None] = None
17+
branch_labels: Union[str, Sequence[str], None] = None
18+
depends_on: Union[str, Sequence[str], None] = None
19+
20+
21+
def upgrade() -> None:
22+
# ### commands auto generated by Alembic - please adjust! ###
23+
op.create_table(
24+
"projects",
25+
sa.Column("id", sa.UUID(), nullable=False),
26+
sa.Column("name", sa.String(length=40), nullable=False),
27+
sa.Column("description", sa.Text(), nullable=True),
28+
sa.PrimaryKeyConstraint("id"),
29+
)
30+
# ### end Alembic commands ###
31+
32+
33+
def downgrade() -> None:
34+
# ### commands auto generated by Alembic - please adjust! ###
35+
op.drop_table("projects")
36+
# ### end Alembic commands ###

docker-compose.test.yaml

+21
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
version: "3.8"
2+
3+
services:
4+
app:
5+
build: .
6+
container_name: pyweb_test
7+
ports:
8+
- "8080:80"
9+
depends_on:
10+
- test_db
11+
environment:
12+
- DATABASE_URL=postgresql+psycopg://postgres:postgres@test_db:5432/test
13+
test_db:
14+
image: postgres:15
15+
container_name: test_db
16+
environment:
17+
- POSTGRES_USER=postgres
18+
- POSTGRES_PASSWORD=postgres
19+
- POSTGRES_DB=test
20+
ports:
21+
- "3254:5432"

docker-compose.yaml

+17-1
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,24 @@ services:
44
app:
55
build: .
66
container_name: pyweb
7-
command: /code/.venv/bin/uvicorn src.main:app --host 0.0.0.0 --port 80 --reload
87
ports:
98
- "80:80"
109
volumes:
1110
- ./src:/code/src
11+
depends_on:
12+
- db
13+
environment:
14+
- DATABASE_URL=postgresql+psycopg://postgres:postgres@db:5432/pyweb
15+
- RELOAD=true
16+
db:
17+
image: postgres:15
18+
container_name: db
19+
environment:
20+
- POSTGRES_USER=postgres
21+
- POSTGRES_PASSWORD=postgres
22+
- POSTGRES_DB=pyweb
23+
volumes:
24+
- db_data:/var/lib/postgresql/data/
25+
26+
volumes:
27+
db_data:

0 commit comments

Comments
 (0)