본문 바로가기

Fastapi

(13)
내맘대로 Fastapi docs 정리(Cookie, Header) Cookie from fastapi import Cookie, FastAPI app = FastAPI() @app.get("/items/") async def read_items(ads_id: Optional[str] = Cookie(None)): 위와 같이 header의 cookie정보를 Cookie parameter로 받을 수 있다. 하지만 path parameter를 Cookie로 지정하면 Cookie로 인식하지 않고 path parameter로 인식한다. Header from fastapi import FastAPI, Header app = FastAPI() @app.get("/items/") async def read_items(user_agent: Optional[str] = Header(No..
내맘대로 Fastapi docs 정리(Pydantic data types, Pydantic Nested Models) Pydantic from pydantic import BaseModel, Field app = FastAPI() class Item(BaseModel): name: str description: Optional[str] = Field( None, title="The description of the item", max_length=300 ) price: float = Field(..., gt=0, description="The price must be greater than zero", example="a") tax: Optional[float] = None query, path, body parameter와 같이 baseModel안에서도 똑같이 쓸 수 있는데 그것은 Field이다. class Item(..
내맘대로 Fastapi Docs 정리(Query, Path, Body parameters) Query parameters from fastapi import FastAPI, Query app = FastAPI() @app.get("/items/") async def read_items(q: Union[str, None] = Query(default=None, max_length=50)): Union[str, None] 대신에 Optional[str] 혹은 str | None(python 3.10이상)을 쓸 수 있으며, Query는 추가적으로 validation을 달고 싶을 때 쓸 수 있다. 다음과 같이 여러 validataion을 넣을 수 있으며, regex는 정규식이다. Query(default=None, min_length=3, max_length=50, regex="^fixedquery$..
fastapi background task in startup 다음과 같이 fastapi에서 background task를 할 수 있다. from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): background..
내맘대로 Fastapi Document summary[9] # app/router/item.py # We know all the path operations in this module have the same # Path prefix: /items. # tags: (just one tag: items). # Extra responses. # dependencies: they all need that X-Token dependency we created. # instead of adding all that to each path operation, we can add it to the APIRouter. from fastapi import APIRouter, Depends, HTTPException from ..dependencies import get_token..
내맘대로 Fastapi Document summary[8] # sql_app/database.py from sqlalchemy import create_engine from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import sessionmaker SQLALCHEMY_DATABASE_URL = "sqlite:///./sql_app.db" # SQLALCHEMY_DATABASE_URL = "postgresql://user:password@postgresserver/db" engine = create_engine( SQLALCHEMY_DATABASE_URL, connect_args={"check_same_thread": False} ) SessionLocal = sessionma..
내맘대로 Fastapi Document summary[7] A "middleware" is a function that works with every request before it is processed by any specific path operation. And also with every response before returning it. If you have dependencies with yield, the exit code will run after the middleware. If there were any background tasks (documented later), they will run after all the middleware. from fastapi import FastAPI, Request app = FastAPI() @app..
내맘대로 Fastapi Document summary[6] # This is because OAuth2 uses "form data" for sending the username and password # pip install python-multipart from fastapi import Depends, FastAPI from fastapi.security import OAuth2PasswordBearer app = FastAPI() oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token") # relative URL location of token # 연결시도할 때 token authorization을 # 위해 url로 가며 앞으로 token을 이용. @app.get("/items/") async def read_it..