Skip to content

Commit ed13972

Browse files
committed
Initial sqlalchemy example
1 parent b824342 commit ed13972

File tree

18 files changed

+1499
-0
lines changed

18 files changed

+1499
-0
lines changed

fastapi-sqlalchemy/.flake8

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
[flake8]
2+
max-line-length = 89
3+
exclude=.venv,.git
4+
ignore = W503
5+
extend-ignore =
6+
# See https://github.com/PyCQA/pycodestyle/issues/373
7+
E203,

fastapi-sqlalchemy/.projectroot

Whitespace-only changes.

fastapi-sqlalchemy/alembic.ini

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
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 files
8+
# file_template = %%(rev)s_%%(slug)s
9+
10+
# sys.path path, will be prepended to sys.path if present.
11+
# defaults to the current working directory.
12+
prepend_sys_path = .
13+
14+
# timezone to use when rendering the date within the migration file
15+
# as well as the filename.
16+
# If specified, requires the python-dateutil library that can be
17+
# installed by adding `alembic[tz]` to the pip requirements
18+
# string value is passed to dateutil.tz.gettz()
19+
# leave blank for localtime
20+
# timezone =
21+
22+
# max length of characters to apply to the
23+
# "slug" field
24+
# truncate_slug_length = 40
25+
26+
# set to 'true' to run the environment during
27+
# the 'revision' command, regardless of autogenerate
28+
# revision_environment = false
29+
30+
# set to 'true' to allow .pyc and .pyo files without
31+
# a source .py file to be detected as revisions in the
32+
# versions/ directory
33+
# sourceless = false
34+
35+
# version location specification; This defaults
36+
# to alembic/versions. When using multiple version
37+
# directories, initial revisions must be specified with --version-path.
38+
# The path separator used here should be the separator specified by "version_path_separator"
39+
# version_locations = %(here)s/bar:%(here)s/bat:alembic/versions
40+
41+
# Logging configuration
42+
[loggers]
43+
keys = root,sqlalchemy,alembic
44+
45+
[handlers]
46+
keys = console
47+
48+
[formatters]
49+
keys = generic
50+
51+
[logger_root]
52+
level = WARN
53+
handlers = console
54+
qualname =
55+
56+
[logger_sqlalchemy]
57+
level = WARN
58+
handlers =
59+
qualname = sqlalchemy.engine
60+
61+
[logger_alembic]
62+
level = INFO
63+
handlers =
64+
qualname = alembic
65+
66+
[handler_console]
67+
class = StreamHandler
68+
args = (sys.stderr,)
69+
level = NOTSET
70+
formatter = generic
71+
72+
[formatter_generic]
73+
format = %(levelname)-5.5s [%(name)s] %(message)s
74+
datefmt = %H:%M:%S

fastapi-sqlalchemy/alembic/README

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

fastapi-sqlalchemy/alembic/env.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
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+
8+
# this is the Alembic Config object, which provides
9+
# access to the values within the .ini file in use.
10+
config = context.config # type: ignore
11+
12+
# Interpret the config file for Python logging.
13+
# This line sets up loggers basically.
14+
fileConfig(config.config_file_name)
15+
16+
# add your model's MetaData object here
17+
# for 'autogenerate' support
18+
# from myapp import mymodel
19+
# target_metadata = mymodel.Base.metadata
20+
# target_metadata = None
21+
22+
from main.database import Base # noqa
23+
24+
target_metadata = Base.metadata
25+
26+
# other values from the config, defined by the needs of env.py,
27+
# can be acquired:
28+
# my_important_option = config.get_main_option("my_important_option")
29+
# ... etc.
30+
31+
32+
def get_url():
33+
return "sqlite:///./db.sqlite3"
34+
35+
36+
def run_migrations_offline():
37+
"""Run migrations in 'offline' mode.
38+
39+
This configures the context with just a URL
40+
and not an Engine, though an Engine is acceptable
41+
here as well. By skipping the Engine creation
42+
we don't even need a DBAPI to be available.
43+
44+
Calls to context.execute() here emit the given string to the
45+
script output.
46+
47+
"""
48+
url = get_url()
49+
context.configure(
50+
url=url,
51+
target_metadata=target_metadata,
52+
literal_binds=True,
53+
dialect_opts={"paramstyle": "named"},
54+
)
55+
56+
with context.begin_transaction():
57+
context.run_migrations()
58+
59+
60+
def run_migrations_online():
61+
"""Run migrations in 'online' mode.
62+
63+
In this scenario we need to create an Engine
64+
and associate a connection with the context.
65+
66+
"""
67+
configuration = config.get_section(config.config_ini_section)
68+
configuration["sqlalchemy.url"] = get_url()
69+
connectable = engine_from_config(
70+
configuration,
71+
prefix="sqlalchemy.",
72+
poolclass=pool.NullPool,
73+
)
74+
75+
with connectable.connect() as connection:
76+
context.configure(connection=connection, target_metadata=target_metadata)
77+
78+
with context.begin_transaction():
79+
context.run_migrations()
80+
81+
82+
if context.is_offline_mode():
83+
run_migrations_offline()
84+
else:
85+
run_migrations_online()
Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
"""${message}
2+
3+
Revision ID: ${up_revision}
4+
Revises: ${down_revision | comma,n}
5+
Create Date: ${create_date}
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
${imports if imports else ""}
11+
12+
# revision identifiers, used by Alembic.
13+
revision = ${repr(up_revision)}
14+
down_revision = ${repr(down_revision)}
15+
branch_labels = ${repr(branch_labels)}
16+
depends_on = ${repr(depends_on)}
17+
18+
19+
def upgrade():
20+
${upgrades if upgrades else "pass"}
21+
22+
23+
def downgrade():
24+
${downgrades if downgrades else "pass"}
Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
"""Add initial models
2+
3+
Revision ID: e690282050a1
4+
Revises:
5+
Create Date: 2021-09-09 17:27:04.631432
6+
7+
"""
8+
from alembic import op
9+
import sqlalchemy as sa
10+
11+
12+
# revision identifiers, used by Alembic.
13+
revision = "e690282050a1"
14+
down_revision = None
15+
branch_labels = None
16+
depends_on = None
17+
18+
19+
def upgrade():
20+
# ### commands auto generated by Alembic - please adjust! ###
21+
op.create_table(
22+
"directors",
23+
sa.Column("id", sa.Integer(), nullable=False),
24+
sa.Column("name", sa.String(), nullable=True),
25+
sa.PrimaryKeyConstraint("id"),
26+
)
27+
op.create_index(op.f("ix_directors_id"), "directors", ["id"], unique=False)
28+
op.create_index(op.f("ix_directors_name"), "directors", ["name"], unique=True)
29+
op.create_table(
30+
"movies",
31+
sa.Column("id", sa.Integer(), nullable=False),
32+
sa.Column("title", sa.String(), nullable=True),
33+
sa.Column("imdb_id", sa.String(), nullable=True),
34+
sa.Column("year", sa.Integer(), nullable=True),
35+
sa.Column("image_url", sa.String(), nullable=True),
36+
sa.Column("imdb_rating", sa.Float(), nullable=True),
37+
sa.Column("imdb_rating_count", sa.String(), nullable=True),
38+
sa.PrimaryKeyConstraint("id"),
39+
)
40+
op.create_index(op.f("ix_movies_id"), "movies", ["id"], unique=False)
41+
op.create_index(op.f("ix_movies_imdb_id"), "movies", ["imdb_id"], unique=False)
42+
# ### end Alembic commands ###
43+
44+
45+
def downgrade():
46+
# ### commands auto generated by Alembic - please adjust! ###
47+
op.drop_index(op.f("ix_movies_imdb_id"), table_name="movies")
48+
op.drop_index(op.f("ix_movies_id"), table_name="movies")
49+
op.drop_table("movies")
50+
op.drop_index(op.f("ix_directors_name"), table_name="directors")
51+
op.drop_index(op.f("ix_directors_id"), table_name="directors")
52+
op.drop_table("directors")
53+
# ### end Alembic commands ###

fastapi-sqlalchemy/api/__init__.py

Whitespace-only changes.

fastapi-sqlalchemy/api/definitions/__init__.py

Whitespace-only changes.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
import strawberry
2+
3+
from main.models import Director as DirectorModel
4+
5+
6+
@strawberry.type
7+
class Director:
8+
id: int
9+
name: str
10+
11+
@classmethod
12+
def from_instance(cls, instance: DirectorModel):
13+
return cls(
14+
id=instance.id,
15+
name=instance.name,
16+
)

0 commit comments

Comments
 (0)