Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix SQLAlchemy support with ORM #30

Merged
merged 3 commits into from Feb 12, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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