본문 바로가기
Developement/Toy Project

Python웹서버 - Fastapi 가볍게 두드려보기

by 튼튼한개발자 2021. 5. 1.

우연히 Go와 성능이 비슷하다는 Fastapi를 접하고 나서

주말에 시간 여유를 내서 가볍게 두드려본다.

 

FastApi fastapi.tiangolo.com/

 

FastAPI

FastAPI FastAPI framework, high performance, easy to learn, fast to code, ready for production Documentation: https://fastapi.tiangolo.com Source Code: https://github.com/tiangolo/fastapi FastAPI is a modern, fast (high-performance), web framework for buil

fastapi.tiangolo.com

우와.. 이게 정녕 fastapi의 능력이라니... Go와 대등할 정도의 매우 높은 성능....?

 

일반 html이 서빙이 가능하도록 일단은 가볍게 만들어보았다.

느낀 점은 뭔가 Flask 같은 느낌이지만 좀 더 강력한 느낌?

 

djagno restful framwork(DRF)도 있지만, 확실히 DRF 보다는 군더더기 없는 심플함이 느껴진다.

 

아직 1.0 버전도 아닌 초기 버전이기 때문에 생태계가 많이 없는 편이지만, 공식문서가 훨씬 더 잘 되어있다.

fastapi.tiangolo.com/ko/

 

FastAPI

FastAPI FastAPI 프레임워크, 고성능, 간편한 학습, 빠른 코드 작성, 준비된 프로덕션 문서: https://fastapi.tiangolo.com 소스 코드: https://github.com/tiangolo/fastapi FastAPI는 현대적이고, 빠르며(고성능), 파이썬

fastapi.tiangolo.com

 

아래는 내가 만든 예제

 

pip install fastapi
pip install uvicorn
pip install python-multipart
pip install aiofiles

 

main.py

import os
import uvicorn
from fastapi import FastAPI, Path, File, Query, Cookie, Header, Request, Response
from fastapi.responses import HTMLResponse, FileResponse
from fastapi.staticfiles import StaticFiles
from typing import Optional
from datetime import datetime

fake_items_db = [{"item_name": "Foo"}, {"item_name": "Bar"}, {"item_name": "Baz"}]

app = FastAPI()
app.mount("/static", StaticFiles(directory="./dist/", html=True))

@app.get("/")
async def root(request: Request):
    return FileResponse("./dist/index.html", media_type='text/html')

@app.get("/header/")
async def read_items(user_agent: Optional[str] = Header(None)):
    return {"User-Agent": user_agent}

@app.get("/cookie/")
async def read_items(ads_id: Optional[str] = Cookie(None)):
    return {"ads_id": ads_id}

@app.get("/response/")
async def read_items():
    html_content = """
    <html>
        <head>
            <title>Some HTML in here</title>
        </head>
        <body>
            <h1>Look ma! HTML!</h1>
        </body>
    </html>
    """
    return HTMLResponse(content=html_content, status_code=200)

@app.get("/items/{item_id}")
async def read_items(
        item_id: int = Path(..., title="The ID of the item to get"),
        q: Optional[str] = Query(None, alias="item-query"),
    ):
    results = {"item_id": item_id}
    if q:
        results.update({"q": q})
    return results

@app.get("/items/")
async def read_item(skip: int = 0, limit: int = 10):
    return fake_items_db[skip : skip + limit]


@app.get("/date/")
async def get_date():
    now = datetime.now()    
    return {"date" : date}

@app.get("/lover/")
async def get_lover():
    now = datetime.now()
    my_lover = "mangokim"
    return {"my_lover" : my_lover, "now" : now}

 

이렇게 하나씩 타이탄의 도구들을 주말마다 하나씩 모으는 기쁨이 있는 것 같다

 

개발자의 예제도 도움이 될듯 하다.

github.com/tiangolo/full-stack-fastapi-postgresql

 

tiangolo/full-stack-fastapi-postgresql

Full stack, modern web application generator. Using FastAPI, PostgreSQL as database, Docker, automatic HTTPS and more. - tiangolo/full-stack-fastapi-postgresql

github.com

 

댓글