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?
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With