bigywater.tech
Flask · 31

Werkzeug Request 对象

request 上到底有哪些属性?url、base_url、url_root 有什么区别?哪些是 Flask 自己加的?请求体为什么只能读一次?这篇用一个真实请求把属性逐个打印出来。

11
flask.Request 自己定义的公开成员个数
1 次
请求体 stream 能被读取的次数
3.2 µs
构造请求对象并读取 3 个属性的耗时

一个请求上的属性

实测 · 本机执行输出
  request.accept_json    = True
  request.base_url       = 'https://shop.example.test:8443/base/inspect/7'
  request.content_length = 7
  request.content_type   = 'application/json'
  request.endpoint       = 'inspect_'
  request.full_path      = '/inspect/7?x=1&y=2'
  request.host           = 'shop.example.test:8443'
  request.host_url       = 'https://shop.example.test:8443/'
  request.is_json        = True
  request.is_secure      = True
  request.method         = 'POST'
  request.mimetype       = 'application/json'
  request.path           = '/inspect/7'
  request.referrer       = 'http://ref.test/'
  request.remote_addr    = '203.0.113.9'
  request.scheme         = 'https'
  request.script_root    = '/base'
  request.type           = 'flask.wrappers.Request'
  request.url            = 'https://shop.example.test:8443/base/inspect/7?x=1&y=2'
  request.url_root       = 'https://shop.example.test:8443/base/'
  request.url_rule       = '/inspect/<int:n>'
  request.user_agent     = 'lab/1.0'
  request.view_args      = {'n': 7}

上一篇:URL 中的 Unicode 与编码;下一篇:Query String 参数解析。

Flask 的 Request 类

实测 · 本机执行输出
  flask.Request 自己定义的公开成员: ['blueprint', 'blueprints', 'endpoint', 'json_module', 'max_content_length', 'max_form_memory_size', 'max_form_parts', 'on_json_loading_failed', 'routing_exception', 'url_rule', 'view_args']
  继承链: ['flask.wrappers.Request', 'werkzeug.wrappers.request.Request', 'werkzeug.sansio.request.Request']

惰性解析

实测 · 本机执行输出
  构造后缓存里已有: ['cookies', 'headers'] | 访问 args 与 form 之后: ['args', 'cookies', 'files', 'form', 'headers']

请求体只能读一次

实测 · 本机执行输出
  get_data() 两次: b'hello body' b'hello body' | 随后读 stream: b''
  先读 stream 再 get_data(): b'hello body' b''

remote_addr

实测 · 本机执行输出
  REMOTE_ADDR=10.0.0.2、X-Forwarded-For=198.51.100.7 → request.remote_addr = 10.0.0.2

开销

实测 · 本机执行输出
  每次构造并读取:3.2 µs

分步演示

Request 对象
本步的对象

    本文用到的工具与边界

    • 本机 macOS 27 arm64 / Python 3.14.7 / Flask 3.1.3 / Werkzeug 3.1.9 / Jinja2 3.1.6 / SQLAlchemy 2.1.1 / gunicorn 26.2.0(都装在自己的虚拟环境里);大多数实验用 Flask 的 test_client(直接调用 WSGI 应用,不经过网络),需要真实 HTTP 时另起 gunicorn 或开发服务器(端口 9600 以上,本机 127.0.0.1);计时用 time.perf_counter,数字每次运行会有小幅抖动
    • 没有验证:真实网络服务器下 environ 里 REMOTE_ADDR、SERVER_PORT 等的来源、user_agent 解析的细节(Werkzeug 3 已弱化)、chunked 请求体的 content_length、request.max_content_length 的行为(见第 37 篇)
    京ICP备2026067502号-1京公网安备11010502063487号