response()函数在Python中的作用及用法介绍
发布时间:2023-12-24 08:05:33
在Python中,response()函数是一种用于返回HTTP响应的内置函数。它通常用于构建Web应用程序或API时,用于发送JSON、HTML或其他格式的响应给客户端。
response()函数的用法很简单,可以使用不同的参数来指定响应的类型、内容和状态码。下面是response()函数的用法介绍及示例:
1. 指定响应的类型:
response(content, content_type=None)
- content: 响应的内容,可以是字符串、字节、字典、列表等。
- content_type: 响应的类型,默认为"text/html"。
例子1:返回一个简单的HTML响应。
@app.route("/")
def home():
return response("<h1>Welcome to my website!</h1>")
例子2:返回一个JSON响应。
@app.route("/data")
def get_data():
data = {"name": "John", "age": 30}
return response(data, content_type="application/json")
2. 指定响应的状态码:
response(content, status=None, headers=None)
- content: 响应的内容。
- status: 响应的状态码,默认为"200 OK"。
- headers: 响应的头部信息,可以是一个字典。
例子3:返回一个自定义的状态码。
@app.route("/user")
def get_user():
user = get_user_from_database()
if user is None:
return response("User not found", status="404 Not Found")
else:
return response(user)
3. 添加响应头:
response(content, headers=None)
- content: 响应的内容。
- headers: 响应的头部信息,以字典形式提供。
例子4:返回一个带有自定义响应头的响应。
@app.route("/protected")
def protected_resource():
user = get_authenticated_user()
if user is None:
return response("Unauthorized", status="401 Unauthorized")
else:
headers = {"Authorization": "Bearer " + user.token}
return response("Welcome, " + user.username, headers=headers)
通过使用response()函数,我们可以方便地返回不同类型和状态码的HTTP响应,从而实现更灵活的Web应用程序和API。
