标题 | python中的魔法方法深入理解 |
内容 | 接触python也有一段时间了,python相关的框架和模块也接触了不少,希望把自己接触到的自己 觉得比较好的设计和实现分享给大家,于是取了一个“charming python”的小标,算是给自己开了一个头吧, 希望大家多多批评指正。 :) from flask import request flask 是一个人气非常高的python web框架,笔者也拿它写过一些大大小小的项目,flask 有一个特性我非常的喜欢,就是无论在什么地方,如果你想要获取当前的request对象,只要 简单的: 代码如下: from flask import request # 从当前request获取内容 request.args request.forms request.cookies ... ... 非常简单好记,用起来也非常的友好。不过,简单的背后藏的实现可就稍微有一些复杂了。 跟随我的文章来看看其中的奥秘吧! 两个疑问? 在我们往下看之前,我们先提出两个疑问: 疑问一 : request ,看上去只像是一个静态的类实例,我们为什么可以直接使用request.args 这样的表达式来获取当前request的args属性,而不用使用比如: 代码如下: from flask import get_request # 获取当前request request = get_request() get_request().args 这样的方式呢?flask是怎么把request对应到当前的请求对象的呢? 疑问二 : 在真正的生产环境中,同一个工作进程下面可能有很多个线程(又或者是协程), 就像我刚刚所说的,request这个类实例是怎么在这样的环境下正常工作的呢? 要知道其中的秘密,我们只能从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是什么东西的同学需要先补下课,首先需要了解一下 partial 。 不过我们可以简单的理解为 partial(func, 'request') 就是使用 'request' 作为func的第一个默认参数来产生另外一个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对象服务的代理。他把所以作用到自己的操作全部“转发”到 它所代理的对象上去。 那么,这个proxy通过python是怎么实现的呢?答案就在源码里: 代码如下: # 为了方便说明,我对代码进行了一些删减和改动 @implements_bool class localproxy(object): __slots__ = ('__local', '__dict__', '__name__') def __init__(self, local, name=none): # 这里有一个点需要注意一下,通过了__setattr__方法,self的 # _localproxy__local 属性被设置成了local,你可能会好奇 # 这个属性名称为什么这么奇怪,其实这是因为python不支持真正的 # private member,具体可以参见官方文档: # 在这里你只要把它当做 self.__local = local 就可以了 :) object.__setattr__(self, '_localproxy__local', local) object.__setattr__(self, '__name__', name) def _get_current_object(self): 获取当前被代理的真正对象,一般情况下不会主动调用这个方法,除非你因为 某些性能原因需要获取做这个被代理的真正对象,或者你需要把它用来另外的 地方。 # 这里主要是判断代理的对象是不是一个werkzeug的local对象,在我们分析request # 的过程中,不会用到这块逻辑。 if not hasattr(self.__local, '__release_local__'): # 从localproxy(partial(_lookup_req_object, 'request'))看来 # 通过调用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 # 内建魔法方法,让所有的关于他自己的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() 这样的方法调用来获取当前的request对象,都是localproxy的功劳。 localproxy作为一个代理,通过自定义魔法方法。代理了我们对于request的所有操作, 使之指向到真正的request对象。 怎么样,现在知道了 request.args 不是它看上去那么简简单单的吧。 现在,让我们来看看第二个问题,在多线程的环境下,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')) 问题的关键就在于这个 _request_ctx_stack 对象了,让我们找到localstack的源码: 代码如下: class localstack(object): def __init__(self): # 其实localstack主要还是用到了另外一个local类 # 它的一些关键的方法也被代理到了这个local类上 # 相对于local类来说,它多实现了一些和堆栈“stack”相关方法,比如push、pop之类 # 所以,我们只要直接看local代码就可以 self._local = local() ... ... @property def top(self): 返回堆栈顶部的对象 try: return self._local.stack[-1] except (attributeerror, indexerror): return none # 所以,当我们调用_request_ctx_stack.top时,其实是调用了 _request_ctx_stack._local.stack[-1] # 让我们来看看local类是怎么实现的吧,不过在这之前我们得先看一下下面出现的get_ident方法 # 首先尝试着从greenlet导入getcurrent方法,这是因为如果flask跑在了像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方法将会返回当前的协程/线程id,这对于每一个请求都是唯一的 class local(object): __slots__ = ('__storage__', '__ident_func__') def __init__(self): object.__setattr__(self, '__storage__', {}) object.__setattr__(self, '__ident_func__', get_ident) ... ... # 问题的关键就在于local类重载了__getattr__和__setattr__这两个魔法方法 def __getattr__(self, name): try: # 在这里我们返回调用了self.__ident_func__(),也就是当前的唯一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 不再是它看上去那么简单了: # 首先我们先调用get_ident方法来获取当前运行的线程/协程id # 然后获取这个id空间下的some_value属性,就像这样: # # local().some_value -> local()[current_thread_id()].some_value # # 设置属性的时候也是这个道理 通过这些分析,相信疑问二也得到了解决,通过使用了当前的线程/协程id,加上重载一些魔法 方法,flask实现了让不同工作线程都使用了自己的那一份stack对象。这样保证了request的正常 工作。 说到这里,这篇文章也差不多了。我们可以看到,为了使用者的方便,作为框架和工具的开发者 需要付出很多额外的工作,有时候,使用一些语言上的魔法是无法避免的,python在这方面也有着 相当不错的支持。 我们所需要做到的就是,学习掌握好python中那些魔法的部分,使用魔法来让自己的代码更简洁, 使用更方便。 |
随便看 |
|
在线学习网考试资料包含高考、自考、专升本考试、人事考试、公务员考试、大学生村官考试、特岗教师招聘考试、事业单位招聘考试、企业人才招聘、银行招聘、教师招聘、农村信用社招聘、各类资格证书考试等各类考试资料。