본문 바로가기
Python

Sanic BluePrint 사용하기

by NOMADFISH 2020. 10. 29.

sanic blueprint

Sanic Routing기능

  • Decorator: 명시적으로 @app.route({path},[{method}...]와 같은 방식
    • @app.route('/',['GET']) : http://xxxx.xxx.xxx path로 request 발생시 이 decorator에 연결된 함수가 호출되어 request를 처리 한다.
  • Blueprint: 아래 예제에서 설명하겟지만 Decorator와 동일한 방식을 사용하지만, 특정 path를 prefix로 먼저 주고, 사용하는 방식이다.
    • REST API의 path는 보통 특정 목적을 가지는 resource group 
    • www.sanicbasic.com/api/sanic/Adnl
    • www.sanicbasic.com/api/sanic/B
    • www.sanicbasic.com/api/sanic/C
    • 위와 같은 3개의 API를 만든다고 가정하면 위의 Decorator를 사용하면 
    • 소스는 아래와 같은 형식이 된다.
import sys # system 속성들을 사용하기 위한 import
from sanic import Sanic, response
from sanic.response import text, json

#sanic app을 생성한다.
app = Sanic('main')

#app route annotation으로 /(가장 처음 루트) 경로로 접근 하면, json을 리턴하는 함수를 생성한다.
@app.route('/',['GET'])
async def test(request):
    return json({'hello': 'world'})

@app.route('/api/sanic/a',['GET'])
async def test(request):
    return json({'hello': 'world'})

@app.route('api/sanic/b',['GET'])
async def test(request):
    return json({'hello': 'world'})
    
@app.route('/api/sanic/c',['GET'])
async def test(request):
    return json({'hello': 'world'})
    
def main(argv):
    app.run(host='0.0.0.0', port=8000) # sanic app을 시작 한다. 호트르와 포트를 지정한다.

if __name__ == '__main__': #메인 Procedure if문
    main(sys.argv)
  • 위와 같이 한군데 소스가 몰리고, path(resource)별로 모듈을 나누기 어렵다는 단점을 가지고 있다.

Blueprint

  • 특정 path를 특정 모듈 하나로 묶어 줄 수 있다.
  • 위 source의 예를 들면 blueprint(module, '/api/sanic') 과 같은 형식으로 묶어 줄 수 있다.
  • main.py
import sys # system 속성들을 사용하기 위한 import
from sanic import Sanic, response
from sanic.response import text, json
from sanic_apis import sanic_blueprint
#sanic app을 생성한다.

app = Sanic('main')

#app route annotation으로 /(가장 처음 루트) 경로로 접근 하면, json을 리턴하는 함수를 생성한다.
@app.route('/',['GET'])
async def test(request):
    return json({'hello': 'world'})

app.blueprint(sanic_bludeprint, url_prefix='/api/sanic') // blueprint 모듈 등록

def main(argv):
    app.run(host='0.0.0.0', port=8000) # sanic app을 시작 한다. 호트르와 포트를 지정한다.

if __name__ == '__main__': #메인 Procedure if문
    main(sys.argv)
  • sanic_apis.py
from sanic import Blueprint
from sanic import Sanic, response
from sanic.response import text, json
sanic_blueprint = Blueprint('sanic')

@sanic_blueprint.get('/a')
async def function_a(request):
   return json({'A'})

@sanic_blueprint.get('/b')
async def function_a(request):
   return json({'A'})

@sanic_blueprint.get('/c')
async def function_a(request):
   return json({'A'})
  • 위 두 code에서 볼 수 있는 것과 같이 bludprint를 이용하여, 모듈을 분리하고, sanic_blueprint 이름의 Decorator를 사용하게 되면 무조건 /api/sanic 이라는 path부터 시작하는 api모듈이 된다.
  • 이것은 흡사 nodejs express에서 subrouter를 app.use를 이용하는 생성하는 방식과 유사하다.
  • app.route를 사용한것 보다. 좀더 깔끔하고, 모듈의 목적에 따라 확실하게 분리, 카테고리의 분류가 확실하여 개발의 편의 성이 높아짐을 느낄 수 있다.

  • 다음에는 blude print를 이용하여 다양한 api를 생성하고 다양한 형태의 response를 내주는 코드를 직접 만들어 돌리는 예제를 작성해 보도록 하겠습니다.

'Python' 카테고리의 다른 글

Sanic 시작 하기(GET API 만들기)  (1) 2020.10.24
Sanic 이란  (0) 2020.10.18