当前位置: 代码网 > it编程>前端脚本>Python > 在FastAPI中改变响应状态码的两种方法

在FastAPI中改变响应状态码的两种方法

2025年02月26日 Python 我要评论
引言fastapi,顾名思义,是一个快速、现代、高性能的web框架,用于用python构建后端api。响应状态码是一个三位数,表示请求的结果。例如,200表示ok, 404表示未找到,500表示服务器

引言

fastapi,顾名思义,是一个快速、现代、高性能的web框架,用于用python构建后端api。响应状态码是一个三位数,表示请求的结果。例如,200表示ok, 404表示未找到,500表示服务器内部错误。默认情况下,fastapi将为成功请求返回200状态码,为验证错误返回422状态码。

但是,有时你可能希望更改状态码以指示不同的结果。例如,你可能希望为创建新资源的成功post请求返回201状态码,或者为无法找到所请求资源的get请求返回404状态码。在这篇简明的基于示例的博文中,我将向你展示在fastapi中更改响应状态代码的两种不同方法。

使用路由装饰器的status_code参数

要更改fastapi中的响应状态代码,可以使用@app中的status_code参数。@app.get, @app.post 或其他路由装饰器。status_code参数接受来starlette.status模块的整数值或常量。例如,要为创建新用户的post请求返回201状态码,你可以如下所示:

from fastapi import fastapi
from starlette.status import http_201_created

# create the fastapi instance
app = fastapi()

# set the status code to 201
@app.post("/users", status_code=http_201_created)
def create_user(name: str):
    # some logic to create a new user
    return {"name": name}

在上面的代码片段中,我从starlette.status模块中导入了常量http_201_created。starlette.status模块是starlette框架的一部分,它是fastapi的一个依赖。starlette.status模块为常见的http状态码提供常量,如http_200_ok、http_404_not_found等。使用这些常量可以使代码更具可读性,并避免拼写错误或错误。例如,我可以写status_code=http_201_created,而不是写status_code=201,这样更具描述性和清晰度。

运行下面命令重启服务:

uvicorn main:app --reload

然后去http://localhost:8000/docs, 可以看到文档中code的值与我们配置的一致,方便用户调试程序。

使用响应对象

在这种方法中,我们使用fastapi模块中的response对象在函数体中动态设置状态码。response对象有status_code属性,你可以从starlette.status模块中分配整数值或常量状态值。

下面的例子返回404状态码的get请求,不能找到被请求的用户:

from fastapi import fastapi, response
from starlette.status import http_404_not_found, http_200_ok

app = fastapi()


@app.get("/users/{user_id}")
def get_user(user_id: int, response: response):
    # some logic to get the user by id
    user = none

    if user is none:
        # set the status code
        response.status_code = http_404_not_found
        return {"detail": "user not found"}
    else:
        # set the status code
        response.status_code = http_200_ok
        return user

查看文档,效果与上面一样。

完整实战案例

这是一个完整的代码示例,展示了如何在不同的场景下更改fastapi中的响应状态代码:

# main.py

from fastapi import fastapi, response
from starlette.status import http_201_created, http_404_not_found

app = fastapi()

# a mock database of users
users = [
    {"id": 1, "name": "sling academy"},
    {"id": 2, "name": "ranni the witch"},
    {"id": 3, "name": "khue"},
]


# a helper function to get a user by id
def get_user_by_id(user_id: int):
    for user in users:
        if user["id"] == user_id:
            return user
    return none


# a post route to create a new user and return a 201 status code
@app.post("/users", status_code=http_201_created)
def create_user(name: str):
    # some logic to create a new user and add it to the database
    new_user = {"id": len(users) + 1, "name": name}
    users.append(new_user)
    return new_user


# a get route to get a user by id and return either a 200 or a 404 status code
@app.get("/users/{user_id}")
def get_user(user_id: int, response: response):
    # some logic to get the user by id from the database
    user = get_user_by_id(user_id)
    if user is none:
        response.status_code = http_404_not_found
        return {"detail": "user not found"}
    else:
        return user

最后总结

在本文中,我解释了如何使用两种方法在fastapi中更改响应状态代码:路由装饰器中的status_code参数和函数体中的response对象。你可以根据自己的需要和偏好使用任何一种方法。更改响应状态码可以帮助您更清楚地与客户端进行通信,并遵循restful api设计的最佳实践。

以上就是在fastapi中改变响应状态码的两种方法的详细内容,更多关于fastapi改变响应状态码的资料请关注代码网其它相关文章!

(0)

相关文章:

版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com