Python_web框架解析
这一阵正在学习廖雪峰老师的实战课程,这里对其中web.py框架进行一些分析,总结一下学到的东西。
这一部分的课程网站:http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/0014023080708565bc89d6ab886481fb25a16cdc3b773f0000
近期学习了廖雪峰老师Python教程实战课程中WebApp博客的编写,这个项目最核心的部分就是web框架的编写。在这里总结一下学到的东西。


def get(path):
def _decorator(func):
func.__web_route__ = path
func.__web_method__ = 'GET'
return func
return _decorator
def post(path):
def _decorator(func):
func.__web_route__ = path
func.__web_method__ = 'POST'
return func
return _decorator
def view(path):
def _decorator(func):
@functools.wraps(func)
def _wrapper(*args, **kw):
r = func(*args, **kw) #这时函数原本应该返回的值,应当为字典类型。
if isinstance(r, dict):
logging.info('return Template')
return Template(path, **r) #得到self.template_name 和 self.model。
raise ValueError('Expect return a dict when using @view() decorator.')
return _wrapper
return _decorator
def interceptor(pattern='/'):
def _decorator(func):
#简单来说就是:给func添加了一个__interceptor__属性,这一属性并非一个单纯的值,
# 而是一个可调用的函数,这个函数使用时:
# func.__interceptor__(ctx.request.path_info)
# 根据ctx.request.path_info判断返回True或者False,从而决定拦截函数是否运行-->看2.
func.__interceptor__ = _build_pattern_fn(pattern)
return func
return _decorator
根据ctx.request.path_info判断返回True或者False,从而决定拦截函数是否运行;def _build_interceptor_fn(func, next):
def _wrapper():
if func.__interceptor__(ctx.request.path_info):
#如果上面为True,那么启动拦截函数
return func(next)
else:
#否则直接运行原函数
return next()
return _wrapper
class Route(object):
'''
A Route object is a callable object.
'''
def __init__(self, func):
self.path = func.__web_route__
self.method = func.__web_method__
self.is_static = _re_route.search(self.path) is None
if not self.is_static:
self.route = re.compile(_build_regex(self.path))
self.func = func
def match(self, url):
m = self.route.match(url)
if m:
return m.groups()
return None
def __call__(self, *args):
return self.func(*args)
def __str__(self):
if self.is_static:
return 'Route(static,%s,path=%s)' % (self.method, self.path)
return 'Route(dynamic,%s,path=%s)' % (self.method, self.path)
__repr__ = __str__
class Request(object):
'''
Request object for obtaining all http request information.
'''
def __init__(self, environ):
self._environ = environ
def _parse_input(self):
def _convert(item):
if isinstance(item, list):
return [_to_unicode(i.value) for i in item]
if item.filename:
return MultipartFile(item)
return _to_unicode(item.value)
#将self._environ['wsgi.input']转换成字典类型
fs = cgi.FieldStorage(fp=self._environ['wsgi.input'], environ=self._environ, keep_blank_values=True)
inputs = dict()
for key in fs:
inputs[key] = _convert(fs[key])
return inputs
def _get_raw_input(self):
'''
Get raw input as dict containing values as unicode, list or MultipartFile.
'''
if not hasattr(self, '_raw_input'):
#将上面的结果放到_raw_input属性中
self._raw_input = self._parse_input()
return self._raw_input
def input(self, **kw):
#复制上边得到的表单字典
copy = Dict(**kw)
raw = self._get_raw_input()
for k, v in raw.iteritems():
copy[k] = v[0] if isinstance(v, list) else v
return copy
def get_body(self):
#得到environ['wsgi.input']原始的数据
fp = self._environ['wsgi.input']
return fp.read()
@property
def remote_addr(self):
return self._environ.get('REMOTE_ADDR', '0.0.0.0')
def _get_cookies(self):
if not hasattr(self, '_cookies'):
cookies = {}
cookie_str = self._environ.get('HTTP_COOKIE')
if cookie_str:
for c in cookie_str.split(';'):
pos = c.find('=')
if pos>0:
cookies[c[:pos].strip()] = _unquote(c[pos+1:])
self._cookies = cookies
return self._cookies
@property
def cookies(self): return Dict(**self._get_cookies())
def cookie(self, name, default=None): return self._get_cookies().get(name, default)
class Response(object):
def __init__(self):
self._status = '200 OK'
self._headers = {'CONTENT-TYPE': 'text/html; charset=utf-8'}
class WSGIApplication(object):
#初始化时创建后面要用到的属性
def __init__(self, document_root=None, **kw):
'''
Init a WSGIApplication.
Args:
document_root: document root path.
''' self._running = False
self._document_root = document_root
self._interceptors = []
self._template_engine = None
self._get_static = {}
self._post_static = {}
self._get_dynamic = []
self._post_dynamic = [] #用来查看服务器是否正在运行
def _check_not_running(self):
if self._running:
raise RuntimeError('Cannot modify WSGIApplication when running.')
#添加模板
@property
def template_engine(self):
return self._template_engine
@template_engine.setter
def template_engine(self, engine):
self._check_not_running()
self._template_engine = engine #add_module()和add_url()用来将urls.py中的函数注册到服务器中
def add_module(self, mod):
self._check_not_running()
m = mod if type(mod)==types.ModuleType else _load_module(mod)
logging.info('Add module: %s' % m.__name__)
for name in dir(m):
fn = getattr(m, name)
if callable(fn) and hasattr(fn, '__web_route__') and hasattr(fn, '__web_method__'):
self.add_url(fn)
def add_url(self, func):
self._check_not_running()
route = Route(func)
if route.is_static:
if route.method=='GET':
self._get_static[route.path] = route
if route.method=='POST':
self._post_static[route.path] = route
else:
if route.method=='GET':
self._get_dynamic.append(route)
if route.method=='POST':
self._post_dynamic.append(route)
logging.info('Add route: %s' % str(route)) #添加拦截函数
def add_interceptor(self, func):
self._check_not_running()
self._interceptors.append(func)
logging.info('Add interceptor: %s' % str(func)) #运行服务器
def run(self, port=9000, host='127.0.0.1'):
from wsgiref.simple_server import make_server
logging.info('application (%s) will start at %s:%s...' % (self._document_root, host, port))
#httpd = make_server('', 8000, hello_world_app) 其中self.get_wsgi_application(debug=True)便是代替hello_world_app,
#这个是一个函数对象wsgi, 可以被调用
server = make_server(host, port, self.get_wsgi_application(debug=True))
server.serve_forever()
#这时这个应用中的核心
#返回值wsgi是一个函数对象,而不是一个确定值,主要是为了上面的调用
def get_wsgi_application(self, debug=False):
self._check_not_running()
if debug:
self._get_dynamic.append(StaticFileRoute())
self._running = True
_application = Dict(document_root=self._document_root) #这个函数的作用就是将注册的函数和请求的路径联系起来
def fn_route():
request_method = ctx.request.request_method
path_info = ctx.request.path_info
if request_method=='GET':
fn = self._get_static.get(path_info, None)
if fn:
#静态路径的话就可以直接调用函数:
return fn()
for fn in self._get_dynamic:
#如果是动态的路径,那么将其中的动态部分提取出来作为函数的参数:
args = fn.match(path_info)
if args:
return fn(*args)
raise notfound()
if request_method=='POST':
fn = self._post_static.get(path_info, None)
if fn:
return fn()
for fn in self._post_dynamic:
args = fn.match(path_info)
if args:
return fn(*args)
raise notfound()
raise badrequest() #添加拦截函数
fn_exec = _build_interceptor_chain(fn_route, *self._interceptors) #wsgi就是应用程序了,其中的两个参数在wsgiref中会提供的:
def wsgi(env, start_response): #将Request和Response实例化成为ctx的属性
ctx.application = _application
ctx.request = Request(env)
response = ctx.response = Response() try: r = fn_exec()
#正常情况下r是被包裹的函数返回的填入返回值的模板
if isinstance(r, Template):
r = self._template_engine(r.template_name, r.model)
if isinstance(r, unicode):
r = r.encode('utf-8')
if r is None:
r = []
start_response(response.status, response.headers)
return r
#处理各种错误
except RedirectError, e:
response.set_header('Location', e.location)
start_response(e.status, response.headers)
return []
except HttpError, e:
start_response(e.status, response.headers)
return ['<html><body><h1>', e.status, '</h1></body></html>']
except Exception, e:
logging.exception(e)
if not debug:
start_response('500 Internal Server Error', [])
return ['<html><body><h1>500 Internal Server Error</h1></body></html>']
exc_type, exc_value, exc_traceback = sys.exc_info()
fp = StringIO()
traceback.print_exception(exc_type, exc_value, exc_traceback, file=fp)
stacks = fp.getvalue()
fp.close()
start_response('500 Internal Server Error', [])
return [
r'''<html><body><h1>500 Internal Server Error</h1><div style="font-family:Monaco, Menlo, Consolas, 'Courier New', monospace;"><pre>''',
stacks.replace('<', '<').replace('>', '>'),
'</pre></div></body></html>']
#请求结束后将线程的各个属性删除
finally:
del ctx.application
del ctx.request
del ctx.response
return wsgi
Python_web框架解析的更多相关文章
- [转载]iOS 10 UserNotifications 框架解析
活久见的重构 - iOS 10 UserNotifications 框架解析 TL;DR iOS 10 中以前杂乱的和通知相关的 API 都被统一了,现在开发者可以使用独立的 UserNotifica ...
- ABP使用及框架解析系列 - [Unit of Work part.1-概念及使用]
前言 ABP ABP是“ASP.NET Boilerplate Project”的简称. ABP的官方网站:http://www.aspnetboilerplate.com ABP在Github上的开 ...
- ABP使用及框架解析系列 - [Unit of Work part.2-框架实现]
前言 ABP ABP是“ASP.NET Boilerplate Project”的简称. ABP的官方网站:http://www.aspnetboilerplate.com ABP在Github上的开 ...
- iOS 10 UserNotifications 框架解析
摘自:https://onevcat.com/2016/08/notification/ iOS 10 中以前杂乱的和通知相关的 API 都被统一了,现在开发者可以使用独立的 UserNotifica ...
- Poco::TCPServer框架解析
Poco::TCPServer框架解析 POCO C++ Libraries提供一套 C++ 的类库用以开发基于网络的可移植的应用程序,功能涉及线程.文件.流,网络协议包括:HTTP.FTP.SMTP ...
- Scrapy爬虫框架解析
Scrapy框架解析 Scrapy框架大致包括以下几个组件:Scrapy Engine.Spiders.Scheduler.Item Pipeline.Downloader: 组件 Scrapy En ...
- 使用 STHTTPRequest 框架解析 Soap1.2 教程
1.STHTTPRequest框架地址 https://github.com/nst/STHTTPRequest 将 STHTTPRequest .h STHTTPRequest.m 文件拖入工程中 ...
- Sword框架解析——知识采集流程页面初始化
Sword框架解析——知识采集流程页面初始化 Sword框架解析知识采集流程页面初始化 问题解答流程采集新增页面初始化 1后台t_xt_gnzy表和BLH类 2BLH类的写法前台目录树代码 3登录系统 ...
- iScroll框架解析——Android 设备页面内 div(容器,非页面)overflow:scroll; 失效解决(转)
移动平台的活,兼容问题超多,今儿又遇到一个.客户要求在弹出层容器内显示内容,但内容条数过多,容器显示滚动条.按说是So easy,容器设死宽.高,CSS加属性 overflow:scroll; -we ...
随机推荐
- Ajax实现在textbox中输入内容,动态从数据库中模糊查询显示到下拉框中
功能:在textbox中输入内容,动态从数据库模糊查询显示到下拉框中,以供选择 1.建立一aspx页面,html代码 <HTML> <HEAD> <title>We ...
- SSMS2008插件开发(2)--Microsoft Visual Studio 2008插件开发介绍
原文:SSMS2008插件开发(2)--Microsoft Visual Studio 2008插件开发介绍 由于开发SSMS2008插件是通过VS2008进行的,有必要先介绍一下VS2008的插件开 ...
- wpa_cli P2P 连接相关的调试命令
在最近的一次客户端上的调试p2p的wifi display, 他们中的一半Android该调整了,整个前所以没有太多的研究p2p过程连接, 客户现在使用的非Android平台架构. 需要协助客户这么多 ...
- bootstrap弹出框
要想使用Bootstrap Popover(弹出框)则必须引入其依赖的文件: jquery.js这个必须的(还是要写在其他js前面,bootstrap是依赖jquery的哦) bootstrap-to ...
- .NET面试问答集锦
程序员级别鉴定书(.NET面试问答集锦) 提供避免元素命名冲突的方法 DOM适合的使用场景是什么?是否有尺寸限制? DOM是一种与浏览器,平台,语言无关的接口,使你可以访问页面其他的标准组件. DOM ...
- poj3519 Lucky Coins Sequence矩阵快速幂
Lucky Coins Sequence Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others ...
- ASP.NET MVC 中的视图生成
关于 ASP.NET MVC 中的视图生成 在 ASP.NET MVC 中,我们将前端的呈现划分为三个独立的部分来实现,Controller 用来控制用户的操作,View 用来控制呈现的内容,Mode ...
- Slithice 分布式架构设计
项目原因: 参与过各种 分布式项目,有 Socket,Remoting,WCF,当然还有最常用的可以跨平台的 WebService. 分布式编码的时间浪费: 但是,无一例外的,开发分布式程序的开发遵循 ...
- 学习SQL关联查询
通过一个小问题来学习SQL关联查询 原话题: 是关于一个left join的,没有技术难度,但不想清楚不一定能回答出正确答案来: TabA表有三个字段Id,Col1,Col2 且里面有一条数据1,1, ...
- 更好的抽屉效果(ios)
昨天项目基本没啥事了,晚上早早的就回家了,躺在床上无聊地玩着手机(Android的),在清理系统垃圾时被一个“360手机助手”给吸引了, 其实我是被它的那个抽屉效果给吸引了,此时你也许会觉得我out了 ...