Skip to content

Commit

Permalink
Update fix SQLAlchemy support with ORM (#30)
Browse files Browse the repository at this point in the history
✨ SQLAlchemy ORM support

Improved jsonable_encoder with SQLAlchemy support, tests running with SQLite, improved and updated SQL docs

* ➕ Add SQLAlchemy to development dependencies (not required for using FastAPI)

* ➕ Add sqlalchemy to testing dependencies (not required to use FastAPI)
  • Loading branch information
tiangolo committed Feb 12, 2019
1 parent 9484f93 commit 955e9fc
Show file tree
Hide file tree
Showing 10 changed files with 338 additions and 109 deletions.
1 change: 1 addition & 0 deletions Pipfile
Expand Up @@ -21,6 +21,7 @@ email-validator = "*"
ujson = "*"
flake8 = "*"
python-multipart = "*"
sqlalchemy = "*"

[packages]
starlette = "==0.10.1"
Expand Down
110 changes: 57 additions & 53 deletions Pipfile.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added docs/img/tutorial/sql-databases/image01.png
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
28 changes: 20 additions & 8 deletions docs/src/sql_databases/tutorial001.py
@@ -1,13 +1,15 @@
from fastapi import FastAPI

from sqlalchemy import Boolean, Column, Integer, String, create_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr
from sqlalchemy.orm import scoped_session, sessionmaker

# SQLAlchemy specific code, as with any other app
SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
SQLALCHEMY_DATABASE_URI = "sqlite:///./test.db"
# SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"

engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)
engine = create_engine(
SQLALCHEMY_DATABASE_URI, connect_args={"check_same_thread": False}
)
db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
Expand All @@ -30,15 +32,25 @@ class User(Base):
is_active = Column(Boolean(), default=True)


def get_user(username, db_session):
return db_session.query(User).filter(User.id == username).first()
Base.metadata.create_all(bind=engine)

first_user = db_session.query(User).first()
if not first_user:
u = User(email="johndoe@example.com", hashed_password="notreallyhashed")
db_session.add(u)
db_session.commit()


# Utility
def get_user(db_session, user_id: int):
return db_session.query(User).filter(User.id == user_id).first()


# FastAPI specific code
app = FastAPI()


@app.get("/users/{username}")
def read_user(username: str):
user = get_user(username, db_session)
@app.get("/users/{user_id}")
def read_user(user_id: int):
user = get_user(db_session, user_id=user_id)
return user

0 comments on commit 955e9fc

Please sign in to comment.