Sanic 웹 프레임워크: 포괄적인 튜토리얼
소개
Sanic은 빠른 비동기 네트워킹 라이브러리인 uvloop 위에 구축된 오픈 소스 Python 웹 프레임워크입니다. 가벼우며 효율적으로 설계되어 성능이 뛰어난 웹 애플리케이션을 개발하는 데 우수한 선택지입니다. Sanic은 Python의 async와 await 구문을 활용하여 요청을 비동기로 처리하므로 대량의 동시 요청을 쉽게 처리할 수 있습니다.
역사
Sanic은 2016년에 Sanic 커뮤니티에 의해 처음 출시되었습니다. Flask 웹 프레임워크에서 영감을 받아 Flask의 성능과 확장성에 대한 한계를 극복하기 위해 만들어졌습니다. Sanic은 속도와 간결함으로 인해 개발자들 사이에서 빠르게 인기를 얻었으며, 현재는 Python 생태계에서 가장 널리 사용되는 웹 프레임워크 중 하나가 되었습니다.
기능
Sanic은 강력한 웹 애플리케이션을 구축하기 위한 다양한 기능을 제공합니다. Sanic의 주요 기능 중 일부는 다음과 같습니다:
비동기 요청 처리: Sanic은 Python의 async와 await 구문을 사용하여 요청을 비동기로 처리합니다. 이는 여러 요청을 동시에 처리할 수 있어 성능과 확장성이 향상됩니다.
빠른 실행: Sanic은 빠른 비동기 네트워킹 라이브러리인 uvloop 위에 구축되어 대량의 요청을 빠르고 효율적으로 처리할 수 있습니다.
라우팅: Sanic은 URL 경로를 간단하고 직관적인 방식으로 정의하고 특정 핸들러 함수에 바인딩할 수 있는 기능을 제공합니다. 이를 통해 RESTful API를 쉽게 생성하고 다양한 종류의 HTTP 요청을 처리할 수 있습니다.
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route('/')
async def hello(request):
return text('안녕, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)위의 코드 스니펫에서는 루트 URL ("/")에 대한 라우트를 정의하고
hello핸들러 함수에 바인딩합니다. 루트 URL로 요청이 들어오면hello함수가 실행되고 "안녕, Sanic!"이라는 응답을 반환합니다.미들웨어 지원: Sanic은 들어오는 요청과 나가는 응답을 가로채고 수정할 수 있는 미들웨어 함수를 정의할 수 있습니다. 이는 인증, 요청 로깅, 에러 처리 등과 같은 작업에 유용합니다.
from sanic import Sanic
from sanic.response import text
app = Sanic()
async def custom_middleware(request):
print('요청 전')
response = await request.next()
print('응답 후')
return response
app.middleware(custom_middleware)
@app.route('/')
async def hello(request):
return text('안녕, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)위의 예제에서는
custom_middleware라는 사용자 정의 미들웨어 함수를 정의하고 요청이 처리되기 전과 응답이 전송된 후에 메시지를 출력합니다.middleware데코레이터를 사용하여 이 미들웨어 함수를 Sanic 애플리케이션에 등록합니다.WebSocket 지원: Sanic은 WebSocket 통신을 내장하여 웹 애플리케이션에서 실시간 기능을 쉽게 구현할 수 있습니다.
from sanic import Sanic
from sanic.websocket import WebSocketProtocol
app = Sanic()
@app.websocket('/ws')
async def websocket_handler(request, ws):
while True:
message = await ws.recv()
await ws.send('너가 말한 거: ' + message)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, protocol=WebSocketProtocol)위의 예제에서는 웹소켓 라우트 ("/ws")를 정의하고
websocket_handler함수에 바인딩합니다. 이 함수는 WebSocket 객체ws를 받아서 메시지를 보내고 받을 수 있습니다.템플릿 렌더링: Sanic은 Jinja2와 Mako와 같은 다양한 템플릿 엔진을 지원하여 동적 HTML 페이지를 쉽게 생성할 수 있습니다.
from sanic import Sanic
from sanic.response import html
from jinja2 import Template
app = Sanic()
@app.route('/')
async def index(request):
template = Template('<h1>안녕, {{ name }}!</h1>')
rendered_template = template.render(name='Sanic')
return html(rendered_template)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)위의 코드 스니펫에서는 개인화된 인사말을 표시하는 Jinja2 템플릿을 정의합니다. 템플릿은 "Sanic"이라는 이름으로 렌더링되고 HTML 응답으로 반환됩니다.
요청 유효성 검사: Sanic은 요청 매개변수, 헤더 및 기타 속성을 사용하여 들어오는 요청을 간단하게 유효성 검사할 수 있는 방법을 제공합니다.
from sanic import Sanic
from sanic.exceptions import InvalidUsage
from sanic.request import RequestParameters
app = Sanic()
@app.route('/')
async def hello(request):
name = request.args.get('name')
if not name:
raise InvalidUsage('이름이 필요합니다.')
return text('안녕, ' + name)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)위의 예제에서는
name매개변수가 있는지 확인하여 요청을 유효성 검사합니다. 제공되지 않는 경우 예외가 발생하고 오류 메시지가 반환됩니다.
예제
다음은 Sanic 사용법을 보여주는 몇 가지 예제입니다:
간단한 Hello World 예제:
from sanic import Sanic
from sanic.response import text
app = Sanic()
@app.route('/')
async def hello(request):
return text('안녕, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)출력:
안녕, Sanic!비동기 요청 처리:
from sanic import Sanic
from sanic.response import text
import asyncio
app = Sanic()
@app.route('/')
async def hello(request):
await asyncio.sleep(1) # 비동기 작업 시뮬레이션
return text('안녕, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)출력:
안녕, Sanic!미들웨어 예제:
from sanic import Sanic
from sanic.response import text
app = Sanic()
async def custom_middleware(request):
print('요청 전')
response = await request.next()
print('응답 후')
return response
app.middleware(custom_middleware)
@app.route('/')
async def hello(request):
return text('안녕, Sanic!')
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000)출력:
요청 전
응답 후WebSocket 예제:
from sanic import Sanic
from sanic.websocket import WebSocketProtocol
app = Sanic()
@app.websocket('/ws')
async def websocket_handler(request, ws):
while True: