response 对象
response 是 Bottle 框架中用于处理 HTTP 响应的一个对象,通常用于设置返回给客户端的内容、状态码、头信息等。
response.status
用于设置响应的状态码。
from bottle import response
@route('/some_route')
def some_view():
response.status = 404 # 设置响应状态码为 404
return "Page Not Found"response.content_type
用于设置响应的 Content-Type,即返回的内容类型。例如,如果你返回的是 JSON 数据,可以设置为 application/json。
@route('/json_data')
def json_view():
response.content_type = 'application/json'
return '{"message": "hello world"}'response.body
用于直接设置响应的主体内容。body 属性是一个字节串(bytes),用于返回数据。
@route('/raw_data')
def raw_data():
response.body = b'Raw binary data'
return response.body一个完整示例
from bottle import route, run, response
@route('/hello')
def hello():
response.status = 200
response.content_type = 'text/plain'
response.headers['X-Custom-Header'] = 'HelloHeader'
return "Hello, Bottle!"
run(host='localhost', port=8080)