mirror of
https://github.com/django/django.git
synced 2025-04-12 03:22:21 +00:00
Added can_handle to BaseParser
This commit is contained in:
parent
caab50bb85
commit
0fd67b89ef
@ -8,6 +8,9 @@ from django.utils.datastructures import ImmutableList, MultiValueDict
|
||||
class BaseParser:
|
||||
media_type = None
|
||||
|
||||
def can_handle(self, media_type):
|
||||
return media_type == self.media_type
|
||||
|
||||
def parse(self, request):
|
||||
pass
|
||||
|
||||
|
@ -363,7 +363,7 @@ class HttpRequest:
|
||||
|
||||
selected_parser = None
|
||||
for parser in parser_list:
|
||||
if self.content_type == parser.media_type:
|
||||
if parser.can_handle(self.content_type):
|
||||
selected_parser = parser
|
||||
break
|
||||
|
||||
|
27
tests/requests_tests/test_parsers.py
Normal file
27
tests/requests_tests/test_parsers.py
Normal file
@ -0,0 +1,27 @@
|
||||
from unittest import TestCase
|
||||
|
||||
from django.http.parsers import BaseParser, FormParser, MultiPartParser
|
||||
|
||||
|
||||
class TestParsers(TestCase):
|
||||
def test_can_handle(self):
|
||||
parser = MultiPartParser()
|
||||
self.assertIs(parser.can_handle("multipart/form-data"), True)
|
||||
self.assertIs(parser.can_handle("application/json"), False)
|
||||
|
||||
parser = FormParser()
|
||||
self.assertIs(parser.can_handle("application/x-www-form-urlencoded"), True)
|
||||
self.assertIs(parser.can_handle("multipart/form-data"), False)
|
||||
|
||||
def test_custom_can_handle(self):
|
||||
class CustomParser(BaseParser):
|
||||
media_type = "text/*"
|
||||
|
||||
def can_handle(self, media_type):
|
||||
main_type, sub_type = media_type.split("/")
|
||||
return main_type == "text"
|
||||
|
||||
parser = CustomParser()
|
||||
self.assertIs(parser.can_handle("application/json"), False)
|
||||
self.assertTrue(parser.can_handle("text/*"), True)
|
||||
self.assertTrue(parser.can_handle("text/csv"), True)
|
Loading…
x
Reference in New Issue
Block a user