support direct json POST and from action/data in api, pass data to api functions

This commit is contained in:
j 2014-10-06 08:29:36 +00:00
parent 2d467ea6c6
commit 316e985eca
2 changed files with 15 additions and 6 deletions

View file

@ -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
'''

View file

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