diff --git a/.gitignore b/.gitignore index 0d87b56..5ac6773 100644 --- a/.gitignore +++ b/.gitignore @@ -174,3 +174,5 @@ pyvenv.cfg .venv pip-selfcheck.json +# vim tags +tags diff --git a/alembic.ini b/alembic.ini new file mode 100644 index 0000000..eb00c9e --- /dev/null +++ b/alembic.ini @@ -0,0 +1,110 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +script_location = alembic + +# 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 = app + +# timezone to use when rendering the date within the migration file +# as well as the filename. +# If specified, requires the python-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# string value is passed to dateutil.tz.gettz() +# 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 alembic/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:alembic/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 = + + +[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 + +# 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 diff --git a/alembic/README b/alembic/README new file mode 100644 index 0000000..98e4f9c --- /dev/null +++ b/alembic/README @@ -0,0 +1 @@ +Generic single-database configuration. \ No newline at end of file diff --git a/alembic/env.py b/alembic/env.py new file mode 100644 index 0000000..60b0977 --- /dev/null +++ b/alembic/env.py @@ -0,0 +1,90 @@ +from logging.config import fileConfig + +from sqlalchemy import engine_from_config +from sqlalchemy import pool + +from alembic import context +import os +import sys +from dotenv import load_dotenv +BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +load_dotenv(os.path.join(BASE_DIR, ".env")) +sys.path.append(BASE_DIR) + + +# this is the Alembic Config object, which provides +# access to the values within the .ini file in use. +config = context.config +print(os.environ["DATABASE_URL"]) +config.set_main_option("sqlalchemy.url", os.environ["DATABASE_URL"]) + +# 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 = None + +from app.models import models +target_metadata = models.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 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() diff --git a/alembic/script.py.mako b/alembic/script.py.mako new file mode 100644 index 0000000..fbc4b07 --- /dev/null +++ b/alembic/script.py.mako @@ -0,0 +1,26 @@ +"""${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 +${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"} diff --git a/alembic/versions/b9ad7be93704_init.py b/alembic/versions/b9ad7be93704_init.py new file mode 100644 index 0000000..bd9e4ad --- /dev/null +++ b/alembic/versions/b9ad7be93704_init.py @@ -0,0 +1,41 @@ +"""init + +Revision ID: b9ad7be93704 +Revises: +Create Date: 2023-08-07 21:31:23.021550 + +""" +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision: str = 'b9ad7be93704' +down_revision: Union[str, None] = None +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.create_table('item', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(), nullable=True), + sa.Column('description', sa.String(), nullable=True), + sa.PrimaryKeyConstraint('id') + ) + op.create_index(op.f('ix_item_description'), 'item', ['description'], unique=False) + op.create_index(op.f('ix_item_id'), 'item', ['id'], unique=False) + op.create_index(op.f('ix_item_title'), 'item', ['title'], unique=False) + # ### end Alembic commands ### + + +def downgrade() -> None: + # ### commands auto generated by Alembic - please adjust! ### + op.drop_index(op.f('ix_item_title'), table_name='item') + op.drop_index(op.f('ix_item_id'), table_name='item') + op.drop_index(op.f('ix_item_description'), table_name='item') + op.drop_table('item') + # ### end Alembic commands ### diff --git a/app/__init__.py b/app/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/alembic.ini b/app/alembic.ini new file mode 100644 index 0000000..0c80eea --- /dev/null +++ b/app/alembic.ini @@ -0,0 +1,108 @@ +# A generic, single database configuration. + +[alembic] +# path to migration scripts +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 +# 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-dateutil library that can be +# installed by adding `alembic[tz]` to the pip requirements +# string value is passed to dateutil.tz.gettz() +# 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 = driver://user:pass@localhost/dbname + + +[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 + +# 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 diff --git a/app/config.py b/app/config.py new file mode 100644 index 0000000..7b75b49 --- /dev/null +++ b/app/config.py @@ -0,0 +1,14 @@ +import os +from dotenv import load_dotenv +from pathlib import Path + +env_path = Path('..') / '.env' +load_dotenv(dotenv_path=env_path) + + +class Settings: + app_name: str = "Awesome API" + admin_email: str + items_per_user: int = 50 + + DATABASE_URL: str = os.getenv("DATABASE_URL") diff --git a/app/crud/__init__.py b/app/crud/__init__.py new file mode 100644 index 0000000..e30f439 --- /dev/null +++ b/app/crud/__init__.py @@ -0,0 +1 @@ +from .item import item diff --git a/app/crud/base.py b/app/crud/base.py new file mode 100644 index 0000000..4e286f7 --- /dev/null +++ b/app/crud/base.py @@ -0,0 +1,70 @@ +from typing import Any, Dict, Generic, List, Optional, Type, TypeVar, Union + +from fastapi.encoders import jsonable_encoder +from pydantic import BaseModel +from sqlalchemy.orm import Session +from fastapi import HTTPException + +from database import Base + +ModelType = TypeVar("ModelType", bound=Base) +CreateSchemaType = TypeVar("CreateSchemaType", bound=BaseModel) +UpdateSchemaType = TypeVar("UpdateSchemaType", bound=BaseModel) + + +class CRUDBase(Generic[ModelType, CreateSchemaType, UpdateSchemaType]): + def __init__(self, model: Type[ModelType]): + """ + CRUD object with default methods to Create, Read, Update, Delete (CRUD). + + **Parameters** + + * `model`: A SQLAlchemy model class + * `schema`: A Pydantic model (schema) class + """ + self.model = model + + def get(self, db: Session, id: Any) -> Optional[ModelType]: + result = db.query(self.model).filter(self.model.id == id).first() + if not result: + raise HTTPException(status_code=404, detail="Item not found") + return result + + def get_multi( + self, db: Session, *, skip: int = 0, limit: int = 100 + ) -> List[ModelType]: + return db.query(self.model).offset(skip).limit(limit).all() + + def create(self, db: Session, *, obj_in: CreateSchemaType) -> ModelType: + obj_in_data = jsonable_encoder(obj_in) + db_obj = self.model(**obj_in_data) # type: ignore + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def update( + self, + db: Session, + *, + db_obj: ModelType, + obj_in: Union[UpdateSchemaType, Dict[str, Any]] + ) -> ModelType: + obj_data = jsonable_encoder(db_obj) + if isinstance(obj_in, dict): + update_data = obj_in + else: + update_data = obj_in.dict(exclude_unset=True) + for field in obj_data: + if field in update_data: + setattr(db_obj, field, update_data[field]) + db.add(db_obj) + db.commit() + db.refresh(db_obj) + return db_obj + + def remove(self, db: Session, *, id: int) -> ModelType: + obj = db.query(self.model).get(id) + db.delete(obj) + db.commit() + return obj diff --git a/app/crud/item.py b/app/crud/item.py new file mode 100644 index 0000000..a395336 --- /dev/null +++ b/app/crud/item.py @@ -0,0 +1,40 @@ +from fastapi import HTTPException +from sqlalchemy.orm import Session + +from models import Item +from schemas.schemas import ItemCreate, ItemUpdate +from crud.base import CRUDBase + + +class CRUDItem(CRUDBase[Item, ItemCreate, ItemUpdate]): + pass + # def get_item(self, db: Session, item_id: int): + # item = db.query(Item).filter(Item.id == item_id).first() + # if not item: + # raise HTTPException(status_code=404, detail="Item not found") + # return item + + # def get_items(self, db: Session, skip: int = 0, limit: int = 100): + # return db.query(Item).offset(skip).limit(limit).all() + + # def create_item(self, db: Session, item: ItemCreate): + # db_item = Item(title=item.title, description=item.description) + # db.add(db_item) + # db.commit() + # db.refresh(db_item) + # return db_item + + # def update_item(self, db: Session, item: ItemUpdate): + # db_item = Item(title=item.title, description=item.description) + # db.add(db_item) + # db.commit() + # db.refresh(db_item) + # return db_item + + # def delete_item(self, db: Session, item_id: int): + # db.query(Item).filter(Item.id == item_id).first().delete() + # db.commit() + # return + + +item = CRUDItem(Item) diff --git a/app/database.py b/app/database.py new file mode 100644 index 0000000..e631c23 --- /dev/null +++ b/app/database.py @@ -0,0 +1,15 @@ +from sqlalchemy import create_engine +from sqlalchemy.ext.declarative import declarative_base +from sqlalchemy.orm import sessionmaker +import config + +SQLALCHEMY_DATABASE_URL = config.Settings.DATABASE_URL +# SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" + +print(SQLALCHEMY_DATABASE_URL) +engine = create_engine( + SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} +) +SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) + +Base = declarative_base() diff --git a/app/main.py b/app/main.py new file mode 100644 index 0000000..5097c9c --- /dev/null +++ b/app/main.py @@ -0,0 +1,51 @@ +from fastapi import Depends, FastAPI +from fastapi.middleware.cors import CORSMiddleware +from sqlalchemy.orm import Session +from schemas import schemas +import database +import crud + +app = FastAPI() +app.add_middleware( + CORSMiddleware, + allow_origins=["*"] +) + + +# Dependency +def get_db(): + db = database.SessionLocal() + try: + yield db + finally: + db.close() + + +@app.get("/") +async def root(): + return {"message": "Hello World"} + + +@app.get("/items/{item_id}", response_model=schemas.Item) +async def get_item(*, db: Session = Depends(get_db), item_id: int): + return crud.item.get(db, item_id) + + +@app.get("/items/", response_model=list[schemas.Item]) +async def get_items(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)): + return crud.item.get_multi(db, skip=skip, limit=limit) + + +@app.post("/items/", response_model=schemas.Item) +async def create_item(item: schemas.ItemCreate, db: Session = Depends(get_db)): + return crud.item.create(db=db, item=item) + + +@app.put("/items/{item_id}", response_model=schemas.ItemUpdate) +async def update_item(item: schemas.ItemUpdate, db: Session = Depends(get_db)): + return crud.item.update(db=db, item=item) + + +@app.delete("/items/{item_id}") +async def delete_item(*, item: schemas.ItemUpdate, db: Session = Depends(get_db), item_id: int): + return crud.remove(item_id) diff --git a/app/models/__init__.py b/app/models/__init__.py new file mode 100644 index 0000000..a6381fc --- /dev/null +++ b/app/models/__init__.py @@ -0,0 +1 @@ +from .item import Item diff --git a/app/models/item.py b/app/models/item.py new file mode 100644 index 0000000..f881d4e --- /dev/null +++ b/app/models/item.py @@ -0,0 +1,11 @@ +from sqlalchemy import Boolean, Column, Integer, String + +from database import Base + + +class Item(Base): + __tablename__ = "item" + + id = Column(Integer, primary_key=True, index=True) + title = Column(String, index=True) + description = Column(String, index=True) diff --git a/app/requirements.txt b/app/requirements.txt new file mode 100644 index 0000000..811f028 --- /dev/null +++ b/app/requirements.txt @@ -0,0 +1,18 @@ +alembic==1.11.2 +annotated-types==0.5.0 +anyio==3.7.1 +click==8.1.6 +fastapi==0.101.0 +greenlet==2.0.2 +h11==0.14.0 +idna==3.4 +Mako==1.2.4 +MarkupSafe==2.1.3 +pydantic==2.1.1 +pydantic_core==2.4.0 +python-dotenv==1.0.0 +sniffio==1.3.0 +SQLAlchemy==2.0.19 +starlette==0.27.0 +typing_extensions==4.7.1 +uvicorn==0.23.2 diff --git a/app/schemas/__init__.py b/app/schemas/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/app/schemas/schemas.py b/app/schemas/schemas.py new file mode 100644 index 0000000..d3627b5 --- /dev/null +++ b/app/schemas/schemas.py @@ -0,0 +1,21 @@ +from pydantic import BaseModel + + +class ItemBase(BaseModel): + title: str + description: str | None = None + + +class Item(ItemBase): + id: int + + class Config: + from_attributes = True + + +class ItemCreate(ItemBase): + pass + + +class ItemUpdate(ItemBase): + pass diff --git a/app/sql_app.db b/app/sql_app.db new file mode 100644 index 0000000..9af13dc Binary files /dev/null and b/app/sql_app.db differ diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..811f028 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +alembic==1.11.2 +annotated-types==0.5.0 +anyio==3.7.1 +click==8.1.6 +fastapi==0.101.0 +greenlet==2.0.2 +h11==0.14.0 +idna==3.4 +Mako==1.2.4 +MarkupSafe==2.1.3 +pydantic==2.1.1 +pydantic_core==2.4.0 +python-dotenv==1.0.0 +sniffio==1.3.0 +SQLAlchemy==2.0.19 +starlette==0.27.0 +typing_extensions==4.7.1 +uvicorn==0.23.2