【问题标题】:Is there a better way to check if the values of an AJAX request are valid?有没有更好的方法来检查 AJAX 请求的值是否有效?
【发布时间】:2016-10-28 07:30:27
【问题描述】:

我正在为 Django 应用程序构建 AJAX 后端,我不知道我是否正确构建它。目前要接受整数值,我需要使用 int() 将它们类型转换为整数,如果我不应用太多样板文件,这会引发异常并始终以 500 结束。这导致我的代码看起来比我想要的稍微混乱,而且我不知道我是否做得正确。这是应用程序中的示例 AJAX 视图:

@ajax_required
def poll(request):
    try:
        last_id = int(request.POST.get('last_id'))
        feed_type = request.POST['feed_type']
    except (KeyError, TypeError):
        return HttpResponseBadRequest()

    if feed_type == 'following' and request.user.is_authenticated():
        posts = Post.get_posts(user=request.user, after_id=last_id)
        return JsonResponse({
            'html': render_to_string('posts/raw_posts.html', {'posts': posts}),
            'count': posts.count()
        })

    return HttpResponseForbidden()

如您所见,我必须做很多样板文件并消除语言本身的一些例外情况,这与我有关,来自 PHP 背景。有没有更好的方法来做到这一点,还是我做的正确?

【问题讨论】:

  • 捕获一个 KeyError 并忘记如果,使用request.POST["last_id"],是什么引发了TypeError
  • @PadraicCunningham 这种方法的问题是当类型转换为 int 时会引发 TypeError。
  • pastebin.com/YsTDFjCL 投射时应该会因输入错误而引发 ValueError
  • @PadraicCunningham 嗯,很好。会改变。编辑:完成
  • @PadraicCunningham 非常感谢您的观察,现在将进行编辑。

标签: jquery python ajax django


【解决方案1】:

如果您不反对使用框架Marshmallow 将为您处理序列化和反序列化,那么除了简单的类型检查之外,定义自定义验证非常容易,而且非常棒。 Tom Christie 甚至有 wrapped it up 用于 Django。

编辑: 如果你选择使用它,你的代码看起来更像这样:

from rest_marshmallow import Schema, fields

class FeedSchema(Schema):
    last_id = fields.Integer()
    feed_type = fields.String()

@ajax_required
def poll(request):
    try:
        # Validate request
        serializer = FeedSchema(data=request.data)
        serializer.is_valid(raise_exception=True)
        data = serializer.validated_data
        # Return posts
        if data['feed_type'] == 'following' and request.user.is_authenticated():
            posts = Post.get_posts(user=request.user, after_id=data['last_id'])
            return JsonResponse({
                'html': render_to_string('posts/raw_posts.html', {'posts': posts}),
                'count': posts.count()
            })
        # The user isn't authenticated or they requested a feed type they don't have access to.
        return HttpResponseForbidden()
    except ValidationError as err:
        return HttpResponseBadRequest(err.messages)

【讨论】:

  • 看起来很像 Django 表单,我正在挖掘它。肯定会尝试的。谢谢!
猜你喜欢
  • 2010-09-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-20
  • 1970-01-01
  • 2022-09-22
  • 2015-09-05
相关资源
最近更新 更多