7

After looking for it for quite a while and asking on: https://gitter.im/timothycrosley/hug I'm unable to find a solution.

what I'm looking for is a way to return a custom http code, lets say 204 in case a condition is met in the get end point. the explanation for routing problems is here

but I can't seem to find a way to return any other codes other than 200 with a null response

Manel
  • 176
  • 4
  • 16
Nick Kobishev
  • 157
  • 4
  • 13
  • In the page you linked it says use status= in the route decorator for that. Don't know hug so don't know how you'd do that dynamically. – jbasko Jan 03 '17 at 13:32
  • well the thing is that i dont need it to depend on a routing problem but rather a condition in the code/exception thrown – Nick Kobishev Jan 03 '17 at 14:18

4 Answers4

6

Found an example in their repo (https://github.com/berdario/hug/blob/5470661c6f171f1e9da609c3bf67ece21cf6d6eb/examples/return_400.py)

import hug
from falcon import HTTP_400

@hug.get()
def only_positive(positive: int, response):
    if positive < 0:
        response.status = HTTP_400
jbasko
  • 7,028
  • 1
  • 38
  • 51
2

You can raise the falcon HTTPError, for example:

raise HTTPInternalServerError

see more details: https://falcon.readthedocs.io/en/stable/api/errors.html

Ford Guo
  • 957
  • 9
  • 18
1

Building on jbasko's answer, it looks like hugs expects status to be the text representation of the HTTP status code.

So, for example:

>> print (HTTP_400)
Bad Request

So, for a more complete example, you can use a dict of all the responses:

STATUS_CODES = {
    100: "100 Continue",
    101: "101 Switching Protocols",
    102: "102 Processing",

    200: "200 OK",
    201: "201 Created",
    ...
}
response.status = STATUS_CODES.get(200) # 200 OK
response.status = STATUS_CODES.get(404) # 404 Not Found
# etc
...

I've compiled a list of all the status_codes in this gist

toast38coza
  • 8,650
  • 3
  • 39
  • 32
0

In addition to jbasko and toast38coza answers, there is a utility function in falcon to get the text representation of numeric status codes:

falcon.get_http_status(200)

https://falcon.readthedocs.io/en/stable/api/util.html#falcon.get_http_status

so:

import hug
import falcon

@hug.get()
def only_positive(positive: int, response):
    if positive < 0:
        response.status = falcon.get_http_status(400)
alpoza
  • 460
  • 4
  • 7