python cherrypy - how to add header

sam picture sam · May 19, 2011 · Viewed 8.5k times · Source

How can I add retry-header in cherrypy?

  import cherrypy
  import os

  class Root:

    def index(self):
      cherrypy.response.headers['Retry-After'] = 60
      cherrypy.request.headers["Age"]= 20
      cherrypy.config.update({'Retry-After': '60'})

      raise cherrypy.HTTPError(503, 'Service Unavailable')
    index.exposed = True 

    cherrypy.quickstart(Root())

This retry-header dt works.

Answer

Pär Wieslander picture Pär Wieslander · May 19, 2011

When you set a status code by raising HTTPError, the headers in cherrypy.response.headers are ignored. Set the HTTP status by setting cherrypy.response.status instead:

import cherrypy

class Root:
    def index(self):
        cherrypy.response.headers['Retry-After'] = 60
        cherrypy.response.status = 503
        # Feel free to return a better error page than the following
        return "<h1>Service Unavailable</h1>"
    index.exposed = True

cherrypy.quickstart(Root())