Custom Response
By default, when you use render to generate the response (e.g. render.as_view(), render.as_json()), the framework handles the HTTP response for you. It automatically sets status code 200, assigns the correct content type (text/html, application/json, etc.), sets character encoding to UTF-8 and writes the output.
However, if you need full control over the response—such as returning a different status code, setting custom headers, or streaming raw output—you can assign a function directly to ctx.go_to.
Example: Custom Header
class Export(object):
def image_viewer(self, ctx):
file_path = "/path/to/image.jpg"
def add_cache_header():
response = ctx.getResponse()
response.setStatus(200)
response.setContentType("image/jpeg")
# set cache for 1 hour
response.setHeader("Cache-Control", "public, max-age=3600")
# write the file to the response output stream
with open(file_path, "rb") as file:
output_stream = response.getOutputStream()
output_stream.write(file.read())
output_stream.flush()
return None # No further processing needed
ctx.go_to = add_cache_header
This method bypasses render and uses the raw HttpServletResponse object. You can stream files, return binary data, or generate server-push content by writing directly to the output stream.