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 ...
随机推荐
- 在ubuntu纯字符gdb界面下来开发调试嵌入式ARM
前面一个帖子介绍了使用eclipse来开发STM32的固件,但有的时候使用Eclipse的GDB调试器会崩溃掉,反复这样造成我们开发的效率降低,信心也会受一打击. 最近接触到的许多源码,就是在linu ...
- 通过js实现在页面中添加音乐
代码如下!兼容IE // JavaScript Document function autoPlay(){//自动播放 var myAuto = document.getElementById('my ...
- shell脚本中执行另一个shell脚本
分类: 可以在一个shell脚本中执行另一个shell脚本(或非可执行文件,主要用于取得一些变量的值),方法是: . 文件名(包括路径) 或 变量=文件名(包括路径) . $变量 注意,圆点后面有 ...
- EntityFramework中支持BulkInsert扩展
EntityFramework中支持BulkInsert扩展 本文为 Dennis Gao 原创技术文章,发表于博客园博客,未经作者本人允许禁止任何形式的转载. 前言 很显然,你应该不至于使用 Ent ...
- C#外挂QQ
C#外挂QQ找茬辅助源码,早期开发 这是一款几年前开发的工具,当年作为一民IT纯屌,为了当年自己心目中的一位女神熬夜开发完成.女神使用后找茬等级瞬间从眼明手快升级为三只眼...每次看到这个就会想起 ...
- Bootstrap相关优质项目推荐
Bootstrap 编码规范by @mdo Bootstrap 编码规范:编写灵活.稳定.高质量的 HTML 和 CSS 代码的规范. jQuery API 中文手册 根据最新的 jQuery 1.1 ...
- [转]Getting a Packet Trace
src:https://developer.apple.com/library/mac/qa/qa1176/_index.html Technical Q&A QA1176 Getting a ...
- BEncoding的编码与解码
BEncoding的编码与解码 1. BEncoding规则 BEncoding是BitTorrent用在传输数据结构的编码方式,我们最熟悉的“种子”文件,它里面的元数据就是 BEncoding ...
- ios学习之常见问题记录
使用Core Data的好处和缺点? 首先这是apple官方极力推荐的,使用它而不是SQLite.好处有大概这么几点:1.减少你model层的代码量,减少50%-70%.无需测试和优化.2.提供了内存 ...
- svn签出单个文件
) { return new string[]{ string.Format("cd /d \"{0}\"",System.IO.Path.GetDirecto ...