Flask 是一个微框架(Micro framework),所谓微框架,它就是很轻量级的,做者划分出了Flask应该负责什么(请求路由、处理请求、返回响应)、不该该负责什么(数据库抽象、表单验证)。它倡导地是不要重复造轮子,结合社区优秀的库,使得Flask更加灵活、定制性更强。python
先写一个简单的Flask应用(main.py)shell
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return 'Hello World'
app.run("127.0.0.1", 80, debug=True)
复制代码
执行测试数据库
> python main.py
> curl http://127.0.0.1:80
Hello World
复制代码
查看一下app.run()
函数源码flask
def run(self, host=None, port=None, debug=None, load_dotenv=True, **options):
...
from werkzeug.serving import run_simple
try:
run_simple(host, port, self, **options)
finally:
self._got_first_request = False
复制代码
核心逻辑是执行run_simple
函数,而且第三个参数self
是Flask对象安全
看一下Flask
类的实现bash
class Flask:
def wsgi_app(self, environ, start_response):
# 将请求信息包装为一个ctx对象
ctx = self.request_context(environ)
error = None
try:
try:
# ctx压栈
ctx.push()
# 分发 处理
response = self.full_dispatch_request()
except Exception as e:
error = e
response = self.handle_exception(e)
except: # noqa: B001
error = sys.exc_info()[1]
raise
return response(environ, start_response)
finally:
if self.should_ignore_error(error):
error = None
# ctx 出栈
ctx.auto_pop(error)
def __call__(self, environ, start_response):
return self.wsgi_app(environ, start_response)
复制代码
当请求到来时,程序在调用app时,因为实现了__call__
函数,则经过该函数调用了wsgi_app()
函数markdown
具体分析wsgi_app函数:多线程
Local
类是用werkzeug
库实现的一个用于类存储数据的类,它支持多线程安全存储。app
使用__storage__
(dict类型)存储数据,可是经过获取到的线程id做为标识来进行隔离,让每一个线程读写本身线程的数据 __storage__
的结构是这样的框架
{
"线程id1": {"stack": [ctx,]},
"线程id2": {"stack": []},
}
复制代码
实际源码
from thread import get_ident
class Local(object):
__slots__ = ("__storage__", "__ident_func__")
def __init__(self):
object.__setattr__(self, "__storage__", {})
object.__setattr__(self, "__ident_func__", get_ident)
def __getattr__(self, name):
# 重写了该方法,首先获取当前线程id,而后去读取该线程id下的数据
try:
return self.__storage__[self.__ident_func__()][name]
except KeyError:
raise AttributeError(name)
def __setattr__(self, name, value):
# 重写了该方法,首先获取当前线程id,而后去写入该线程id下的数据
ident = self.__ident_func__()
storage = self.__storage__
try:
storage[ident][name] = value
except KeyError:
storage[ident] = {name: value}
def __delattr__(self, name):
# 重写了该方法,首先获取当前线程id,而后去删除该线程id下的数据
try:
del self.__storage__[self.__ident_func__()][name]
except KeyError:
raise AttributeError(name)
复制代码
LocalStack
是基于Local
类实现的栈类,因此它支持线程安全。 实际源码
class LocalStack(object):
def __init__(self):
self._local = Local()
def push(self, obj):
"""Pushes a new item to the stack"""
rv = getattr(self._local, "stack", None)
if rv is None:
self._local.stack = rv = []
rv.append(obj)
return rv
def pop(self):
"""Removes the topmost item from the stack, will return the old value or `None` if the stack was already empty. """
stack = getattr(self._local, "stack", None)
if stack is None:
return None
elif len(stack) == 1:
release_local(self._local)
return stack[-1]
else:
return stack.pop()
@property
def top(self):
try:
return self._local.stack[-1]
except (AttributeError, IndexError):
return None
复制代码