Flask RESTX

x·2023년 5월 8일
0

flask

목록 보기
1/1

Flask-RESTX는 flask에서 REST API를 빠르게 만들 수 있게 해준다

Resource

여러 HTTP 메서드들에 접근할 수 있게 해줌
지원하지 않는 HTTP 메서드면 405 method not allowed 리턴함
적절한 메서드면 호출되고 모든 인수들이 전달됨

from flask import Flask, request
from flask_restx import Resource, Api

app = Flask(__name__)
api = Api(app)

todos = {}

@api.route('/<string:todo_id>')
class TodoSimple(Resource):
    def get(self, todo_id):
        return {todo_id: todos[todo_id]}

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}

if __name__ == '__main__':
    app.run(debug=True)

뷰 메서드에서의 다양한 값을 응답할 수 있음. 응답 상태코드, 응답 헤더도 응답 가능

class Todo3(Resource):
    def get(self):
        # Set the response code to 201 and return custom headers
        return {'task': 'Hello world'}, 201, {'Etag': 'some-opaque-string'}

add_namespace
네임스페이스에 또 다른 네임스페이스를 추가하고 path에 추가되는 네임스페이스 prefix를 지정할 수 있음

ns.add_namespace(another_ns, path=None)

route
리소스를 라우팅하는 데코레이터

parser
스키마 검증하는 용도. marshmallow같은 더 나은 스키마 벨리데이터로 대체된다고 함.

parser = api.parser()
parser.add_argument('param', type=int, help='Some param', location='form')
parser.add_argument('in_files', type=FileStorage, location='files')


@api.route('/with-parser/', endpoint='with-parser')
class WithParserResource(restx.Resource):
    @api.expect(parser)
    def get(self):
        return {}

Namespace

URL 자원을 묶는 용도

from flask_restx import Namespace

ns = Namespace('user' description='사용자')

doc

api 문서를 객체에 추가하기 위한 데코레이터

ns = Namespace('user' description='사용자')

@ns.doc(body={"age": "유저 나이"}, params={"id": "유저 id"}

response

응답 데코레이터

@ns.response(204, '성공')
@ns.response(400, '에러')

model

API나 네임스페이스에 모델 등록
모델 name, model 필드에 따른 타입 지정 등을 함
doc 데코레이터에 스키마로 활용할 수 있음

my_fields = api.model('MyModel', {
    'name': fields.String,
    'age': fields.Integer(min=0)
})

clone

모델의 모든 필드를 복사함.
클론할 모델을 써주고 필드를 추가할 수 있음. 상속같은 느낌

api.clone("child_user_fields", user_fields, {
	"address": fields,String
})

0개의 댓글