📝 Add docs for integrating with NoSQL

This commit is contained in:
Sebastián Ramírez
2018-12-15 21:20:34 +04:00
parent c9e6527768
commit 8a95ea23e2
4 changed files with 223 additions and 0 deletions

View File

@@ -0,0 +1,54 @@
from typing import Optional
from fastapi import FastAPI
from pydantic import BaseModel
from couchbase import LOCKMODE_WAIT
from couchbase.bucket import Bucket
from couchbase.cluster import Cluster, PasswordAuthenticator
USERPROFILE_DOC_TYPE = "userprofile"
def get_bucket():
cluster = Cluster("couchbase://couchbasehost:8091")
authenticator = PasswordAuthenticator("username", "password")
cluster.authenticate(authenticator)
bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT)
return bucket
class User(BaseModel):
username: str
email: Optional[str] = None
full_name: Optional[str] = None
disabled: Optional[bool] = None
class UserInDB(User):
type: str = USERPROFILE_DOC_TYPE
hashed_password: str
class Meta:
key: Optional[str] = None
def get_user(bucket: Bucket, username: str):
doc_id = f"userprofile::{username}"
result = bucket.get(doc_id, quiet=True)
if not result.value:
return None
user = UserInDB(**result.value)
user.Meta.key = result.key
return user
# FastAPI specific code
app = FastAPI()
@app.get("/users/{username}", response_model=User)
def read_user(username: str):
bucket = get_bucket()
user = get_user(bucket=bucket, username=username)
return user

View File

@@ -12,6 +12,7 @@ db_session = scoped_session(
sessionmaker(autocommit=False, autoflush=False, bind=engine)
)
class CustomBase:
# Generate __tablename__ automatically
@declared_attr