HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythondjangoMinor

Decorator to take away repetitive code

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
awaytakerepetitivecodedecorator

Problem

I'm using django and I wrote this decorator to take away some of the repetitive code I found for ajax views and I want to know your opinion (too basic, bad design, try this instead, etc).

def ajax_only(func):
    def _ajax_only(request,*args,**kwargs):
        if not request.is_ajax():
            return HttpResponse('Ajax not supported.')
        else:
            return func(request,*args,**kwargs)
    return _ajax_only

Solution


  • You should use the functools.wraps function, it makes sure the docstring/name/etc gets passed through



  • Instead of "ajax not supported" shouldn't it be: "only ajax supported"?



  • Shouldn't you respond with a Status Code 400 or something if not using ajax when you should be



  • Why do you want to check this? What's the point of enforcing ajax calls, won't that just make testing harder?

Context

StackExchange Code Review Q#7826, answer score: 6

Revisions (0)

No revisions yet.