FastAPI로 영상 스트리밍 서비스 구현하기

FastAPI logo

영상 스트리밍은 실시간으로 영상 데이터를 서버에서 클라이언트로 전송하는 기술입니다. FastAPI는 Python 기반의 웹 프레임워크로써, 간단하고 빠른 영상 스트리밍 서비스를 구현하기에 이상적입니다.

필수 패키지 설치

FastAPI를 사용하려면 아래의 패키지를 설치해야 합니다.

pip install fastapi
pip install uvicorn

기본 코드 작성

아래는 FastAPI를 사용하여 간단한 영상 스트리밍 서비스를 구현하는 예제 코드입니다.

from fastapi import FastAPI, WebSocket
from fastapi.responses import StreamingResponse, HTMLResponse

app = FastAPI()

@app.get("/")
async def get_webpage():
    webpage = """
    <h1>영상 스트리밍 서비스</h1>
    <video controls autoplay>
        <source src="/stream" type="video/mp4">
        Your browser does not support the video tag.
    </video>
    """
    return HTMLResponse(content=webpage, status_code=200)

@app.get("/stream")
async def stream_video():
    async def generate_video():
        # 동영상 데이터를 읽어와서 yield로 반환하는 코드 작성
        # 예: 영상 파일에서 프레임을 읽어와서 전송
        with open('video.mp4', 'rb') as video_file:
            while True:
                chunk = video_file.read(1024)
                if not chunk:
                    break
                yield chunk

    return StreamingResponse(generate_video(), media_type='video/mp4')

@app.websocket("/ws")
async def websocket_endpoint(websocket: WebSocket):
    await websocket.accept()
    while True:
        message = await websocket.receive_text()
        await websocket.send_text(f"Received message: {message}")

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)

서버 실행 및 테스트

위 코드를 main.py 파일로 저장한 후, 아래의 명령어를 통해 서버를 실행할 수 있습니다.

uvicorn main:app --reload

http://localhost:8000/ 로 접속하면 영상 스트리밍 서비스를 확인할 수 있습니다.

마무리

FastAPI를 사용하여 간단한 영상 스트리밍 서비스를 구현하는 방법을 알아보았습니다. FastAPI의 빠른 속도와 간편한 사용법으로 실시간 영상 데이터를 전송하는 서비스를 구현할 수 있습니다. 추가적으로, 영상 데이터는 웹 소켓을 통해 클라이언트와 양방향 통신을 할 수도 있습니다.

#FastAPI #영상스트리밍