16

Maybe it is a stupid question but I cannot figure out how to a http status code in webpy.

In the documentation I can see a list of types for the main status codes, but is there a generic function to set the status code?

I'm trying to implement an unAPI server and it's required to reply with a 300 Multiple Choices to a request with only an identifier. More info here

Thanks!

EDIT: I just discovered that I can set it through web.ctx doing

web.ctx.status = '300 Multiple Choices'

is this the best solution?

Martin Brown
  • 24,692
  • 14
  • 77
  • 122
Giovanni Di Milia
  • 13,480
  • 13
  • 55
  • 67

1 Answers1

17

The way web.py does this for 301 and other redirect types is by subclassing web.HTTPError (which in turn sets web.ctx.status). For example:

class MultipleChoices(web.HTTPError):
    def __init__(self, choices):
        status = '300 Multiple Choices'
        headers = {'Content-Type': 'text/html'}
        data = '<h1>Multiple Choices</h1>\n<ul>\n'
        data += ''.join('<li><a href="{0}">{0}</a></li>\n'.format(c)
                        for c in choices)
        data += '</ul>'
        web.HTTPError.__init__(self, status, headers, data)

Then to output this status code you raise MultipleChoices in your handler:

class MyHandler:
    def GET(self):
        raise MultipleChoices(['http://example.com/', 'http://www.google.com/'])

It'll need tuning for your particular unAPI application, of course.

See also the source for web.HTTPError in webapi.py.

Ben Hoyt
  • 10,694
  • 5
  • 60
  • 84