跳转到主要内容

Django的轻量级JSON辅助函数集合。

项目描述

Building Status

A lightweight collection of JSON helpers for Django. Includes a template filter for safely outputting JSON, views that encode and decode JSON, and a helper for writing simple REST views.

A special JSON encoder is used to serialize QuerySets and objects with to_json methods.

过滤器

You can serialize an object in JSON using the |json filter. This is useful to generate safe JavaScript

{% load argonauts %}
<script type="application/javascript">
  (function () {
      var object_list = {{ object_list|json }};
      // do something with object_list
  })();
</script>

|json is safe to use anywhere in XML or XHTML except in an attribute. It’s important to use this tag rather than dumping the output of json.dumps into HTML, because an attacker could output a closing tag and effect an XSS attack. For example, if we output json.dumps("</script><script>console.log('xss'); //") in template like this

<script>
  var somedata = {{ somedata_as_json|safe }};
</script>

We get

<script>
  var somedata = "</script>
<script>
  console.log('xss'); //";
</script>

This allows the attacker to inject their own JavaScript. The |json tag prevents this by encoding the closing </script> tag with JSON’s unicode escapes. If we output {{ somedata|json }}, we get

<script>
  var somedata = "\u0060xscript\u0062x\u0060xscript\u0062xconsole.log('xss');//";
</script>

它还会转义 ampersands 以生成有效的 XML。例如,使用值 foo & bar

<document><json>{{ value|json }}</json></document>
<!-- Results in valid XML:
<document><json>"foo \u0038x bar"</json></document>
-->

视图

JsonResponseMixin

JsonResponseMixin 实现了将对象序列化为 JSON 响应的 render_to_response 方法。因此,它与通用 Django 视图兼容

from django.db import models
from django.views.generic.detail import BaseDetailView
from argonauts.views import JsonResponseMixin

class Blog(models.Model):
    title = models.CharField(max_length=255)
    body = models.TextField()

    def to_json(self):
        return {
            'title': self.title,
            'body': self.body,
        }

class BlogDetailView(JsonResponseMixin, BaseDetailView):
    """
    Detail view returning object serialized in JSON
    """
    model = Blog

JsonRequestMixin

JsonRequestMixin 通过 data() 方法提供对请求数据的访问。

from django.views.generic.base import View
from argonauts.views import JsonRequestMixin:
from argonauts.http import JsonResponse

class EchoView(JsonRequestMixin, View):
    def dispatch(self, *args, **kwargs):
        return JsonResponse(self.data())

RestView

RestView 是一个抽象类。子类应实现 auth(),用于处理身份验证,以及至少一个 HTTP 方法。

RestView 实现了 OPTIONS HTTP 方法,并从 JsonRequestMixinJsonResponseMixin 继承。

from django.core.exceptions import PermissionDenied
from argonauts.views import RestView
from .utils import get_action

class CrazyRestView(RestView):
    def auth(self, *args, **kwargs):
        if not self.request.user.is_superuser:
            raise PermissionDenied

    def post(self, *args, **kwargs):
        action = kwargs.pop('action')
        action_func = get_action(action)
        return self.render_to_response(action_func(self.data()))

变更日志

1.2.0 (2016-09-20)

  • 为 JsonTestClient 添加了对没有 Content-Type 头的请求的支持

  • 移除了对旧版本 Django 的支持(<= 1.7)

1.1.4 (2015-07-29)

  • 测试模拟的 http 请求不总是有字符集

1.1.3 (2015-05-27)

  • 修复了包(包括 MANIFEST.in 中的 CHANGELOG)

1.1.2 (2015-05-27)

  • 添加了 JsonTestCaseJsonTestMixin

1.1.1 (2015-04-20)

  • 修复了包

1.1.0 (2015-04-20)

清理

  • 放弃了 Django 1.3 的支持

  • 添加了对 Python 3 的支持

  • 更新了文档

  • 将测试切换到 py.test

  • 切换到 zest.releaser

1.0.1 (2013-10-06)

  • 修复了测试

1.0.0 (2013-07-05)

初始发布

  • 从 django-fusionbox 中提取

  • 安全 JSON 序列化器

  • 安全 JSON 模板过滤器

  • JSON 视图

项目详情


下载文件

下载您平台上的文件。如果您不确定选择哪个,请了解有关 安装包 的更多信息。

源分发

django-argonauts-1.2.0.tar.gz (7.4 kB 查看哈希值)

上传时间

由以下机构支持

AWS AWS 云计算和安全赞助商 Datadog Datadog 监控 Fastly Fastly CDN Google Google 下载分析 Microsoft Microsoft PSF 赞助商 Pingdom Pingdom 监控 Sentry Sentry 错误日志 StatusPage StatusPage 状态页面