Search code examples
pythonrequesttwisted

Twisted: returning from a blocking request


I have a render() function which does not make use of deferreds, because it is faster to return the response directly. I don't want to return a bytestring directly, but write it first into the request object, finalize it manually and then return. It is important that I'm able to use the return statement in the second code snippet.

def render(self, request)
  return b"not authorized"

should become (if it is okay to do so)

def render(self, request)
  request.write(b"not authorized")
  request.finish()
  return NOT_DONE_YET

I've noticed that when I return anything else than NOT_DONE_YET I get an exceptions.RuntimeError: Request.write called on a request after Request.finish was called.

There are valid examples which make use of a very similar sequence:

  request.redirect(...)
  request.finish()
  return NOT_DONE_YET

So, is it ok to use the combination of write / finished / NOT_DONE_YET?


Solution

  • Ok, according to a docstring in Twisted's source code,

    render_METHOD methods are expected to return a byte string which will be the rendered page, unless the return value is C{server.NOT_DONE_YET}, in which case it is this class's responsibility to write the results using C{request.write(data)} and then call C{request.finish()}.