Skip to content
Permalink
Browse files

[#5] Schematics validation을 위한 view decorator 추가

  • Loading branch information...
JoMingyu committed Mar 2, 2019
1 parent 577f83b commit 4fa401504d45750b60fdd4455824f5df350cd7bc
Showing with 51 additions and 11 deletions.
  1. +3 −1 app/__init__.py
  2. +6 −10 app/context.py
  3. +33 −0 app/decorators/validation.py
  4. +9 −0 app/hooks/error.py
@@ -1,4 +1,5 @@
from flask import Flask
from schematics.exceptions import BaseError
from werkzeug.exceptions import HTTPException

from app.misc.log import log
@@ -15,10 +16,11 @@ def register_views(flask_app: Flask):


def register_hooks(flask_app: Flask):
from app.hooks.error import broad_exception_handler, http_exception_handler
from app.hooks.error import schematics_baseerror_handler, broad_exception_handler, http_exception_handler
from app.hooks.request_context import after_request

flask_app.after_request(after_request)
flask_app.register_error_handler(BaseError, schematics_baseerror_handler)
flask_app.register_error_handler(HTTPException, http_exception_handler)
flask_app.register_error_handler(Exception, broad_exception_handler)

@@ -1,18 +1,14 @@
from flask import current_app, request
from flask import g


class _ContextProperty:
@property
def secret_key(self) -> str:
return current_app.secret_key
def request_payload_object(self):
return g.request_payload_object

@property
def user_agent(self) -> str:
return request.headers['user_agent']

@property
def remote_addr(self) -> str:
return request.remote_addr
@request_payload_object.setter
def request_payload_object(self, value):
g.request_payload_object = value


context_property = _ContextProperty()
@@ -0,0 +1,33 @@
from enum import Enum
from functools import wraps
from typing import Type

from flask import request
from schematics import Model

from app.context import context_property


class PayloadLocation(Enum):
ARGS = 'args'
JSON = 'json'


class BaseModel(Model):
def validate_additional(self):
raise NotImplementedError # For abstract method


def validate_with_schematics(validation_target: PayloadLocation, model: Type[BaseModel]):
def decorator(fn):
@wraps(fn)
def wrapper(*args, **kwargs):
instance = model(getattr(request, validation_target.value))
instance.validate()
getattr(instance, 'validate_additional', lambda: ...)()

context_property.request_payload_object = instance

return fn(*args, **kwargs)
return wrapper
return decorator
@@ -1,6 +1,15 @@
from flask import jsonify

from schematics.exceptions import BaseError
from werkzeug.exceptions import HTTPException


def schematics_baseerror_handler(e: BaseError):
return jsonify({
'msg': e.to_primitive()
}), 400


def http_exception_handler(e: HTTPException):
return '', e.code

0 comments on commit 4fa4015

Please sign in to comment.
You can’t perform that action at this time.