Skip to content

Commit

Permalink
Add migrations with alembic + API call
Browse files Browse the repository at this point in the history
  • Loading branch information
vmagueta committed Aug 1, 2024
1 parent e10cd01 commit ebc7b2c
Show file tree
Hide file tree
Showing 15 changed files with 334 additions and 6 deletions.
116 changes: 116 additions & 0 deletions alembic.ini
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
# A generic, single database configuration.

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

# 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 migrations/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:migrations/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 = sqlite:///assets/database.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

# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
# hooks = ruff
# ruff.type = exec
# ruff.executable = %(here)s/.venv/bin/ruff
# ruff.options = --fix 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
Binary file modified assets/database.db
Binary file not shown.
9 changes: 5 additions & 4 deletions assets/people.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
Jim Halpert, Sales, Salesman, [email protected]
Dwight Schrute, Sales, Manager, [email protected]
Gabe Lewis, C-Level, CEO, [email protected]
Pam Beasly, General, Recepcionist, [email protected]
Jim Halpert, Sales, Salesman, [email protected], USD
Dwight Schrute, Sales, Manager, [email protected], EUR
Gabe Lewis, C-Level, CEO, [email protected], BRL
Pam Beasly, General, Recepcionist, [email protected], BRL
Bruno, General, Guard, [email protected], BRL
4 changes: 3 additions & 1 deletion dundie/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ def load(filepath):
- Loads to database
"""
table = Table(title="Dunder Mifflin Associates")
headers = ["email", "name", "dept", "role", "created"]
headers = ["email", "name", "dept", "role", "currency", "created"]
for header in headers:
table.add_column(header, style="magenta")

Expand Down Expand Up @@ -72,6 +72,8 @@ def show(output, **query):
table.add_column(key.title().replace("_", " "), style="magenta")

for person in result:
person["value"] = f"{person['value']:.2f}"
person["balance"] = f"{person['balance']:.2f}"
table.add_row(*[str(value) for value in person.values()])

console = Console()
Expand Down
9 changes: 8 additions & 1 deletion dundie/core.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
from dundie.models import Person
from dundie.settings import DATEFMT
from dundie.utils.db import add_movement, add_person
from dundie.utils.exchange import get_rates
from dundie.utils.log import get_logger

log = get_logger()
Expand All @@ -30,7 +31,7 @@ def load(filepath: str) -> ResultDict:
raise e

people = []
headers = ["name", "dept", "role", "email"]
headers = ["name", "dept", "role", "email", "currency"]

with get_session() as session:
for line in csv_data:
Expand Down Expand Up @@ -64,8 +65,13 @@ def read(**query: Query) -> ResultDict:
sql = sql.where(*query_statements) # WHERE ...

with get_session() as session:
currencies = session.exec(
select(Person.currency).distinct(Person.currency)
)
rates = get_rates(currencies)
results = session.exec(sql)
for person in results:
total = rates[person.currency].value * person.balance[0].value
return_data.append(
{
"email": person.email,
Expand All @@ -74,6 +80,7 @@ def read(**query: Query) -> ResultDict:
DATEFMT
),
**person.dict(exclude={"id"}),
**{"value": total},
}
)
return return_data
Expand Down
1 change: 1 addition & 0 deletions dundie/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ class Person(SQLModel, table=True):
name: str = Field(nullable=False)
dept: str = Field(nullable=False, index=True)
role: str = Field(nullable=False)
currency: str = Field(default="USD")

balance: "Balance" = Relationship(back_populates="person")
movement: "Movement" = Relationship(back_populates="person")
Expand Down
1 change: 1 addition & 0 deletions dundie/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@

EMAIL_FROM: str = "[email protected]"
DATEFMT: str = "%d/%m/%Y %H:%M:%S"
API_BASE_URL = "https://economia.awesomeapi.com.br/json/last/USD-{currency}"

ROOT_PATH: str = os.path.dirname(__file__)
DATABASE_PATH: str = os.path.join(ROOT_PATH, "..", "assets", "database.db")
Expand Down
1 change: 1 addition & 0 deletions dundie/utils/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ def add_person(session: Session, instance: Person):
else:
existing.dept = instance.dept
existing.role = instance.role
existing.currency = instance.currency
session.add(existing)
return instance, created

Expand Down
30 changes: 30 additions & 0 deletions dundie/utils/exchange.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
from decimal import Decimal

import httpx
from pydantic import BaseModel, Field

from dundie.settings import API_BASE_URL


class USDRate(BaseModel):
code: str = Field(default="USD")
codein: str = Field(default="USD")
name: str = Field(default="Dolar/Dolar")
value: Decimal = Field(alias="high")


def get_rates(currencies: list[str]) -> dict[str, USDRate]:
"""Get current rate for USD vc Currency."""
return_data = {}
for currency in currencies:
if currency == "USD":
return_data[currency] = USDRate(high=1)
else:
response = httpx.get(API_BASE_URL.format(currency=currency))
if response.status_code == 200:
data = response.json()["USD" + currency]
return_data[currency] = USDRate(**data)
else:
return_data[currency] = USDRate(name="api/error", high=0)

return return_data
1 change: 1 addition & 0 deletions migrations/README
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Generic single-database configuration.
79 changes: 79 additions & 0 deletions migrations/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
from logging.config import fileConfig

from sqlalchemy import engine_from_config
from sqlalchemy import pool

from alembic import context
from dundie import models

# 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 = models.SQLModel.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()
27 changes: 27 additions & 0 deletions migrations/script.py.mako
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""${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
import sqlmodel
${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"}
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
"""Adicionado o campo currency em person
Revision ID: 63699c03d253
Revises: 863e6e940c0a
Create Date: 2024-08-01 15:25:47.385323
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
import sqlmodel


# revision identifiers, used by Alembic.
revision: str = '63699c03d253'
down_revision: Union[str, None] = '863e6e940c0a'
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('person', sa.Column(
'currency', sqlmodel.sql.sqltypes.AutoString(), nullable=True)
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('person', 'currency')
# ### end Alembic commands ###
Loading

0 comments on commit ebc7b2c

Please sign in to comment.