Flask是一个使用 Python 编写的轻量级 Web 应用框架。其 WSGI 工具箱采用 Werkzeug ,模板引擎则使用 Jinja2 。Flask使用 BSD 授权。Flask也被称为 “microframework” ,因为它使用简单的核心,用 extension 增加其他功能。Flask没有默认使用的数据库、窗体验证工具。Flask较其他同类型框架更为灵活、轻便、安全且容易上手。它可以很好地结合MVC模式进行开发,开发人员分工合作,小型团队在短时间内就可以完成功能丰富的中小型网站或Web服务的实现。另外,Flask还有很强的定制性,用户可以根据自己的需求来添加相应的功能,在保持核心功能简单的同时实现功能的丰富与扩展,其强大的插件库可以让用户实现个性化的网站定制,开发出功能强大的网站。
栈
先入后出
class Stack():
def __init__(self,size): #定义栈
self.size=size
self.stack=[]
self.top=-1
def push(self,x): #入栈
if self.isfull():
raise exception("stack is full")
else:
self.stack.append(x)
self.top=self.top+1 #["a"] self.top= 0 ["a","b"] self.top=1
def pop(self): #出栈
if self.isempty():
raise exception("stack is empty")
else:
self.top=self.top-1
self.stack.pop()
def isfull(self):
return self.top+1 == self.size
def isempty(self):
return self.top == '-1'
def showStack(self):
print(self.stack)
s=Stack(10)
for i in range(6):
s.push(i)
print(s.showStack())
for i in range(3):
s.pop()
print(s.showStack())
队列
class Queue():
def __init__(self,size): #队列属性
self.size=size
self.putnum =-1
self.getnum =-1
self.queue=[]
def put(self,element): #入队
if self.isfull():
raise exception("queue is full")
else:
self.queue.append(element)
self.putnum=self.putnum+1
def get(self): #出队
if self.isempty():
raise exception("queue is empty")
else:
self.queue.pop(0)
self.getnum=self.getnum+1
def isfull(self):
return self.putnum-self.getnum+1 == self.size
def isempty(self):
return self.putnum == self.getnum
def showQueue(self):
print(self.queue)
q=Queue(10)
for i in range(6):
q.put(i)
q.showQueue()
for i in range(3):
q.get()
q.showQueue()
偏函数固定参数提取属性值
from functools import partial
class HttpRequest(object): #请求信息
def __init__(self):
self.method = "GET"
self.body = b"name=abc@age=123"
def __getitem__(self, item):
return self.__dict__[item]
class Foo(object): #添加属性
def __init__(self):
self.request = HttpRequest()
self.session = {"login":True,"is_super":False}
def __getitem__(self, item):
return self.__dict__[item]
foo = Foo() #从栈中提取的上下文
def func(args):
return getattr(foo,args)
re_func = partial(func,'request') #=====>re_func():HttpRequest()
se_func = partial(func,'session') #======>se_func():{"login":True,"is_super":False}
class LocalProxy(object): #栈隔离
def __init__(self,local):
self._local = local
def _get_current_object(self):
print(self._local,self._local())
return self._local()
def __getitem__(self, item):
return getattr(self._get_current_object(),item)
request = LocalProxy(re_func)
ret = request['method']
print(ret)
session = LocalProxy(se_func) #local={"login":True,"is_super":False}
print(session._get_current_object())
request1 = HttpRequest()
print(request1["method"])
给线程分配值
import time
import threading
class A:
pass
local = A()
local = threading.local()
def func(n):
local.val = n
time.sleep(5)
print(local.val)
for i in range(10):
t = threading.Thread(target=func,args=(i,))
t.start()
如果把第6行注释掉,运行结果为 9 9 9 9 9 9 9 9 9 9
如果把第5行注释掉,运行结果为 0~9随机排列
local = A()设置为全局变量
local = threading.local()设置为单个线程的私有变量
通过栈隔离来存取栈
from threading import current_thread as getcurrent
class Local(object):
def __init__(self):
object.__setattr__(self,"_storage",{})
def __setattr__(self, key, value):
ident = getcurrent() # 定制粒度更细的
if ident in self._storage:
self._storage[ident][key] = value
else:
self._storage[ident] = {key:value}
def __getattr__(self, item):
ident = getcurrent()
return self._storage[ident][item]
class LocalStack(object):
def __init__(self):
self.local = Local()
def push(self,item):
self.local.stack = []
self.local.stack.append(item)
def pop(self):
return self.local.stack.pop()
def top(self):
return self.local.stack[-1]
_local_stack = LocalStack()
_local_stack.push(55)
print(_local_stack.top()) # 取栈顶元素
一个简单的flask框架
from wsgiref.simple_server import make_server
ViewFunctions = {}
def wapper(name):
def _wapper(f):
ViewFunctions[name] = f
return f
return _wapper
@wapper("/home")
def home():
return [b'<h1>Hello, web!</h1>']
@wapper("/favicon.ico")
def pic():
return [b'<h1>pic!</h1>']
print(ViewFunctions)
class Flask:
def __init__(self):
self.view_functions = {}
def __call__(self,environ, start_response):
key = environ['PATH_INFO']
print(key)
start_response('200 OK', [('Content-Type', 'text/html')])
return ViewFunctions[key]()
application = Flask()
httpd = make_server('', 8000, application)
# 开始监听HTTP请求:
httpd.serve_forever()