Nick Heiner
Nick Heiner

Reputation: 122480

Error handling in Django-Piston

In Django-Piston, is there a good way to do error handling? (Like returning a 400 status code when the caller omits a required GET parameter, or when the parameters are invalid.)

Upvotes: 2

Views: 1756

Answers (1)

goldstein
goldstein

Reputation: 467

Django-piston respects HTTP status codes and handles common erros by default (auth, etc), but you can also throw new exceptions or status using rc from piston.utils.

For example:

from django.contrib.auth.models import User
from piston.handler import AnonymousBaseHandler
from piston.utils import rc

class AnonymousUserHandler(AnonymousBaseHandler):
    allowed_methods = ('GET', )
    fields = ('id', 'username',)

    def read(self, request):
        try:
            user = User.objects.get(username=request.GET.get('username', None))
            return user
        except Exception:
            resp = rc.NOT_FOUND
            resp.write(' User not found')
            return resp

Check out all utilities at https://django-piston-sheepdog.readthedocs.io/en/latest/helpers.html

Upvotes: 4

Related Questions