Example #1
0
def personas(request):
    """
    Actions over the personas list
    """
    if request.method == 'GET':  # list of exiting personas
        sqs = Persona.objects.filter(is_ready=True)
        if 'public' in request.GET:
            sqs = sqs.filter(is_public=True)

        result = [get_persona_data(request, persona) for persona in sqs]
        return JsonResponse(result, safe=False)
    elif request.method == 'POST':  # create a new persona
        form = PersonaAPIForm(request.POST)

        if not form.is_valid():
            return JsonResponse({'error': form.errors}, status=400, safe=False)

        # create the (not ready) object
        p = form.save()

        err = update_query(p, request.POST)
        if err:  # some error occurred
            return err

        return JsonResponse(get_persona_data(request, p), safe=False, status=201)
    elif request.method in ['PUT', 'DELETE']:
        return JsonResponse({'error': '%s method over entire persona list disabled' % request.method}, status=400)
    else:
        return JsonResponse({'error': 'Only GET, POST methods allowed'}, status=400)
Example #2
0
def persona(request, pk):
    """
    Actions over a specific persona
    """
    try:
        p = Persona.objects.get(pk=pk)
    except ObjectDoesNotExist:
        return JsonResponse({'error': 'Persona #%s not found' % pk}, status=404)

    if request.method == 'GET':
        return JsonResponse(get_persona_data(request, p), safe=False)
    elif request.method == 'POST':
        data = request.POST.copy()
        # (partial) update
        if 'name' not in data:
            data['name'] = p.name
        if 'description' not in data:
            data['description'] = p.description
        if 'avatar' not in data:
            data['avatar'] = p.avatar
        if 'is_public' not in data:
            data['is_public'] = p.is_public

        # validate form
        form = PersonaAPIForm(data, instance=p)

        if not form.is_valid():
            return JsonResponse({'error': form.errors}, status=400)

        # special case for query -- additional actions required
        if 'query' in data and p.query != data.get('query'):
            err = update_query(p, data)
            if err:  # some error occurred
                return err

        return JsonResponse(get_persona_data(request, p), safe=False)
    elif request.method == 'DELETE':
        p.delete()
        return HttpResponse(status=204)
    else:
        return JsonResponse({'error': 'Only GET, POST, DELETE methods allowed'}, status=400)