python hug api返回自定义http代码

时间:2017-01-03 13:28:31

标签: python api http hug

找了好一会儿后问: https://gitter.im/timothycrosley/hug 我无法找到解决方案。

我正在寻找的是一种返回自定义http代码的方法,如果在get端点满足条件,则说204。 路由问题的解释是here

但我似乎无法找到一种方法来返回除200以外的任何其他代码

4 个答案:

答案 0 :(得分:5)

在他们的回购(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

答案 1 :(得分:1)

基于jbasko的回答,看起来hugs期望status是HTTP状态代码的文本表示。

所以,例如:

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
...

因此,对于更完整的示例,您可以使用所有响应的字典:

onbeforeunload

我编制了所有status_codes in this gist

的列表

答案 2 :(得分:0)

您可以引发falcon HTTPError,例如:

raise HTTPInternalServerError

查看更多详情:https://falcon.readthedocs.io/en/stable/api/errors.html

答案 3 :(得分:0)

除了jbasko和toast38coza答案外,猎鹰中还有一个实用程序函数来获取数字状态代码的文本表示形式:

falcon.get_http_status(200)

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

如此:

import hug
import falcon

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