Skip to content

Commit f9af9ab

Browse files
committed
add basic clean structure
1 parent 6f8c608 commit f9af9ab

17 files changed

+354
-61
lines changed

.env

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
DB_URL="postgresql+psycopg2://postgres:1234@localhost:5432"

.gitignore

+2-1
Original file line numberDiff line numberDiff line change
@@ -1 +1,2 @@
1-
venv
1+
venv
2+
__pycache__

Makefile

+7-1
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,8 @@
11
run:
2-
fastapi dev main.py
2+
fastapi dev main.py
3+
4+
review:
5+
alembic revision --autogenerate -m "Create User model"
6+
7+
upgrade:
8+
alembic upgrade head

__pycache__/main.cpython-312.pyc

-266 Bytes
Binary file not shown.

alembic.ini

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

database/database.py

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from sqlalchemy import create_engine
2+
from sqlalchemy.orm import sessionmaker
3+
4+
DB_URL = "postgresql://postgres:1234@localhost:5432/postgres"
5+
6+
engine = create_engine(DB_URL)
7+
8+
new_session = sessionmaker(autocommit=False, autoflush=False, bind=engine)

main.py

+6-49
Original file line numberDiff line numberDiff line change
@@ -1,55 +1,12 @@
1-
from fastapi import FastAPI, HTTPException
2-
from typing import List
1+
from fastapi import FastAPI
2+
from sqlalchemy.orm import session
33

4-
from uuid import UUID, uuid4
5-
from models.task_models import Task
4+
from database.database import engine, new_session
5+
from routers.routes import router
66

77

8-
app = FastAPI()
9-
10-
tasks = []
11-
12-
13-
@app.post("/tasks", response_model=Task)
14-
def add_task(task: Task):
15-
task.id = uuid4()
16-
tasks.append(task)
17-
return task
18-
19-
20-
@app.get("/tasks", response_model=List[Task])
21-
async def get_tasks():
22-
return tasks
23-
24-
25-
@app.get("/tasks/{task_id}", response_model=Task)
26-
def get_task_by_id(task_id: UUID):
27-
for task in tasks:
28-
if task.id == task_id:
29-
return task
30-
31-
raise HTTPException(status_code=404, detail="Task not found")
32-
33-
34-
@app.put("/tasks/{task_id}")
35-
def update_task(task_id: UUID, task_update: Task):
36-
for i, task in enumerate(tasks):
37-
if task.id == task_id:
38-
updated_task = task.copy(update=task_update.dict(exclude_unset=True))
39-
tasks[i] = updated_task
40-
return updated_task
41-
42-
raise HTTPException(status_code=404, detail="Task not found")
43-
44-
45-
@app.delete("/tasks/{task_id}")
46-
def delete_task(task_id: UUID):
47-
for i, task in enumerate(tasks):
48-
if task.id == task_id:
49-
tasks.pop(i)
50-
return {"ok": "task deleted successfully"}
51-
raise HTTPException(status_code=404, detail="Task not found")
52-
8+
app = FastAPI(title="Trading App", version="1.0")
9+
app.include_router(router)
5310

5411
if __name__ == "__main__":
5512
import uvicorn

migrations/README

Whitespace-only changes.

migrations/env.py

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

migrations/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,35 @@
1+
"""Create User model
2+
3+
Revision ID: 6b78fdfedaa6
4+
Revises:
5+
Create Date: 2024-09-09 11:55:24.008408
6+
7+
"""
8+
from typing import Sequence, Union
9+
10+
from alembic import op
11+
import sqlalchemy as sa
12+
13+
14+
# revision identifiers, used by Alembic.
15+
revision: str = '6b78fdfedaa6'
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('users',
24+
sa.Column('id', sa.Integer(), nullable=False),
25+
sa.Column('name', sa.String(length=50), nullable=False),
26+
sa.PrimaryKeyConstraint('id'),
27+
sa.UniqueConstraint('name')
28+
)
29+
# ### end Alembic commands ###
30+
31+
32+
def downgrade() -> None:
33+
# ### commands auto generated by Alembic - please adjust! ###
34+
op.drop_table('users')
35+
# ### end Alembic commands ###
-640 Bytes
Binary file not shown.

models/task_models.py

-10
This file was deleted.

models/user.py

+16
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
from sqlalchemy import Column, String, Integer
2+
from sqlalchemy.orm import Mapped, mapped_column, DeclarativeBase
3+
4+
5+
class Base(DeclarativeBase):
6+
pass
7+
8+
9+
class UserModel(Base):
10+
__tablename__ = "users"
11+
12+
id: Mapped[int] = mapped_column(Integer, primary_key=True)
13+
name: Mapped[str] = mapped_column(String(50), unique=True, nullable=False)
14+
15+
def __repr__(self):
16+
return f"id: {self.id}, name: {self.name}"

0 commit comments

Comments
 (0)