Is there a better way to check if AJAX request values ​​are valid?

I am creating an AJAX backend for a Django application, and I do not know if I am building it correctly. Currently, to accept integer values, I need to give them to integers using the int () function, which throws exceptions and ends 500 times if I don't use a lot of patterns. This makes my code look a little messier than I would like, and I don't know if I am doing it right. This is an example of an AJAX view from an application:

@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()

As you can see, I need to make a lot of templates and disable some exceptions from the language itself, which concerns me, based on the PHP background. Is there a better way to do this or am I doing it right?

+4
1

Marshmallow, , , . 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)
0

All Articles