FastAPI : 빠르고 단순하고 가벼운 파이썬 프레임워크
실습
라이브러리 설치
pip install fastapi
pip install uvicorn
pip install jinja2
main.py 생성
# main.py
from fastapi import FastAPI
app = FastAPI()
@app.get("/")
def read_root():
return {"Hello": "World"} # "/" 주소는 이 딕셔너리를 보여준다
@app.get("/items/{item_id}")
def read_item(item_id, q): # item_id와 주소뒤에 ?q="예시" 에서 예시를 q로 받는다.
return {"item_id": item_id, "q": q} # "/items/{item_id}" 주소는 이 딕셔너리를 보여준다.
실행해보기
uvicorn main:app --reload
127.0.0.1:8000/
127.0.0.1:8000/items/1
127.0.0.1:8000/items/2?q=검색어
HTML 띄우기
templates라는 폴더 만들기
templates / index.html 생성
<!-- index.html -->
<h1>hello world</h1>
main.py 수정
# main.py
from fastapi import FastAPI
from fastapi import Request
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates") # templates 폴더를 경로로 하겠다.
app = FastAPI(docs_url="/documentation", redoc_url=None)
@app.get("/")
def home(request: Request):
return templates.TemplateResponse("index.html",{"request":request})
127.0.0.1:8000/
HTML에 데이터 넘겨보기
main.py 수정
from fastapi import FastAPI
from fastapi import Request
from fastapi.templating import Jinja2Templates
templates = Jinja2Templates(directory="templates")
db = [
{
"id": 1,
"title": "이번 공부 너무 재미있어요.",
"description": "완전 내 스타일이야!",
"url": "https://inf.run/MQAk",
"tags": ["Python", "Programming", "Beginner"]
},
{
"id": 2,
"title": "웹 개발자가 되고 싶어요!",
"description": "함께 해봐요!",
"url": "https://inf.run/MQAk",
"tags": ["Node.js", "Express", "Web Development"]
},
{
"id": 3,
"title": "데이터 과학자가 되고 싶어요!",
"description": "같이 준비해봅시다!",
"url": "https://inf.run/mDME",
"tags": ["Data Science", "Python", "Statistics"]
}
]
app = FastAPI(docs_url="/documentation", redoc_url=None)
@app.get("/")
def home(request: Request):
return templates.TemplateResponse("index.html", {"request": request})
@app.get("/items/{item_id}")
def read_item(item_id, request: Request):
return templates.TemplateResponse("index.html", {"request": request, "data": db[int(item_id)]})
index.html 수정
<h1>hello world</h1>
<p>{{data.title}}</p>
<p>{{data.description}}</p>
http://127.0.0.1:8000/items/1