7

在寻找了很长一段时间并询问后: https ://gitter.im/timothycrosley/hug 我无法找到解决方案。

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

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

4

4 回答 4

6

在他们的仓库中找到了一个例子(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
于 2017-01-03T19:56:23.513 回答
2

您可以引发 falcon HTTPError,例如:

raise HTTPInternalServerError

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

于 2017-10-24T02:47:33.527 回答
1

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

因此,例如:

>> print (HTTP_400)
Bad Request

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

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

我已经编译了这个 gist中所有 status_codes 的列表

于 2017-04-08T17:21:38.010 回答
0

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

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)
于 2019-04-12T12:21:06.013 回答