About jason

jason is a set of lightweight helpers that makes it simpler to return JSON http responses from a Django view.

Installation

Can be downloaded from PyPi, or via a package manager:

pip install jason

Documentation

jason.response(data={}, status=200, message='OK')

Wraps the arguments in a dictionary and returns a HttpResponse object with the HTTP status set to status. The body of the response is JSON data on the format:

{
    "status": 400,
    "message": "OK",
    "data": {"ids": [1, 2, 3]}
}

The content of data is serialized using the DjangoJSONEncoder class.

Example:

import jason

def my_view(request):
    return jason.response({'weight': 80}, 200, 'OK')
jason.view(allowed_methods, exceptions={})

Decorates a Django function based view and wraps it’s return in the jason.response() function. The view should return a list or tuple which is unpacked using the *-operator into jason.response().

The view can raise a jason.Bail Exception.

allowed_methods lists which HTTP methods are allowed, e.g. [‘GET’, ‘POST’].

exceptions is a dictionary where the keys are Exception classes and values are callables. It defines responses for raised Exceptions other than the jason.Bail Exception. The callable should return a tuple or list that can unpacked into jason.response().

Example:

import jason

@jason.view(allowed_methods=['GET', 'POST'], exceptions={
    WebFault: lambda e: ({}, 400, e.message, )
})
def my_view(request):
    return {'numbers': get_numbers()},
jason.permission_required(perm)

A json pendant to permission_required. Will return a 401 response if the user is not allowed. The body of the response will be the following json data:

{
    "status": 401,
    "message": "Unauthorized",
    "data": {}
}

Example:

import jason

@jason.permission_required("my_perm")
def my_view(request):
    ...
exception jason.Bail(data={}, status=400, message='Bad Request')

This exception can be raised inside a view decorated by jason.view(). The arguments are the same as to jason.response(). When raised the return of the view will be the output of the jason.response() function.

Example:

import jason

@jason.view(allowed_methods=['GET'])
def my_view(request):
    if not_to_my_liking():
        raise jason.Bail({}, 400, 'Do not like!')

    ...

Table Of Contents

This Page