Issue #1176 resolved

Custom Response Headers documentation fix

Anonymous created an issue


I was looking for documented way to add 'Cash-control: no-cache' header to server response.

The best place with examples I found was Custom Response Headers section:

Unfortunately, this section has example only for advanced header modification, while simple one (using cherrypy.response.headers) is not documented.

I tried to adapt advanced example to simple one and found that advanced example does not work in Python 3. Request to '' replies error:

Unrecoverable error in the server.
Traceback (most recent call last):
  File "C:\Data\Bisoft Logistics\dev\python\webapi\venv32\lib\site-packages\cherrypy\", line 169, in trap
    return func(*args, **kwargs)
  File "C:\Data\Bisoft Logistics\dev\python\webapi\venv32\lib\site-packages\cherrypy\", line 96, in __call__
    return self.nextapp(environ, start_response)
  File "C:\Data\Bisoft Logistics\dev\python\webapi\venv32\lib\site-packages\cherrypy\", line 379, in tail
    return self.response_class(environ, start_response, self.cpapp)
  File "C:\Data\Bisoft Logistics\dev\python\webapi\venv32\lib\site-packages\cherrypy\", line 233, in __init__
    raise TypeError("response.header_list key %r is not a byte string." % k)
TypeError: response.header_list key 'foo' is not a byte string.

So I had to read cherrypy sources to develop simple example. Then I found that in advanced example you create cherrypy.tool 'on_end_resource', where it is already useless to modify cherrypy.response.headers. Hooking-up to 'before_finalize' is the last place to where modified cherrypy.response.headers are converted to cherrypy.response.header_list. It is also documented that using cherrypy.response.headers is better in general, but nowhere is documented how. I am sure it can save a lot of time if this section would be documented with simple example and have advanced example fixed.

Here is simple example I was looking for:

import cherrypy

def multi_headers():
    cherrypy.response.headers.update(cherrypy.response.multiheaders) = cherrypy.Tool('before_finalize', multi_headers)

class Root(object):
    def index(self):
        cherrypy.response.multiheaders = {'Cach-Control': 'no-cache'}
        return "Hello"


Thank you!



Comments (3)

  1. Jason R. Coombs

    You're right. I looked through the documentation and they seem to assume you're familiar with the basic usage of CherryPy headers. There's even a more simple way to handle them:

    import cherrypy
    class Root(object):
      def index(self):
        cherrypy.response.headers['Cache-Control'] = 'no-cache'
        return "Hello"

    I agree the introductory documentation could have some material on using headers. I believe this introductory material used to be in the tutorial, which is no longer part of the documentation.

  2. Log in to comment