python中的魔法方法深入理解

字號:


    接觸python也有一段時間了,python相關(guān)的框架和模塊也接觸了不少,希望把自己接觸到的自己 覺得比較好的設(shè)計和實(shí)現(xiàn)分享給大家,于是取了一個“charming python”的小標(biāo),算是給自己開了一個頭吧, 希望大家多多批評指正。 :)
    from flask import request
    flask 是一個人氣非常高的python web框架,筆者也拿它寫過一些大大小小的項(xiàng)目,flask 有一個特性我非常的喜歡,就是無論在什么地方,如果你想要獲取當(dāng)前的request對象,只要 簡單的:
    代碼如下:
    from flask import request
    # 從當(dāng)前request獲取內(nèi)容
    request.args
    request.forms
    request.cookies
    ... ...
    非常簡單好記,用起來也非常的友好。不過,簡單的背后藏的實(shí)現(xiàn)可就稍微有一些復(fù)雜了。 跟隨我的文章來看看其中的奧秘吧!
    兩個疑問?
    在我們往下看之前,我們先提出兩個疑問:
    疑問一 : request ,看上去只像是一個靜態(tài)的類實(shí)例,我們?yōu)槭裁纯梢灾苯邮褂胷equest.args 這樣的表達(dá)式來獲取當(dāng)前request的args屬性,而不用使用比如:
    代碼如下:
    from flask import get_request
    # 獲取當(dāng)前request
    request = get_request()
    get_request().args
    這樣的方式呢?flask是怎么把request對應(yīng)到當(dāng)前的請求對象的呢?
    疑問二 : 在真正的生產(chǎn)環(huán)境中,同一個工作進(jìn)程下面可能有很多個線程(又或者是協(xié)程), 就像我剛剛所說的,request這個類實(shí)例是怎么在這樣的環(huán)境下正常工作的呢?
    要知道其中的秘密,我們只能從flask的源碼開始看了。
    源碼,源碼,還是源碼
    首先我們打開flask的源碼,從最開始的__init__.py來看看request是怎么出來的:
    代碼如下:
    # file: flask/__init__.py
    from .globals import current_app, g, request, session, _request_ctx_stack
    # file: flask/globals.py
    from functools import partial
    from werkzeug.local import localstack, localproxy
    def _lookup_req_object(name):
        top = _request_ctx_stack.top
        if top is none:
            raise runtimeerror('working outside of request context')
        return getattr(top, name)
    # context locals
    _request_ctx_stack = localstack()
    request = localproxy(partial(_lookup_req_object, 'request'))
    我們可以看到flask的request是從globals.py引入的,而這里的定義request的代碼為 request = localproxy(partial(_lookup_req_object, 'request')) , 如果有不了解 partial是什么東西的同學(xué)需要先補(bǔ)下課,首先需要了解一下 partial 。
    不過我們可以簡單的理解為 partial(func, 'request') 就是使用 'request' 作為func的第一個默認(rèn)參數(shù)來產(chǎn)生另外一個function。
    所以, partial(_lookup_req_object, 'request') 我們可以理解為:
    生成一個callable的function,這個function主要是從 _request_ctx_stack 這個localstack對象獲取堆棧頂部的第一個requestcontext對象,然后返回這個對象的request屬性。
    這個werkzeug下的localproxy引起了我們的注意,讓我們來看看它是什么吧:
    代碼如下:
    @implements_bool
    class localproxy(object):
        acts as a proxy for a werkzeug local.  forwards all operations to
        a proxied object.  the only operations not supported for forwarding
        are right handed operands and any kind of assignment.
        ... ...
    看前幾句介紹就能知道它主要是做什么的了,顧名思義,localproxy主要是就一個proxy, 一個為werkzeug的local對象服務(wù)的代理。他把所以作用到自己的操作全部“轉(zhuǎn)發(fā)”到 它所代理的對象上去。
    那么,這個proxy通過python是怎么實(shí)現(xiàn)的呢?答案就在源碼里:
    代碼如下:
    # 為了方便說明,我對代碼進(jìn)行了一些刪減和改動
    @implements_bool
    class localproxy(object):
        __slots__ = ('__local', '__dict__', '__name__')
        def __init__(self, local, name=none):
            # 這里有一個點(diǎn)需要注意一下,通過了__setattr__方法,self的
            # _localproxy__local 屬性被設(shè)置成了local,你可能會好奇
            # 這個屬性名稱為什么這么奇怪,其實(shí)這是因?yàn)閜ython不支持真正的
            # private member,具體可以參見官方文檔:
            # 在這里你只要把它當(dāng)做 self.__local = local 就可以了 :)
            object.__setattr__(self, '_localproxy__local', local)
            object.__setattr__(self, '__name__', name)
        def _get_current_object(self):
            獲取當(dāng)前被代理的真正對象,一般情況下不會主動調(diào)用這個方法,除非你因?yàn)?BR>            某些性能原因需要獲取做這個被代理的真正對象,或者你需要把它用來另外的
            地方。
            # 這里主要是判斷代理的對象是不是一個werkzeug的local對象,在我們分析request
            # 的過程中,不會用到這塊邏輯。
            if not hasattr(self.__local, '__release_local__'):
                # 從localproxy(partial(_lookup_req_object, 'request'))看來
                # 通過調(diào)用self.__local()方法,我們得到了 partial(_lookup_req_object, 'request')()
                # 也就是 ``_request_ctx_stack.top.request``
                return self.__local()
            try:
                return getattr(self.__local, self.__name__)
            except attributeerror:
                raise runtimeerror('no object bound to %s' % self.__name__)
        # 接下來就是一大段一段的python的魔法方法了,local proxy重載了(幾乎)?所有python
        # 內(nèi)建魔法方法,讓所有的關(guān)于他自己的operations都指向到了_get_current_object()
        # 所返回的對象,也就是真正的被代理對象。
        ... ...
        __setattr__ = lambda x, n, v: setattr(x._get_current_object(), n, v)
        __delattr__ = lambda x, n: delattr(x._get_current_object(), n)
        __str__ = lambda x: str(x._get_current_object())
        __lt__ = lambda x, o: x._get_current_object() < o
        __le__ = lambda x, o: x._get_current_object() <= o
        __eq__ = lambda x, o: x._get_current_object() == o
        __ne__ = lambda x, o: x._get_current_object() != o
        __gt__ = lambda x, o: x._get_current_object() > o
        __ge__ = lambda x, o: x._get_current_object() >= o
        ... ...
    事情到了這里,我們在文章開頭的第二個疑問就能夠得到解答了,我們之所以不需要使用get_request() 這樣的方法調(diào)用來獲取當(dāng)前的request對象,都是localproxy的功勞。
    localproxy作為一個代理,通過自定義魔法方法。代理了我們對于request的所有操作, 使之指向到真正的request對象。
    怎么樣,現(xiàn)在知道了 request.args 不是它看上去那么簡簡單單的吧。
    現(xiàn)在,讓我們來看看第二個問題,在多線程的環(huán)境下,request是怎么正常工作的呢? 還是讓我們回到globals.py吧:
    代碼如下:
    from functools import partial
    from werkzeug.local import localstack, localproxy
    def _lookup_req_object(name):
        top = _request_ctx_stack.top
        if top is none:
            raise runtimeerror('working outside of request context')
        return getattr(top, name)
    # context locals
    _request_ctx_stack = localstack()
    request = localproxy(partial(_lookup_req_object, 'request'))
    問題的關(guān)鍵就在于這個 _request_ctx_stack 對象了,讓我們找到localstack的源碼:
    代碼如下:
    class localstack(object):
        def __init__(self):
            # 其實(shí)localstack主要還是用到了另外一個local類
            # 它的一些關(guān)鍵的方法也被代理到了這個local類上
            # 相對于local類來說,它多實(shí)現(xiàn)了一些和堆?!皊tack”相關(guān)方法,比如push、pop之類
            # 所以,我們只要直接看local代碼就可以
            self._local = local()
        ... ...
        @property
        def top(self):
            返回堆棧頂部的對象
            try:
                return self._local.stack[-1]
            except (attributeerror, indexerror):
                return none
    # 所以,當(dāng)我們調(diào)用_request_ctx_stack.top時,其實(shí)是調(diào)用了 _request_ctx_stack._local.stack[-1]
    # 讓我們來看看local類是怎么實(shí)現(xiàn)的吧,不過在這之前我們得先看一下下面出現(xiàn)的get_ident方法
    # 首先嘗試著從greenlet導(dǎo)入getcurrent方法,這是因?yàn)槿绻鹒lask跑在了像gevent這種容器下的時候
    # 所以的請求都是以greenlet作為最小單位,而不是thread線程。
    try:
        from greenlet import getcurrent as get_ident
    except importerror:
        try:
            from thread import get_ident
        except importerror:
            from _thread import get_ident
    # 總之,這個get_ident方法將會返回當(dāng)前的協(xié)程/線程id,這對于每一個請求都是唯一的
    class local(object):
        __slots__ = ('__storage__', '__ident_func__')
        def __init__(self):
            object.__setattr__(self, '__storage__', {})
            object.__setattr__(self, '__ident_func__', get_ident)
        ... ...
        # 問題的關(guān)鍵就在于local類重載了__getattr__和__setattr__這兩個魔法方法
        def __getattr__(self, name):
            try:
                # 在這里我們返回調(diào)用了self.__ident_func__(),也就是當(dāng)前的唯一id
                # 來作為__storage__的key
                return self.__storage__[self.__ident_func__()][name]
            except keyerror:
                raise attributeerror(name)
        def __setattr__(self, name, value):
            ident = self.__ident_func__()
            storage = self.__storage__
            try:
                storage[ident][name] = value
            except keyerror:
                storage[ident] = {name: value}
        ... ...
        # 重載了這兩個魔法方法之后
        # local().some_value 不再是它看上去那么簡單了:
        # 首先我們先調(diào)用get_ident方法來獲取當(dāng)前運(yùn)行的線程/協(xié)程id
        # 然后獲取這個id空間下的some_value屬性,就像這樣:
        #
        #   local().some_value -> local()[current_thread_id()].some_value
        #
        # 設(shè)置屬性的時候也是這個道理
    通過這些分析,相信疑問二也得到了解決,通過使用了當(dāng)前的線程/協(xié)程id,加上重載一些魔法 方法,flask實(shí)現(xiàn)了讓不同工作線程都使用了自己的那一份stack對象。這樣保證了request的正常 工作。
    說到這里,這篇文章也差不多了。我們可以看到,為了使用者的方便,作為框架和工具的開發(fā)者 需要付出很多額外的工作,有時候,使用一些語言上的魔法是無法避免的,python在這方面也有著 相當(dāng)不錯的支持。
    我們所需要做到的就是,學(xué)習(xí)掌握好python中那些魔法的部分,使用魔法來讓自己的代碼更簡潔, 使用更方便。