Middleware 处于 server/gateway 和 application/framework 之间,对 server/gateway 来说,它相当于 application/framework;对 application/framework 来说,它相当于 server/gateway。Middleware可以实现以下功能:
1.根据 url 把用户请求调度到不同的 application 中。
2.负载均衡,转发用户请求
3.预处理 XSL 等相关数据
4.限制请求速率,设置白名单
这个图片解释了为什么flask会使用localstack来处理请求
class IPBlacklistMiddleware(object):
def __init__(self, app):
self.app = app
def __call__(self, environ, start_response):
ip_addr = environ.get('HTTP_HOST').split(':')[0]
if ip_addr not in ('127.0.0.1'):
return forbidden(start_response)
return self.app(environ, start_response)
def forbidden(start_response):
start_response('403 Forbidden', [('Content-Type', 'text/plain')])
return ['Forbidden']
def application(environ, start_response):
start_response('200 OK', [('Content-Type', 'text/plain')])
return ['This is a python application!']
if __name__ == '__main__':
from wsgiref.simple_server import make_server
application = IPBlacklistMiddleware(application)
server = make_server('0.0.0.0', 8080, application)
server.serve_forever()
https://www.cnblogs.com/-wenli/p/10884168.html