Adding a better API view decorator for required paramters, their types, and http method used.

This commit is contained in:
Samuel Clay 2012-12-12 13:58:10 -08:00
parent 31d1c828f7
commit dac88c0a25
2 changed files with 72 additions and 9 deletions

View file

@ -26,6 +26,7 @@ from utils import json_functions as json
from utils import log as logging
from utils.user_functions import get_user, ajax_login_required
from utils.view_functions import render_to, is_true
from utils.view_functions import required_params
from utils.story_functions import format_story_link_date__short
from utils.story_functions import format_story_link_date__long
from utils.story_functions import strip_tags
@ -457,7 +458,8 @@ def load_social_page(request, user_id, username=None, **kwargs):
template = 'social/social_page.xhtml'
return render_to_response(template, params, context_instance=RequestContext(request))
@required_params('story_id', feed_id=int)
def story_public_comments(request):
format = request.REQUEST.get('format', 'json')
relative_user_id = request.REQUEST.get('user_id', None)
@ -467,11 +469,18 @@ def story_public_comments(request):
if not relative_user_id:
relative_user_id = get_user(request).pk
stories = MSharedStory.objects.filter(story_feed_id=feed_id, story_guid=story_id).limit(1)
stories = Feed.format_stories(stories)
stories, profiles = MSharedStory.stories_with_comments_and_profiles(stories, relative_user_id,
story, _ = MStory.find_story(story_feed_id=feed_id, story_id=story_id)
if not story:
return json.json_response(request, {
'message': "Story not found.",
'code': -1,
})
story = Feed.format_story(story)
stories, profiles = MSharedStory.stories_with_comments_and_profiles([story],
relative_user_id,
check_all=True)
if format == 'html':
stories = MSharedStory.attach_users_to_stories(stories, profiles)
return render_to_response('social/story_comments.xhtml', {

View file

@ -1,12 +1,17 @@
from django.http import Http404
from django.http import Http404, HttpResponse
from django.template import RequestContext
from django.shortcuts import render_to_response
from utils import json_functions as json
import functools
def get_argument_or_404(request, param, method='REQUEST'):
def get_argument_or_404(request, param, method='REQUEST', code='404'):
try:
return getattr(request, method)[param]
except KeyError:
raise Http404
if code == '404':
raise Http404
else:
return
def render_to(template):
"""
@ -36,4 +41,53 @@ def render_to(template):
def is_true(value):
if value == 1:
return True
return bool(value) and isinstance(value, basestring) and value.lower() not in ('false', '0')
return bool(value) and isinstance(value, basestring) and value.lower() not in ('false', '0')
class required_params(object):
"Instances of this class can be used as decorators"
def __init__(self, *args, **kwargs):
self.params = args
self.named_params = kwargs
self.method = kwargs.get('method', 'REQUEST')
def __call__(self, fn):
def wrapper(request, *args, **kwargs):
return self.view_wrapper(request, fn, *args, **kwargs)
functools.update_wrapper(wrapper, fn)
return wrapper
def view_wrapper(self, request, fn, *args, **kwargs):
if request.method != self.method and self.method != 'REQUEST':
return self.disallowed(method=True, status_code=405)
for param in self.params:
if not getattr(request, self.method).get(param):
return self.disallowed(param)
for param, param_type in self.named_params.items():
if not getattr(request, self.method).get(param):
return self.disallowed(param)
try:
if not param_type(getattr(request, self.method).get(param)):
return self.disallowed(param, param_type)
except (TypeError, ValueError):
return self.disallowed(param, param_type)
return fn(request, *args, **kwargs)
def disallowed(self, param=None, param_type=None, method=False, status_code=400):
if method:
message = "Invalid method. Use %s." % self.method
elif param_type:
message = "Invalid paramter: %s - needs to be %s" % (
param,
param_type,
)
else:
message = "Missing parameter: %s" % param
print status_code
return HttpResponse(json.encode({
'message': message,
'code': -1,
}), mimetype="application/json", status=status_code)