目录

Werkzeug 源码解析(3)

Werkzeug Request 源码解析

代码示例:

1
2
3
4
5
6
7
8
from werkzeug.wrappers import Request, Response

def application(environ, start_response):
    request = Request(environ)
    text = 'Hello %s!' % request.args.get('name', 'World')
    response = Response(text, mimetype='text/plain')
    return response(environ, start_response)

请注意,之后RequestResponse的相关源码都会围绕Werkzeug给出的以上代码讲解。

Request 类

文件定位

src/werkzeug/wrappers/request.py

作用

根据Request类的名称其实就可以知道,Request类是处理请求的,实际上,通过阅读相关代码,Request类的作用确实如此

分析

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class Request(
    BaseRequest,
    AcceptMixin,
    ETagRequestMixin,
    UserAgentMixin,
    AuthorizationMixin,
    CORSRequestMixin,
    CommonRequestDescriptorsMixin,
):
    """Full featured request object implementing the following mixins:

    -   :class:`AcceptMixin` for accept header parsing
    -   :class:`ETagRequestMixin` for etag and cache control handling
    -   :class:`UserAgentMixin` for user agent introspection
    -   :class:`AuthorizationMixin` for http auth handling
    -   :class:`~werkzeug.wrappers.cors.CORSRequestMixin` for Cross
        Origin Resource Sharing headers
    -   :class:`CommonRequestDescriptorsMixin` for common headers

    """

​ 根据注释可知,除了BaseRequest类之外,其他的Mixin类都是作为添加高级方法的类。而且Request类也没有初始化方法,所以可以将注意力从Request转移到BaseRequest类上面。

BaseRequest 类

截取以上代码示例的代码

1
request = Request(environ)

调用父类BaseRequest__init__方法

1
2
3
4
5
    def __init__(self, environ, populate_request=True, shallow=False):
        self.environ = environ
        if populate_request and not shallow:
            self.environ["werkzeug.request"] = self
        self.shallow = shallow