bottle Python HTTP 自定义响应码最小示例

bottle 中,你可以通过首先导入 HTTPResponse 来生成自定义 HTTP 响应码:

bottle_custom_response.py
from bottle import HTTPResponse

然后,在你的 @route 函数中,raise 一个 HTTPResponse,例如

bottle_raise_httpresponse.py
raise HTTPResponse("This is a HTTP 401 test URL", status=401)

完整示例

bottle_custom_server.py
#!/usr/bin/env python3
from bottle import HTTPResponse, route, run

@route('/test401')
def hello():
    raise HTTPResponse("This is a HTTP 401 test URL", status=401)

run(host='localhost', port=8080, debug=True)

运行此脚本,然后打开 http://localhost/test401,这将导致 HTTP 401(未授权)响应码,带有

output.txt
This is a HTTP 401 test URL

作为响应体。


Check out similar posts by category: Python