1 ๋ถ„ ์†Œ์š”

์œ ํšจ์„ฑ ๊ฒ€์‚ฌ - Validation?

์œ ํšจ์„ฑ ๊ฒ€์‚ฌ(Validation)๋ž€, ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ ๋ฐ์ดํ„ฐ๊ฐ€ ์‹ค์ œ ์œ ํšจํ•œ ๊ฐ’์ธ์ง€ ์•„๋‹Œ์ง€๋ฅผ ํŒ๋‹จํ•˜๋Š” ๊ณผ์ •์ด๋‹ค.
์˜ˆ์‹œ๋กœ ๋กœ๊ทธ์ธ ์ƒํ™ฉ์„ ๋“ค ์ˆ˜ ์žˆ๋‹ค.

์‚ฌ์šฉ์ž๊ฐ€ ๋กœ๊ทธ์ธ ํผ์— ์•„์ด๋””์™€ ๋น„๋ฐ€๋ฒˆํ˜ธ๋ฅผ ์ž…๋ ฅํ•˜๋ฉด, ๊ทธ ๊ฐ’๋“ค์ด ์„œ๋ฒ„๋กœ ๋„˜์–ด์˜ฌ ๊ฒƒ์ด๋‹ค.
๊ทธ ๋•Œ, ์•„์ด๋”” ํ˜น์€ ๋น„๋ฐ€๋ฒˆํ˜ธ๊ฐ€ ์‹ค์ œ ํšŒ์› DB์— ์กด์žฌํ•˜๋Š” ๊ฐ’์ธ์ง€, ์ค‘๋ณต๋œ ๊ฐ’์€ ์•„๋‹Œ์ง€ ๋“ฑ์„ ํŒ๋‹จํ•˜๋Š” ๊ณผ์ •์ด ํ•„์š”ํ•  ๊ฒƒ์ด๋‹ค.

DRF(Django Rest Framework)์—์„œ๋Š” ์‚ฌ์šฉ์ž๋กœ๋ถ€ํ„ฐ ๋ฐ›์€ ๊ฐ’์„ ์‹œ๋ฆฌ์–ผ๋ผ์ด์ €(Serializer)๋ฅผ ํ†ตํ•ด ์ง๋ ฌํ™” ๊ณผ์ •์„ ๊ฑฐ์นœ๋‹ค.
์ด ํ›„, ์ง๋ ฌํ™” ํ•œ ๊ฐ’์„ ๊ฐ–๊ณ  ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ๋งˆ์นœ ํ›„์— ๋‚˜๋จธ์ง€ ๋กœ์ง์„ ์ˆ˜ํ–‰ํ•˜๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด๋‹ค.

DRF์—์„œ๋Š” is_valid() ๋ฉ”์„œ๋“œ๋ฅผ ํ†ตํ•ด ์œ ํšจ์„ฑ ๊ฒ€์‚ฌ๋ฅผ ์ˆ˜ํ–‰ํ•œ๋‹ค.

serializer.is_valid()?

is.valid()๋Š” ์‹œ๋ฆฌ์–ผ๋ผ์ด์ €๋ฅผ ํ†ตํ•ด ๋ฐ์ดํ„ฐ๋ฅผ ๋ฐ›์€ ํ›„, ๊ทธ ๊ฐ’์ด ์œ ํšจํ•œ ๊ฐ’์ธ์ง€ ํŒ๋‹จํ•˜๋Š” ๋ฉ”์„œ๋“œ์ด๋‹ค.

is_valid()๋ฉ”์„œ๋“œ์—๋Š” raise_exception=True ํ˜น์€ raise_exception=False ์˜ ์˜ต์…˜์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค.

์•„๋ž˜๋Š” is_valid()๊ฐ€ ๊ตฌํ˜„๋˜์–ด์žˆ๋Š” restframework.serializers.py์˜ ์ผ๋ถ€์ด๋‹ค.

class BaseSerializer(Field):
		...
		
		def is_valid(self, *, raise_exception=False):
        assert hasattr(self, 'initial_data'), (
            'Cannot call `.is_valid()` as no `data=` keyword argument was '
            'passed when instantiating the serializer instance.'
        )

        if not hasattr(self, '_validated_data'):
            try:
                self._validated_data = self.run_validation(self.initial_data)
            except ValidationError as exc:
                self._validated_data = {}
                self._errors = exc.detail
            else:
                self._errors = {}

        if self._errors and raise_exception:
            raise ValidationError(self.errors)

        return not bool(self._errors)
    
		  ...

์ด ์ฝ”๋“œ์—์„œ ๋ณผ ์ˆ˜ ์žˆ๋“ฏ์ด raise_exception ์˜ต์…˜์€ False๊ฐ€ ๊ธฐ๋ณธ๊ฐ’์ด๋‹ค.

raise_exception ์˜ต์…˜์€ ๋ญ˜๊นŒ?

raise_exception ์˜ต์…˜

์ด ์˜ต์…˜์€ is_valid() ๋ฅผ ์ˆ˜ํ–‰ํ•  ๋•Œ, ๊ฐ’์ด ์œ ํšจํ•œ ๊ฐ’์ด ์•„๋‹ˆ๋ฉด ์—๋Ÿฌ๋ฅผ ๋ฐœ์ƒ์‹œํ‚ค๋Š” ์˜ต์…˜์ด๋‹ค.

๋งŒ์•ฝ raise_exception=True ๋กœ ์„ค์ •ํ–ˆ๋Š”๋ฐ, is_valid() ์ค‘ ๊ฐ’ ์ฒดํฌ์—์„œ ์—๋Ÿฌ๊ฐ€ ๋ฐœ์ƒํ•˜๋ฉด ValidationError ๋ฅผ raiseํ•˜๊ฒŒ ๋œ๋‹ค.

๋ณดํ†ต์˜ ๊ฒฝ์šฐ์—๋Š” view์—์„œ ์ค‘๊ฐ„์— exception์ด raise๋  ๊ฒฝ์šฐ, 500 ์„œ๋ฒ„ ์—๋Ÿฌ๋ฅผ ๋ฆฌํ„ดํ•œ๋‹ค.

ํ•˜์ง€๋งŒ, ์˜ต์…˜์„ True๋กœ ์„ค์ •ํ•œ ์ƒํƒœ์—์„œ ValidationError๊ฐ€ raise๋˜๋Š” ๊ฒฝ์šฐ์—๋Š” DRF์—์„œ exception ํ•ธ๋“ค๋Ÿฌ์— ์˜ํ•ด 400 ์ฝ”๋“œ๋ฅผ ๋ฆฌํ„ดํ•˜๊ฒŒ ๋œ๋‹ค.

์ฐธ๊ณ  ์ž๋ฃŒ

[ํ•ด์„ค๊ณผ ํ•จ๊ป˜ ์ฝ๋Š” DRF ๋ฌธ์„œ] Validation - Raising an exception on invalid data

ํƒœ๊ทธ: ,

์นดํ…Œ๊ณ ๋ฆฌ:

์—…๋ฐ์ดํŠธ:

๋Œ“๊ธ€๋‚จ๊ธฐ๊ธฐ