Skip to content

Commit 0574456

Browse files
committed
Add first endpoint
1 parent 0d2484e commit 0574456

15 files changed

+866
-1
lines changed

alembic.ini

Lines changed: 117 additions & 0 deletions
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 = migrations
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+
13+
# sys.path path, will be prepended to sys.path if present.
14+
# defaults to the current working directory.
15+
prepend_sys_path = .
16+
17+
# timezone to use when rendering the date within the migration file
18+
# as well as the filename.
19+
# If specified, requires the python>=3.9 or backports.zoneinfo library.
20+
# Any required deps can installed by adding `alembic[tz]` to the pip requirements
21+
# string value is passed to ZoneInfo()
22+
# leave blank for localtime
23+
# timezone =
24+
25+
# max length of characters to apply to the
26+
# "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 migrations/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:migrations/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+
# DSN
64+
sqlalchemy.url = postgresql+asyncpg://%(DB_USER)s:%(DB_PASS)s@%(DB_HOST)s:%(DB_PORT)s/%(DB_NAME)s?async_fallback=True
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

main.py renamed to api/__init__.py

File renamed without changes.

api/config.py

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
import os
2+
from dotenv import load_dotenv
3+
4+
load_dotenv()
5+
6+
DB_HOST = os.environ.get("DB_HOST")
7+
DB_PORT = os.environ.get("DB_PORT")
8+
DB_NAME = os.environ.get("DB_NAME")
9+
DB_USER = os.environ.get("DB_USER")
10+
DB_PASS = os.environ.get("DB_PASS")

api/database.py

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
from typing import AsyncGenerator
2+
3+
from sqlalchemy.orm import sessionmaker
4+
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
5+
6+
from config import DB_HOST, DB_NAME, DB_PASS, DB_PORT, DB_USER
7+
8+
DATABASE_URL = f"postgresql+asyncpg://{DB_USER}:{DB_PASS}@{DB_HOST}:{DB_PORT}/{DB_NAME}"
9+
10+
11+
engine = create_async_engine(DATABASE_URL)
12+
async_session_maker = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
13+
14+
15+
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
16+
async with async_session_maker() as session:
17+
yield session

api/main.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
from fastapi import FastAPI, Request, status
2+
from fastapi.encoders import jsonable_encoder
3+
from pydantic import ValidationError
4+
from fastapi.responses import JSONResponse
5+
from v1.router import router as router_restaurant
6+
7+
app = FastAPI(
8+
title="Ylab Homework First"
9+
)
10+
11+
12+
@app.exception_handler(ValidationError)
13+
async def validation_exception_handler(request: Request, exc: ValidationError):
14+
return JSONResponse(
15+
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
16+
content=jsonable_encoder({"detail": exc.errors()}),
17+
)
18+
19+
app.include_router(router_restaurant)
20+
21+
# @app.post('/users/{user_id}')
22+
# def change_user_name(user_id: int, new_name: str):
23+
# current_user = list(filter(lambda user: user.get('id') == user_id, fake_users))[0]
24+
# current_user['name'] = new_name
25+
#
26+
# return {'status': 200, 'data': current_user}

api/v1/router.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
from fastapi import APIRouter, Depends
2+
from sqlalchemy import select
3+
from sqlalchemy.ext.asyncio import AsyncSession
4+
5+
from database import get_async_session
6+
from .models import Menu
7+
from .schemas import MenuDTO
8+
9+
router = APIRouter(
10+
prefix="/api/v1/menus",
11+
tags=["Menus"]
12+
)
13+
14+
15+
@router.get("/")
16+
async def root(session: AsyncSession = Depends(get_async_session)):
17+
query = select(Menu)
18+
# print(query)
19+
# result = list(await session.scalars(query))
20+
result = await session.execute(query)
21+
result_orm = result.scalars().all()
22+
# print(result_orm)
23+
result_dto = [MenuDTO.model_validate(row, from_attributes=True) for row in result_orm]
24+
# print(result_dto)
25+
26+
return result_dto
27+
28+
29+
# @router.post('/')
30+
# async def add_restaurant(new_restaurant: RestaurantAdd, sessions: AsyncSession = Depends(get_async_session)):
31+
# return {'status': 'success', 'message': ''}

api/v1/schemas.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
from pydantic import BaseModel, UUID4
2+
3+
4+
class MenuDTO(BaseModel):
5+
id: UUID4
6+
title: str
7+
description: str
8+

migrations/README

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Generic single-database configuration.

migrations/env.py

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

migrations/script.py.mako

Lines changed: 26 additions & 0 deletions
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"}
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""dish back and submenu redacted
2+
3+
Revision ID: 804eb99fe48e
4+
Revises: bf606edaead7
5+
Create Date: 2024-01-22 13:28:25.496591
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 = '804eb99fe48e'
16+
down_revision: Union[str, None] = 'bf606edaead7'
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+
pass
24+
# ### end Alembic commands ###
25+
26+
27+
def downgrade() -> None:
28+
# ### commands auto generated by Alembic - please adjust! ###
29+
pass
30+
# ### end Alembic commands ###
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
"""dish redacted
2+
3+
Revision ID: bf606edaead7
4+
Revises: c6c4c8da3a40
5+
Create Date: 2024-01-22 13:17:44.606146
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 = 'bf606edaead7'
16+
down_revision: Union[str, None] = 'c6c4c8da3a40'
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+
pass
24+
# ### end Alembic commands ###
25+
26+
27+
def downgrade() -> None:
28+
# ### commands auto generated by Alembic - please adjust! ###
29+
pass
30+
# ### end Alembic commands ###

0 commit comments

Comments
 (0)