mirror of https://github.com/tiangolo/fastapi.git
🚚 Re-order tutorial Python fiels
This commit is contained in:
parent
ec7bec32ba
commit
400a4a99af
|
|
@ -0,0 +1,17 @@
|
||||||
|
from fastapi import Body, FastAPI
|
||||||
|
from pydantic import BaseModel, Schema
|
||||||
|
|
||||||
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
|
class Item(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: str = Schema(None, title="The description of the item", max_length=300)
|
||||||
|
price: float = Schema(..., gt=0, description="The price must be greater than zero")
|
||||||
|
tax: float = None
|
||||||
|
|
||||||
|
|
||||||
|
@app.put("/items/{item_id}")
|
||||||
|
async def update_item(*, item_id: int, item: Item = Body(..., embed=True)):
|
||||||
|
results = {"item_id": item_id, "item": item}
|
||||||
|
return results
|
||||||
|
|
@ -1,5 +1,5 @@
|
||||||
from fastapi import FastAPI
|
from fastapi import Body, FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel, Schema
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
@ -9,10 +9,21 @@ class Item(BaseModel):
|
||||||
description: str = None
|
description: str = None
|
||||||
price: float
|
price: float
|
||||||
tax: float = None
|
tax: float = None
|
||||||
tags: list = []
|
|
||||||
|
|
||||||
|
|
||||||
@app.put("/items/{item_id}")
|
@app.put("/items/{item_id}")
|
||||||
async def update_item(*, item_id: int, item: Item):
|
async def update_item(
|
||||||
|
*,
|
||||||
|
item_id: int,
|
||||||
|
item: Item = Body(
|
||||||
|
...,
|
||||||
|
example={
|
||||||
|
"name": "Foo",
|
||||||
|
"description": "A very nice Item",
|
||||||
|
"price": 35.4,
|
||||||
|
"tax": 3.2,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
):
|
||||||
results = {"item_id": item_id, "item": item}
|
results = {"item_id": item_id, "item": item}
|
||||||
return results
|
return results
|
||||||
|
|
|
||||||
|
|
@ -1,5 +1,3 @@
|
||||||
from typing import List
|
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
|
|
@ -11,7 +9,7 @@ class Item(BaseModel):
|
||||||
description: str = None
|
description: str = None
|
||||||
price: float
|
price: float
|
||||||
tax: float = None
|
tax: float = None
|
||||||
tags: List[str] = []
|
tags: list = []
|
||||||
|
|
||||||
|
|
||||||
@app.put("/items/{item_id}")
|
@app.put("/items/{item_id}")
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import Set
|
from typing import List
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
@ -11,7 +11,7 @@ class Item(BaseModel):
|
||||||
description: str = None
|
description: str = None
|
||||||
price: float
|
price: float
|
||||||
tax: float = None
|
tax: float = None
|
||||||
tags: Set[str] = []
|
tags: List[str] = []
|
||||||
|
|
||||||
|
|
||||||
@app.put("/items/{item_id}")
|
@app.put("/items/{item_id}")
|
||||||
|
|
|
||||||
|
|
@ -6,18 +6,12 @@ from pydantic import BaseModel
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class Image(BaseModel):
|
|
||||||
url: str
|
|
||||||
name: str
|
|
||||||
|
|
||||||
|
|
||||||
class Item(BaseModel):
|
class Item(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
description: str = None
|
description: str = None
|
||||||
price: float
|
price: float
|
||||||
tax: float = None
|
tax: float = None
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
image: Image = None
|
|
||||||
|
|
||||||
|
|
||||||
@app.put("/items/{item_id}")
|
@app.put("/items/{item_id}")
|
||||||
|
|
|
||||||
|
|
@ -2,13 +2,12 @@ from typing import Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from pydantic.types import UrlStr
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class Image(BaseModel):
|
class Image(BaseModel):
|
||||||
url: UrlStr
|
url: str
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List, Set
|
from typing import Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
@ -18,7 +18,7 @@ class Item(BaseModel):
|
||||||
price: float
|
price: float
|
||||||
tax: float = None
|
tax: float = None
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
image: List[Image] = None
|
image: Image = None
|
||||||
|
|
||||||
|
|
||||||
@app.put("/items/{item_id}")
|
@app.put("/items/{item_id}")
|
||||||
|
|
|
||||||
|
|
@ -21,13 +21,7 @@ class Item(BaseModel):
|
||||||
image: List[Image] = None
|
image: List[Image] = None
|
||||||
|
|
||||||
|
|
||||||
class Offer(BaseModel):
|
@app.put("/items/{item_id}")
|
||||||
name: str
|
async def update_item(*, item_id: int, item: Item):
|
||||||
description: str = None
|
results = {"item_id": item_id, "item": item}
|
||||||
price: float
|
return results
|
||||||
items: List[Item]
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/offers/")
|
|
||||||
async def create_offer(*, offer: Offer):
|
|
||||||
return offer
|
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,4 @@
|
||||||
from typing import List
|
from typing import List, Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
@ -12,6 +12,22 @@ class Image(BaseModel):
|
||||||
name: str
|
name: str
|
||||||
|
|
||||||
|
|
||||||
@app.post("/images/multiple/")
|
class Item(BaseModel):
|
||||||
async def create_multiple_images(*, images: List[Image]):
|
name: str
|
||||||
return images
|
description: str = None
|
||||||
|
price: float
|
||||||
|
tax: float = None
|
||||||
|
tags: Set[str] = []
|
||||||
|
image: List[Image] = None
|
||||||
|
|
||||||
|
|
||||||
|
class Offer(BaseModel):
|
||||||
|
name: str
|
||||||
|
description: str = None
|
||||||
|
price: float
|
||||||
|
items: List[Item]
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/offers/")
|
||||||
|
async def create_offer(*, offer: Offer):
|
||||||
|
return offer
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,17 @@
|
||||||
from fastapi import Cookie, FastAPI
|
from typing import List
|
||||||
|
|
||||||
|
from fastapi import FastAPI
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from pydantic.types import UrlStr
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/")
|
class Image(BaseModel):
|
||||||
async def read_items(*, ads_id: str = Cookie(None)):
|
url: UrlStr
|
||||||
return {"ads_id": ads_id}
|
name: str
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/images/multiple/")
|
||||||
|
async def create_multiple_images(*, images: List[Image]):
|
||||||
|
return images
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
from fastapi import FastAPI, Header
|
from fastapi import Cookie, FastAPI
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/")
|
@app.get("/items/")
|
||||||
async def read_items(*, accept_encoding: str = Header(None)):
|
async def read_items(*, ads_id: str = Cookie(None)):
|
||||||
return {"Accept-Encoding": accept_encoding}
|
return {"ads_id": ads_id}
|
||||||
|
|
|
||||||
|
|
@ -4,5 +4,5 @@ app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/")
|
@app.get("/items/")
|
||||||
async def read_items(*, strange_header: str = Header(None, convert_underscores=False)):
|
async def read_items(*, accept_encoding: str = Header(None)):
|
||||||
return {"strange_header": strange_header}
|
return {"Accept-Encoding": accept_encoding}
|
||||||
|
|
|
||||||
|
|
@ -1,19 +1,8 @@
|
||||||
from typing import Set
|
from fastapi import FastAPI, Header
|
||||||
|
|
||||||
from fastapi import FastAPI
|
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class Item(BaseModel):
|
@app.get("/items/")
|
||||||
name: str
|
async def read_items(*, strange_header: str = Header(None, convert_underscores=False)):
|
||||||
description: str = None
|
return {"strange_header": strange_header}
|
||||||
price: float
|
|
||||||
tax: float = None
|
|
||||||
tags: Set[str] = []
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/items/", response_model=Item)
|
|
||||||
async def create_item(*, item: Item):
|
|
||||||
return item
|
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,19 @@
|
||||||
|
from typing import Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
from pydantic.types import EmailStr
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class UserIn(BaseModel):
|
class Item(BaseModel):
|
||||||
username: str
|
name: str
|
||||||
password: str
|
description: str = None
|
||||||
email: EmailStr
|
price: float
|
||||||
full_name: str = None
|
tax: float = None
|
||||||
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
# Don't do this in production!
|
@app.post("/items/", response_model=Item)
|
||||||
@app.post("/user/", response_model=UserIn)
|
async def create_item(*, item: Item):
|
||||||
async def create_user(*, user: UserIn):
|
return item
|
||||||
return user
|
|
||||||
|
|
|
||||||
|
|
@ -12,12 +12,7 @@ class UserIn(BaseModel):
|
||||||
full_name: str = None
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
class UserOut(BaseModel):
|
# Don't do this in production!
|
||||||
username: str
|
@app.post("/user/", response_model=UserIn)
|
||||||
email: EmailStr
|
|
||||||
full_name: str = None
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/user/", response_model=UserOut)
|
|
||||||
async def create_user(*, user: UserIn):
|
async def create_user(*, user: UserIn):
|
||||||
return user
|
return user
|
||||||
|
|
|
||||||
|
|
@ -18,25 +18,6 @@ class UserOut(BaseModel):
|
||||||
full_name: str = None
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
class UserInDB(BaseModel):
|
|
||||||
username: str
|
|
||||||
hashed_password: str
|
|
||||||
email: EmailStr
|
|
||||||
full_name: str = None
|
|
||||||
|
|
||||||
|
|
||||||
def fake_password_hasher(raw_password: str):
|
|
||||||
return "supersecret" + raw_password
|
|
||||||
|
|
||||||
|
|
||||||
def fake_save_user(user_in: UserIn):
|
|
||||||
hashed_password = fake_password_hasher(user_in.password)
|
|
||||||
user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
|
|
||||||
print("User saved! ..not really")
|
|
||||||
return user_in_db
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/user/", response_model=UserOut)
|
@app.post("/user/", response_model=UserOut)
|
||||||
async def create_user(*, user_in: UserIn):
|
async def create_user(*, user: UserIn):
|
||||||
user_saved = fake_save_user(user_in)
|
return user
|
||||||
return user_saved
|
|
||||||
|
|
|
||||||
|
|
@ -5,22 +5,24 @@ from pydantic.types import EmailStr
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class UserBase(BaseModel):
|
class UserIn(BaseModel):
|
||||||
|
username: str
|
||||||
|
password: str
|
||||||
|
email: EmailStr
|
||||||
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserOut(BaseModel):
|
||||||
username: str
|
username: str
|
||||||
email: EmailStr
|
email: EmailStr
|
||||||
full_name: str = None
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
class UserIn(UserBase):
|
class UserInDB(BaseModel):
|
||||||
password: str
|
username: str
|
||||||
|
|
||||||
|
|
||||||
class UserOut(UserBase):
|
|
||||||
pass
|
|
||||||
|
|
||||||
|
|
||||||
class UserInDB(UserBase):
|
|
||||||
hashed_password: str
|
hashed_password: str
|
||||||
|
email: EmailStr
|
||||||
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
def fake_password_hasher(raw_password: str):
|
def fake_password_hasher(raw_password: str):
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,40 @@
|
||||||
from fastapi import FastAPI, Form
|
from fastapi import FastAPI
|
||||||
|
from pydantic import BaseModel
|
||||||
|
from pydantic.types import EmailStr
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/login/")
|
class UserBase(BaseModel):
|
||||||
async def login(*, username: str = Form(...), password: str = Form(...)):
|
username: str
|
||||||
return {"username": username}
|
email: EmailStr
|
||||||
|
full_name: str = None
|
||||||
|
|
||||||
|
|
||||||
|
class UserIn(UserBase):
|
||||||
|
password: str
|
||||||
|
|
||||||
|
|
||||||
|
class UserOut(UserBase):
|
||||||
|
pass
|
||||||
|
|
||||||
|
|
||||||
|
class UserInDB(UserBase):
|
||||||
|
hashed_password: str
|
||||||
|
|
||||||
|
|
||||||
|
def fake_password_hasher(raw_password: str):
|
||||||
|
return "supersecret" + raw_password
|
||||||
|
|
||||||
|
|
||||||
|
def fake_save_user(user_in: UserIn):
|
||||||
|
hashed_password = fake_password_hasher(user_in.password)
|
||||||
|
user_in_db = UserInDB(**user_in.dict(), hashed_password=hashed_password)
|
||||||
|
print("User saved! ..not really")
|
||||||
|
return user_in_db
|
||||||
|
|
||||||
|
|
||||||
|
@app.post("/user/", response_model=UserOut)
|
||||||
|
async def create_user(*, user_in: UserIn):
|
||||||
|
user_saved = fake_save_user(user_in)
|
||||||
|
return user_saved
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
from fastapi import FastAPI, File
|
from fastapi import FastAPI, Form
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/files/")
|
@app.post("/login/")
|
||||||
async def create_file(*, file: bytes = File(...)):
|
async def login(*, username: str = Form(...), password: str = Form(...)):
|
||||||
return {"file_size": len(file)}
|
return {"username": username}
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,8 @@
|
||||||
from fastapi import FastAPI, File, Form
|
from fastapi import FastAPI, File
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.post("/files/")
|
@app.post("/files/")
|
||||||
async def create_file(*, file: bytes = File(...), token: str = Form(...)):
|
async def create_file(*, file: bytes = File(...)):
|
||||||
return {"file_size": len(file), "token": token}
|
return {"file_size": len(file)}
|
||||||
|
|
|
||||||
|
|
@ -1,20 +1,8 @@
|
||||||
from typing import Set
|
from fastapi import FastAPI, File, Form
|
||||||
|
|
||||||
from fastapi import FastAPI
|
|
||||||
from pydantic import BaseModel
|
|
||||||
from starlette.status import HTTP_201_CREATED
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class Item(BaseModel):
|
@app.post("/files/")
|
||||||
name: str
|
async def create_file(*, file: bytes = File(...), token: str = Form(...)):
|
||||||
description: str = None
|
return {"file_size": len(file), "token": token}
|
||||||
price: float
|
|
||||||
tax: float = None
|
|
||||||
tags: Set[str] = []
|
|
||||||
|
|
||||||
|
|
||||||
@app.post("/items/", response_model=Item, status_code=HTTP_201_CREATED)
|
|
||||||
async def create_item(*, item: Item):
|
|
||||||
return item
|
|
||||||
|
|
|
||||||
|
|
@ -2,6 +2,7 @@ from typing import Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
from starlette.status import HTTP_201_CREATED
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
@ -14,6 +15,6 @@ class Item(BaseModel):
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
@app.post("/items/", response_model=Item, tags=["items"])
|
@app.post("/items/", response_model=Item, status_code=HTTP_201_CREATED)
|
||||||
async def create_item(*, item: Item):
|
async def create_item(*, item: Item):
|
||||||
return item
|
return item
|
||||||
|
|
|
||||||
|
|
@ -14,11 +14,6 @@ class Item(BaseModel):
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
@app.post(
|
@app.post("/items/", response_model=Item, tags=["items"])
|
||||||
"/items/",
|
|
||||||
response_model=Item,
|
|
||||||
summary="Create an item",
|
|
||||||
description="Create an item with all the information, name, description, price, tax and a set of unique tags",
|
|
||||||
)
|
|
||||||
async def create_item(*, item: Item):
|
async def create_item(*, item: Item):
|
||||||
return item
|
return item
|
||||||
|
|
|
||||||
|
|
@ -14,15 +14,11 @@ class Item(BaseModel):
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
@app.post("/items/", response_model=Item, summary="Create an item")
|
@app.post(
|
||||||
|
"/items/",
|
||||||
|
response_model=Item,
|
||||||
|
summary="Create an item",
|
||||||
|
description="Create an item with all the information, name, description, price, tax and a set of unique tags",
|
||||||
|
)
|
||||||
async def create_item(*, item: Item):
|
async def create_item(*, item: Item):
|
||||||
"""
|
|
||||||
Create an item with all the information:
|
|
||||||
|
|
||||||
* name: each item must have a name
|
|
||||||
* description: a long description
|
|
||||||
* price: required
|
|
||||||
* tax: if the item doesn't have tax, you can omit this
|
|
||||||
* tags: a set of unique tag strings for this item
|
|
||||||
"""
|
|
||||||
return item
|
return item
|
||||||
|
|
|
||||||
|
|
@ -14,12 +14,7 @@ class Item(BaseModel):
|
||||||
tags: Set[str] = []
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
@app.post(
|
@app.post("/items/", response_model=Item, summary="Create an item")
|
||||||
"/items/",
|
|
||||||
response_model=Item,
|
|
||||||
summary="Create an item",
|
|
||||||
response_description="The created item",
|
|
||||||
)
|
|
||||||
async def create_item(*, item: Item):
|
async def create_item(*, item: Item):
|
||||||
"""
|
"""
|
||||||
Create an item with all the information:
|
Create an item with all the information:
|
||||||
|
|
|
||||||
|
|
@ -1,8 +1,33 @@
|
||||||
|
from typing import Set
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
|
from pydantic import BaseModel
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/", deprecated=True)
|
class Item(BaseModel):
|
||||||
async def read_items():
|
name: str
|
||||||
return [{"item_id": "Foo"}]
|
description: str = None
|
||||||
|
price: float
|
||||||
|
tax: float = None
|
||||||
|
tags: Set[str] = []
|
||||||
|
|
||||||
|
|
||||||
|
@app.post(
|
||||||
|
"/items/",
|
||||||
|
response_model=Item,
|
||||||
|
summary="Create an item",
|
||||||
|
response_description="The created item",
|
||||||
|
)
|
||||||
|
async def create_item(*, item: Item):
|
||||||
|
"""
|
||||||
|
Create an item with all the information:
|
||||||
|
|
||||||
|
* name: each item must have a name
|
||||||
|
* description: a long description
|
||||||
|
* price: required
|
||||||
|
* tax: if the item doesn't have tax, you can omit this
|
||||||
|
* tags: a set of unique tag strings for this item
|
||||||
|
"""
|
||||||
|
return item
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,6 @@ from fastapi import FastAPI
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/", operation_id="some_specific_id_you_define")
|
@app.get("/items/", deprecated=True)
|
||||||
async def read_items():
|
async def read_items():
|
||||||
return [{"item_id": "Foo"}]
|
return [{"item_id": "Foo"}]
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,6 @@ from fastapi import FastAPI
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/", include_in_schema=False)
|
@app.get("/items/", operation_id="some_specific_id_you_define")
|
||||||
async def read_items():
|
async def read_items():
|
||||||
return [{"item_id": "Foo"}]
|
return [{"item_id": "Foo"}]
|
||||||
|
|
|
||||||
|
|
@ -1,9 +1,8 @@
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from starlette.responses import UJSONResponse
|
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/", content_type=UJSONResponse)
|
@app.get("/items/", include_in_schema=False)
|
||||||
async def read_items():
|
async def read_items():
|
||||||
return [{"item_id": "Foo"}]
|
return [{"item_id": "Foo"}]
|
||||||
|
|
|
||||||
|
|
@ -1,18 +1,9 @@
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from starlette.responses import HTMLResponse
|
from starlette.responses import UJSONResponse
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/items/", content_type=HTMLResponse)
|
@app.get("/items/", content_type=UJSONResponse)
|
||||||
async def read_items():
|
async def read_items():
|
||||||
return """
|
return [{"item_id": "Foo"}]
|
||||||
<html>
|
|
||||||
<head>
|
|
||||||
<title>Some HTML in here</title>
|
|
||||||
</head>
|
|
||||||
<body>
|
|
||||||
<h1>Look ma! HTML!</h1>
|
|
||||||
</body>
|
|
||||||
</html>
|
|
||||||
"""
|
|
||||||
|
|
|
||||||
|
|
@ -1,27 +1,18 @@
|
||||||
from fastapi import Depends, FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
from starlette.responses import HTMLResponse
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
|
@app.get("/items/", content_type=HTMLResponse)
|
||||||
|
async def read_items():
|
||||||
|
return """
|
||||||
class CommonQueryParams(BaseModel):
|
<html>
|
||||||
q: str = None
|
<head>
|
||||||
skip: int = None
|
<title>Some HTML in here</title>
|
||||||
limit: int = None
|
</head>
|
||||||
|
<body>
|
||||||
|
<h1>Look ma! HTML!</h1>
|
||||||
async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
|
</body>
|
||||||
return CommonQueryParams(q=q, skip=skip, limit=limit)
|
</html>
|
||||||
|
"""
|
||||||
|
|
||||||
@app.get("/items/")
|
|
||||||
async def read_items(commons: CommonQueryParams = Depends(common_parameters)):
|
|
||||||
response = {}
|
|
||||||
if commons.q:
|
|
||||||
response.update({"q": commons.q})
|
|
||||||
items = fake_items_db[commons.skip : commons.limit]
|
|
||||||
response.update({"items": items})
|
|
||||||
return response
|
|
||||||
|
|
|
||||||
|
|
@ -1,34 +1,27 @@
|
||||||
from typing import List
|
from fastapi import Depends, FastAPI
|
||||||
|
|
||||||
from fastapi import Cookie, Depends, FastAPI
|
|
||||||
from pydantic import BaseModel
|
from pydantic import BaseModel
|
||||||
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
class InterestsTracker(BaseModel):
|
fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]
|
||||||
track_code: str
|
|
||||||
interests: List[str]
|
|
||||||
|
|
||||||
|
|
||||||
fake_tracked_users_db = {
|
class CommonQueryParams(BaseModel):
|
||||||
"Foo": {"track_code": "Foo", "interests": ["sports", "movies"]},
|
q: str = None
|
||||||
"Bar": {"track_code": "Bar", "interests": ["food", "shows"]},
|
skip: int = None
|
||||||
"Baz": {"track_code": "Baz", "interests": ["gaming", "virtual reality"]},
|
limit: int = None
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
async def get_tracked_interests(track_code: str = Cookie(None)):
|
async def common_parameters(q: str = None, skip: int = 0, limit: int = 100):
|
||||||
if track_code in fake_tracked_users_db:
|
return CommonQueryParams(q=q, skip=skip, limit=limit)
|
||||||
track_dict = fake_tracked_users_db[track_code]
|
|
||||||
track = InterestsTracker(**track_dict)
|
|
||||||
return track
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/interests/")
|
@app.get("/items/")
|
||||||
async def read_interests(
|
async def read_items(commons: CommonQueryParams = Depends(common_parameters)):
|
||||||
tracked_interests: InterestsTracker = Depends(get_tracked_interests)
|
response = {}
|
||||||
):
|
if commons.q:
|
||||||
response = {"interests": tracked_interests.interests}
|
response.update({"q": commons.q})
|
||||||
|
items = fake_items_db[commons.skip : commons.limit]
|
||||||
|
response.update({"items": items})
|
||||||
return response
|
return response
|
||||||
|
|
|
||||||
|
|
@ -1,4 +1,3 @@
|
||||||
from random import choice
|
|
||||||
from typing import List
|
from typing import List
|
||||||
|
|
||||||
from fastapi import Cookie, Depends, FastAPI
|
from fastapi import Cookie, Depends, FastAPI
|
||||||
|
|
@ -27,23 +26,9 @@ async def get_tracked_interests(track_code: str = Cookie(None)):
|
||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
class ComplexTracker:
|
@app.get("/interests/")
|
||||||
def __init__(self, tracker: InterestsTracker = Depends(get_tracked_interests)):
|
async def read_interests(
|
||||||
self.tracker = tracker
|
tracked_interests: InterestsTracker = Depends(get_tracked_interests)
|
||||||
|
):
|
||||||
def random_interest(self):
|
response = {"interests": tracked_interests.interests}
|
||||||
"""
|
|
||||||
Get a random interest from the tracked ones for the current user.
|
|
||||||
If the user doesn't have tracked interests, return a random one from the ones available.
|
|
||||||
"""
|
|
||||||
if self.tracker.interests:
|
|
||||||
return choice(self.tracker.interests)
|
|
||||||
return choice(
|
|
||||||
["sports", "movies", "food", "shows", "gaming", "virtual reality"]
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
@app.get("/suggested-category")
|
|
||||||
async def read_suggested_category(tracker: ComplexTracker = Depends(None)):
|
|
||||||
response = {"category": tracker.random_interest()}
|
|
||||||
return response
|
return response
|
||||||
|
|
|
||||||
|
|
@ -1,52 +1,49 @@
|
||||||
from fastapi import FastAPI
|
from random import choice
|
||||||
|
from typing import List
|
||||||
|
|
||||||
from sqlalchemy import Boolean, Column, Integer, String, create_engine
|
from fastapi import Cookie, Depends, FastAPI
|
||||||
from sqlalchemy.ext.declarative import declarative_base, declared_attr
|
from pydantic import BaseModel
|
||||||
from sqlalchemy.orm import scoped_session, sessionmaker
|
|
||||||
|
|
||||||
# SQLAlchemy specific code, as with any other app
|
|
||||||
|
|
||||||
|
|
||||||
SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
|
|
||||||
|
|
||||||
# By creating this a CustomBase class and inheriting from it, your models will have
|
|
||||||
# automatic __tablename__ attributes. So you don't have to declare them.
|
|
||||||
# So, your models will behave very similarly to, for example, Flask-SQLAlchemy
|
|
||||||
|
|
||||||
|
|
||||||
class CustomBase:
|
|
||||||
# Generate __tablename__ automatically
|
|
||||||
@declared_attr
|
|
||||||
def __tablename__(cls):
|
|
||||||
return cls.__name__.lower()
|
|
||||||
|
|
||||||
|
|
||||||
Base = declarative_base(cls=CustomBase)
|
|
||||||
|
|
||||||
|
|
||||||
class User(Base):
|
|
||||||
# Own properties
|
|
||||||
id = Column(Integer, primary_key=True, index=True)
|
|
||||||
email = Column(String, unique=True, index=True)
|
|
||||||
hashed_password = Column(String)
|
|
||||||
is_active = Column(Boolean(), default=True)
|
|
||||||
|
|
||||||
|
|
||||||
engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)
|
|
||||||
db_session = scoped_session(
|
|
||||||
sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
def get_user(username, db_session):
|
|
||||||
return db_session.query(User).filter(User.id == username).first()
|
|
||||||
|
|
||||||
|
|
||||||
# FastAPI specific code
|
|
||||||
app = FastAPI()
|
app = FastAPI()
|
||||||
|
|
||||||
|
|
||||||
@app.get("/users/{username}")
|
class InterestsTracker(BaseModel):
|
||||||
def read_user(username: str):
|
track_code: str
|
||||||
user = get_user(username, db_session)
|
interests: List[str]
|
||||||
return user
|
|
||||||
|
|
||||||
|
fake_tracked_users_db = {
|
||||||
|
"Foo": {"track_code": "Foo", "interests": ["sports", "movies"]},
|
||||||
|
"Bar": {"track_code": "Bar", "interests": ["food", "shows"]},
|
||||||
|
"Baz": {"track_code": "Baz", "interests": ["gaming", "virtual reality"]},
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
async def get_tracked_interests(track_code: str = Cookie(None)):
|
||||||
|
if track_code in fake_tracked_users_db:
|
||||||
|
track_dict = fake_tracked_users_db[track_code]
|
||||||
|
track = InterestsTracker(**track_dict)
|
||||||
|
return track
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
class ComplexTracker:
|
||||||
|
def __init__(self, tracker: InterestsTracker = Depends(get_tracked_interests)):
|
||||||
|
self.tracker = tracker
|
||||||
|
|
||||||
|
def random_interest(self):
|
||||||
|
"""
|
||||||
|
Get a random interest from the tracked ones for the current user.
|
||||||
|
If the user doesn't have tracked interests, return a random one from the ones available.
|
||||||
|
"""
|
||||||
|
if self.tracker.interests:
|
||||||
|
return choice(self.tracker.interests)
|
||||||
|
return choice(
|
||||||
|
["sports", "movies", "food", "shows", "gaming", "virtual reality"]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@app.get("/suggested-category")
|
||||||
|
async def read_suggested_category(tracker: ComplexTracker = Depends(None)):
|
||||||
|
response = {"category": tracker.random_interest()}
|
||||||
|
return response
|
||||||
|
|
|
||||||
|
|
@ -1,49 +1,45 @@
|
||||||
from typing import Optional
|
|
||||||
|
|
||||||
from fastapi import FastAPI
|
from fastapi import FastAPI
|
||||||
from pydantic import BaseModel
|
|
||||||
|
|
||||||
from app.models.config import USERPROFILE_DOC_TYPE
|
from sqlalchemy import Boolean, Column, Integer, String, create_engine
|
||||||
from couchbase import LOCKMODE_WAIT
|
from sqlalchemy.ext.declarative import declarative_base, declared_attr
|
||||||
from couchbase.bucket import Bucket
|
from sqlalchemy.orm import scoped_session, sessionmaker
|
||||||
from couchbase.cluster import Cluster, PasswordAuthenticator
|
|
||||||
|
# SQLAlchemy specific code, as with any other app
|
||||||
|
|
||||||
|
|
||||||
def get_bucket():
|
SQLALCHEMY_DATABASE_URI = "postgresql://user:password@postgresserver/db"
|
||||||
cluster = Cluster("couchbase://couchbasehost:8091")
|
|
||||||
authenticator = PasswordAuthenticator("username", "password")
|
# By creating this a CustomBase class and inheriting from it, your models will have
|
||||||
cluster.authenticate(authenticator)
|
# automatic __tablename__ attributes. So you don't have to declare them.
|
||||||
bucket: Bucket = cluster.open_bucket("bucket_name", lockmode=LOCKMODE_WAIT)
|
# So, your models will behave very similarly to, for example, Flask-SQLAlchemy
|
||||||
return bucket
|
|
||||||
|
|
||||||
|
|
||||||
class User(BaseModel):
|
class CustomBase:
|
||||||
username: str
|
# Generate __tablename__ automatically
|
||||||
email: Optional[str] = None
|
@declared_attr
|
||||||
full_name: Optional[str] = None
|
def __tablename__(cls):
|
||||||
disabled: Optional[bool] = None
|
return cls.__name__.lower()
|
||||||
|
|
||||||
|
|
||||||
class UserInDB(User):
|
Base = declarative_base(cls=CustomBase)
|
||||||
type: str = USERPROFILE_DOC_TYPE
|
|
||||||
hashed_password: str
|
|
||||||
|
|
||||||
class Meta:
|
|
||||||
key: Optional[str] = None
|
|
||||||
|
|
||||||
|
|
||||||
def get_user_doc_id(username):
|
class User(Base):
|
||||||
return f"userprofile::{username}"
|
# Own properties
|
||||||
|
id = Column(Integer, primary_key=True, index=True)
|
||||||
|
email = Column(String, unique=True, index=True)
|
||||||
|
hashed_password = Column(String)
|
||||||
|
is_active = Column(Boolean(), default=True)
|
||||||
|
|
||||||
|
|
||||||
def get_user(bucket: Bucket, username: str):
|
engine = create_engine(SQLALCHEMY_DATABASE_URI, convert_unicode=True)
|
||||||
doc_id = get_user_doc_id(username)
|
db_session = scoped_session(
|
||||||
result = bucket.get(doc_id, quiet=True)
|
sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||||
if not result.value:
|
)
|
||||||
return None
|
|
||||||
user = UserInDB(**result.value)
|
|
||||||
user.Meta.key = result.key
|
def get_user(username, db_session):
|
||||||
return user
|
return db_session.query(User).filter(User.id == username).first()
|
||||||
|
|
||||||
|
|
||||||
# FastAPI specific code
|
# FastAPI specific code
|
||||||
|
|
@ -52,6 +48,5 @@ app = FastAPI()
|
||||||
|
|
||||||
@app.get("/users/{username}")
|
@app.get("/users/{username}")
|
||||||
def read_user(username: str):
|
def read_user(username: str):
|
||||||
bucket = get_bucket()
|
user = get_user(username, db_session)
|
||||||
user = get_user(bucket=bucket, username=username)
|
|
||||||
return user
|
return user
|
||||||
|
|
|
||||||
Loading…
Reference in New Issue