check login decorator for json responses

Март 21, 2010

Django has a login_required decorator that redirects to the login page if user is not authenticated, here I’ll show how to write a custom decorator for json responses. If the uses is authenticated then decorated function returns the desired data otherwise some error in json format.
NB — this decorator is for view functions with request as a first argument.

import simplejson as json

def check_login(view_func):
	def check(*args):
		request = args[0]		
		if not request.user or not request.user.is_active:			
			return HttpResponse(json.dumps({"error" : u"%s" % strings.loginRequired}))
		else: return view_func(*args)
	return check

It also uses simplejson package that can be downloaded from here.

Usage:

@check_login
def view_func(request):
	return json.dumps({some data})	

tags: ,
posted in Python, Web by dmitko

1 Comment to "check login decorator for json responses"

  1. Trifonov wrote:

    а можно себе в блог Вашу статью скопировать? =)

 
Powered by Wordpress and MySQL. Theme by Shlomi Noach, openark.org