views:

34

answers:

1

Hey everyone,

I'm trying to patch a testing framework built in python for javascript called mootools-test-runner (i'm a front end developer by day, so my python skills are pretty weak... really weak.)

The use case is we want to be able to make a json request to the server and have it delay x amount of time before it returns -- originally it was written to use a sleep method, but that prevented multiple simultaneous requests. Sooo... after poking around for about a day i arrived at the code below. The problem i'm seeing (although there could well be many problems with my code) is:

The view test_runner.views.echo_json didn't return an HttpResponse object.

if anyone could offer any advice or point me in the right direction I would be super grateful -- thanks!

def echo_json(req, wasDelayed=False):
   if req.REQUEST.get('delay') and wasDelayed == False:
        sleeper(req, echo_jsonp)
   else:
        response = {}
        callback = req.REQUEST.get('callback', False)
        noresponse_eys = ['callback', 'delay']
        for key, value in req.REQUEST.items():
           if key not in noresponse_keys:
               response.update({key: value})

        response = simplejson.dumps(response)

        if callback:
           response = '%s(%s);' % (callback, response)

        return HttpResponse(response, mimetype='application/javascript')

def sleeper(req, callback)
    delay = float(req.REQUEST.get('delay'))
    t = threading.Timer(delay, functools.partial(callback, req, true))
    t.start()
A: 

Are you sure you want the return statement inside the for key, value loop? You're only allowing a single iteration, and returning.

Also, check the flow of the function. There are cases in which it will return None. Easiest way to do this is printing out your request object and examining it in the cases in which the function doesn't return an HttpResponse object.

See that your function will return None if:

  • req.request contains the key 'delay' and wasDelayed is True
  • req.REQUEST.items() is empty

I can't be sure, but I think the 2 problems are the else: and the return there. Shouldn't the code below the else: be executing whether the response is delayed or not? And shouldn't the return statement be outside the for loop?

Santiago Lezica
Yeah, it looks like you've got an extra indentation on that return line. Try dedenting it a stop.
Paul McMillan
The else executes the same code in some kind of weird sleep loop. A more standard way to do that would be with a while.
Paul McMillan
the return inside teh for loop was a copy paste error -- sorry about that. thanks for your help
jacobthornton
A copy-paste error in the code, or in the post here? Do you need further help?
Santiago Lezica
in my original post i had a copy paste error -- i'm now working though trying to get @unutbu solution working
jacobthornton