小编kal*_*sin的帖子

在字符串中规范化lineends的最pythonic方法是什么?

给定一个未知来源的文本字符串,如何最好地重写它以获得已知的lineend-convention?

我经常这样做:

lines = text.splitlines()
text = '\n'.join(lines)
Run Code Online (Sandbox Code Playgroud)

...但是这并不处理完全混淆的约定的"混合"文本文件(是的,它们仍然存在!).

编辑

我正在做的事情当然是:

'\n'.join(text.splitlines())
Run Code Online (Sandbox Code Playgroud)

......那不是我要问的.

之后的总行数应该相同,因此不会剥离空行.

测试用例

拆分

'a\nb\n\nc\nd'
'a\r\nb\r\n\r\nc\r\nd'
'a\rb\r\rc\rd'
'a\rb\n\rc\rd'
'a\rb\r\nc\nd'
'a\nb\r\nc\rd'
Run Code Online (Sandbox Code Playgroud)

..应该全部产生5行.在混合上下文中,splitlines假定'\ r \n'是单个逻辑换行符,导致最后两个测试用例为4行.

Hm,包含'\ r \n'的混合上下文可以通过比较splitlines()和split('\n')和/或split('\ r')的结果来检测...

python newline line-breaks

7
推荐指数
2
解决办法
5092
查看次数

如何在Django Rest Framework JSON API中生成JSON-API数据属性vs结果属性?

我有一个使用Django Rest Framework JSON API的django 1.9.2项目:

https://github.com/django-json-api/django-rest-framework-json-api:

我的视图看起来像这样:

class QuestionViewSet(viewsets.ReadOnlyModelViewSet):
    """
    API endpoint that allows questions and answers to be read.
    """
    resource_name = 'questions'
    queryset = Question.objects.all()
    serializer_class = QuestionSerializer
    renderers = renderers.JSONRenderer
    parsers = parsers.JSONParser
Run Code Online (Sandbox Code Playgroud)

典型响应如下:

{"links": {"first": "http://testserver/api/v1/coaches?page=1", "last": "http://testserver/api/v1/coaches?page=1", "next": null, "prev": null}, "results": [{"id": 1, "created": "2016-02-11T02:41:22.569000Z", "updated": null, "deleted": null, "uuid": "0473c709-994f-465b-989e-407c623f365f", "user": {"type": "User", "id": "2"}}, {"id": 2, "created": "2016-02-11T02:41:46.853000Z", "updated": null, "deleted": null, "uuid": "36e19c0e-bda6-4bd7-bc73-374a6fc509d6", "user": {"type": "User", "id": "3"}}, {"id": …
Run Code Online (Sandbox Code Playgroud)

python django django-rest-framework json-api

6
推荐指数
1
解决办法
266
查看次数

如何将渲染器连接到视图集中的特定端点,并且仅连接到该端点

DRF 文档展示了如何将渲染器连接到 APIView,但没有展示如何针对 ViewSet 中的特定操作执行此操作。鉴于:

class XViewSet(ViewSet):
    serializer_class = XSerializer

    @action(detail=True, methods=['get'])
    def my_action(self, request, pk=None):
         ..
Run Code Online (Sandbox Code Playgroud)

如何设置特定的渲染器my_action,使其不会影响视图集中的其他/默认操作?

当然,我可以为该操作创建一个 APIView,但这会导致 urls.py 变得更加混乱

django-rest-framework

5
推荐指数
1
解决办法
1113
查看次数