Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Webpy: how to set http status code to 300

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?

like image 400
Giovanni Di Milia Avatar asked Jan 25 '11 19:01

Giovanni Di Milia


People also ask

How do you set a status code in HTTP response?

To set a different HTTP status code from your Servlet, call the following method on the HttpServletResponse object passed in to your server: res. setStatus(nnn); where nnn is a valid HTTP status code.

What are 300 HTTP codes?

The HTTP 300 Multiple Choices redirect status response code indicates that the request has more than one possible responses. The user-agent or the user should choose one of them. As there is no standardized way of choosing one of the responses, this response code is very rarely used.

How do I get my HTTP status code 200?

The HTTP 200 OK success status response code indicates that the request has succeeded. A 200 response is cacheable by default. The meaning of a success depends on the HTTP request method: GET : The resource has been fetched and is transmitted in the message body.


1 Answers

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.

like image 189
Ben Hoyt Avatar answered Sep 19 '22 22:09

Ben Hoyt