使用bottle.response模块在Python中处理不同类型的HTTP响应
发布时间:2023-12-26 02:35:22
在Python中,可以使用bottle.response模块来处理不同类型的HTTP响应。该模块提供了一系列函数,可以用于设置响应的状态码、头部和内容。
下面是一个使用bottle.response模块处理不同类型的HTTP响应的示例:
from bottle import route, run, response
# 设置路由
@route('/hello')
def hello():
response.content_type = 'text/plain' # 设置内容类型为纯文本
return 'Hello, World!'
@route('/json')
def json():
response.status = 200 # 设置状态码为200
response.content_type = 'application/json' # 设置内容类型为JSON
return {'message': 'Hello, World!'}
@route('/error')
def error():
response.status = 500 # 设置状态码为500
response.content_type = 'text/html' # 设置内容类型为HTML
return '<h1>Internal Server Error</h1>'
# 运行应用
run(host='localhost', port=8080)
在上面的示例中,定义了三个不同的路由,分别处理/hello、/json和/error的请求。
/hello路由返回一个纯文本的响应,使用response.content_type将内容类型设置为text/plain。
/json路由返回一个JSON格式的响应,使用response.status设置状态码为200,使用response.content_type将内容类型设置为application/json,并且返回一个包含message字段的字典。
/error路由返回一个HTML格式的错误响应,使用response.status设置状态码为500,使用response.content_type将内容类型设置为text/html,并且返回一个HTML字符串。
注意,在每个路由函数中,都需要通过response对象来设置响应的状态码、内容类型等信息。可以通过设置response.status来设置状态码,通过设置response.content_type来设置内容类型。
以上示例只是演示了如何使用bottle.response模块处理不同类型的HTTP响应。实际应用中,可以根据需要对响应进行更复杂的处理,例如设置响应头部、设置Cookies等。
