我正在为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背景。有没有更好的方法来做到这一点,还是我正确地做事?
答案 0 :(得分:0)
如果您不反对使用框架Marshmallow将为您处理序列化和反序列化,除了简单的类型检查之外定义自定义验证非常容易,并且它非常棒。汤姆克里斯蒂甚至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)