在Django REST API中将json数据作为纯文本发布,并添加新行

2024-06-29 00:56:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个python服务(web),其中我想使用djangorestapi输入带有新行的纯文本。比如说,

输入:
3
一月
二月
六月

我想在下面的django API内容表单中输入带有新行的约束。见下图

enter image description here

在APIView中检索post输入值后,我将通过一些计算获得输出。响应将作为JSON输出。例如,[“01”、“02”、“03”]

我的问题是当我试图发布输入内容时(有新行的文本)。它给出如下错误:, enter image description here

如何通过这个python Django REST API输入(带新行的纯文本),输出将作为一个有序json数组的响应

提前感谢您的指导方针


Tags: django文本restapiwebjson表单内容
2条回答

如果您想将请求正文作为多行文本发送,您需要做几件事

  1. 创建一个明文解析器

This is needed because DjangoRestFramework by default has JSONParser as its default, that is why you are seeing the error message you are receiving

如果您遵循这个GuidLine,您将看到如何实现它

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)

        try:
            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))

  1. 将该解析器添加到Django Rest框架配置中
REST_FRAMEWORK = {
    ...
    'DEFAULT_PARSER_CLASSES': [
        'rest_framework.parsers.JSONParser',
        'path.to.PlainTextParser' # Replace path.to with you project path to that class
    ],
    ...
}

If you want it to only work on specific Views, you can add it to its parser_classes

  1. 当您在DjangoRestFramwork Browsable API中执行请求时,请选择text/plain作为媒体类型,并在http客户端putContent-Type: text/plain

这应该是它,我希望它有帮助

尝试使用raw string literals而不是您正在做的事情

    In [4]: n_s="This is \t Stack over \n flow"

    In [5]: r_s=r"This is  \t Stack over \n flow" 

    In [8]: print(n_s)
    This is      Stack over 
    flow

   In [9]: print(r_s)
   This is  \t Stack over \n flow

尝试以三重引号r''..''发布

相关问题 更多 >