sanic-org / sanic

Accelerate your web app development | Build fast. Run fast.

Home Page:https://sanic.dev

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

添加在使用return json时,自定义状态码为405(或是其他错误代码)时,如果自定义了body,使用开发者自定义的body进行返回

David-xian66 opened this issue · comments

commented

Is there an existing issue for this?

  • I have searched the existing issues

Is your feature request related to a problem? Please describe.

添加在使用return json时,自定义状态码为405(或是其他错误代码)时,如果自定义了body,使用开发者自定义的body进行返回

我今天写了一个API,我写了在请求方式不对时,返回405错误代码 并且返回我自定义的json,但是sanic就是使用了默认的错误信息…

Describe the solution you'd like

在自定义body值的时候,错误信息使用body的值

Additional context

No response

commented

我的部分代码


app.config.FALLBACK_ERROR_FORMAT = "json"


@app.route("/api/panel")
async def test(request):
    if request.method == 'GET':
        return json({
            "status": 200, 
            "time": 0
        },status=200)
    else:
        return json(body=ErrorRequest(), status=405)

Sorry, we use English to discuss feature requests. Please reopen a new issue in English. If you would like, we have several languages supported in our Discord server.

注意,app.route默认只接受GET方式。这就是为什么如果你试图对该处理程序进行POST或其他操作,你会得到一个错误。

你可以通过methods参数自定义它。

commented

注意,app.route默认只接受GET方式。这就是为什么如果你试图对处理程序进行POST或其他操作,你会得到一个错误。>> 你可以通过methods参数自定义它。

OK 感谢

commented

有没有具体事例呢🤔

@app.get("/")
async def index_get(request):
    ...

@app.post("/", name="index_post")
@app.put("/", name="index_put")
@app.delete("/", name="index_delete")
async def index_modify(request):
    ...

Or if you really want that many on one handler,

@app.route("/", methods=["GET", "POST", "PUT", "DELETE"])
async def index(request):
    ...
commented
@app.get("/")
async def index_get(request):
    ...

@app.post("/", name="index_post")
@app.put("/", name="index_put")
@app.delete("/", name="index_delete")
async def index_modify(request):
    ...

Or if you really want that many on one handler,

@app.route("/", methods=["GET", "POST", "PUT", "DELETE"])
async def index(request):
    ...

OK!Thank you, thank you so much