From 316e985eca8a3b83b7592c14694c29a44be889d9 Mon Sep 17 00:00:00 2001 From: j <0x006A@0x2620.org> Date: Mon, 6 Oct 2014 08:29:36 +0000 Subject: [PATCH] support direct json POST and from action/data in api, pass data to api functions --- ox/django/api/actions.py | 5 ++--- ox/django/api/views.py | 16 +++++++++++++--- 2 files changed, 15 insertions(+), 6 deletions(-) diff --git a/ox/django/api/actions.py b/ox/django/api/actions.py index ab08749..6b44777 100644 --- a/ox/django/api/actions.py +++ b/ox/django/api/actions.py @@ -53,7 +53,7 @@ class ApiActions(dict): versions = {} def __init__(self): - def api(request): + def api(request, data): ''' returns list of all known api actions param data { @@ -77,7 +77,6 @@ class ApiActions(dict): } } ''' - data = json.loads(request.POST.get('data', '{}')) docs = data.get('docs', False) code = data.get('code', False) version = getattr(request, 'version', None) @@ -134,7 +133,7 @@ class ApiActions(dict): actions = ApiActions() -def error(request): +def error(request, data): ''' this action is used to test api error codes, it should return a 503 error ''' diff --git a/ox/django/api/views.py b/ox/django/api/views.py index 558a077..43591ed 100644 --- a/ox/django/api/views.py +++ b/ox/django/api/views.py @@ -2,6 +2,8 @@ # vi:si:et:sw=4:sts=4:ts=4 from __future__ import division, with_statement +import json + from django.shortcuts import render_to_response from django.template import RequestContext from django.conf import settings @@ -16,7 +18,9 @@ def api(request): 'text': 'use POST'}}) response['Access-Control-Allow-Origin'] = '*' return response - if not 'action' in request.POST: + if request.META['REQUEST_METHOD'] != "POST" or ( + not 'action' in request.POST and request.META.get('CONTENT_TYPE') != 'application/json' + ): methods = actions.keys() api = [] for f in sorted(methods): @@ -28,14 +32,20 @@ def api(request): 'sitename': settings.SITENAME }) return render_to_response('api.html', context) - action = request.POST['action'] + if request.META.get('CONTENT_TYPE') == 'application/json': + r = json.loads(request.body) + action = r['action'] + data = r.get('data', {}) + else: + action = request.POST['action'] + data = json.loads(request.POST.get('data', '{}')) version = getattr(request, 'version', None) if version: f = actions.versions.get(version, {}).get(action, actions.get(action)) else: f = actions.get(action) if f: - response = f(request) + response = f(request, data) else: response = render_to_json_response(json_response(status=400, text='Unknown action %s' % action))