request 对象

request 对象是客户端的 HTTP 请求对象,每次客户端发起请求,请求的内容都包含在 request 这个对象里面。


headers

request.headers 属性是一个字典,包含了所有的 HTTP 请求头信息。你可以使用它来访问请求中的各种头部数据,比如 User-Agent、Content-Type、Authorization 等。

from bottle import Bottle, request, run

app = Bottle()

@app.route('/')
def index():
    # 获取所有请求头
    headers = request.headers

    # 打印所有请求头
    for header, value in headers.items():
        print(f'{header}: {value}')

    return "Check the console for request headers."

run(app, host='localhost', port=8080)

method

请求方法。

@route('/')
def index():    
    return request.method # 返回 GET

path

请求路径。

@route('/')
def index():    
    return request.path # 返回 /

query

GET 请求参数获取。

@route('/')
def index():    
    return request.query.id # 请求 /?id=123 返回 123

forms

POST 请求参数获取。

@route('/', method=['post'])
def index(): 
    return request.forms.name 
    # 通过 HTTP POST X-WWW-form-urlencoded (name=jmjc) 请求 | 返回 jmjc

params

GET 和 POST 请求参数获取。

@route('/', method=['get'])
def index(): 
    return request.params.id # 通过 /?id=123 请求,返回 123

@route('/', method=['post'])
def index(): 
    return request.params.name # 通过 post name=jmjc 请求,返回 jmjc

json

application/json 请求参数获取。

@route('/', method=['post'])
def index(): 
    return request.json # 通过 application/json {"name":"jmjc"} 请求,返回 {"name":"jmjc"}

客户端 IP 获取

@route('/')
def index(): 
    return request.environ.get('REMOTE_ADDR') # 获取客户端 IP
CATEGORIES