如果你想把你的请求正文作为多行文本发送,你需要做一些事情。
Create a PlainTextParser
之所以需要这样做,是因为DjangoRestFramework默认将JSONParser作为其默认程序,这就是为什么你会看到你所收到的错误信息。
If you follow this
GuidLine
you will see how to implement it.
import codecs
from django.conf import settings
from rest_framework.exceptions import ParseError
from rest_framework.parsers import BaseParser
class PlainTextParser(BaseParser):
media_type = "text/plain"
def parse(self, stream, media_type=None, parser_context=None):
Parses the incoming bytestream as Plain Text and returns the resulting data.
parser_context = parser_context or {}
encoding = parser_context.get('encoding', settings.DEFAULT_CHARSET)
decoded_stream = codecs.getreader(encoding)(stream)
text_content = decoded_stream.read()
return text_content
except ValueError as exc:
raise ParseError('Plain text parse error - %s' % str(exc))
Add that parser to Django Rest Framework configuration
REST_FRAMEWORK = {
'DEFAULT_PARSER_CLASSES': [
'rest_framework.parsers.JSONParser',
'path.to.PlainTextParser' # Replace path.to with you project path to that class
如果你想让它只在特定的视图上工作,你可以将它添加到其parser_classes
中。
When you do your request in DjangoRestFramwork Browsable API, choose text/plain as your media type, and in your http client put Content-Type: text/plain
This should be it, I hope it helps.