1. WSGI Server <-----> WSGI Middleware<-----> WSGI Application 

1.1 WSGI Server

  wsgi server可以理解为一个符合wsgi规范的web server,接收request请求,封装一系列环境变量,按照wsgi规范调用注册的wsgi app,最后将response返回给客户端。

1.2 WSGI Application

wsgi application就是一个普通的callable对象,当有请求到来时,wsgi server会调用这个wsgi application。

   这个对象接收两个参数,通常为environ,start_response。

   environ可以理解为环境变量,跟一次请求相关的所有信息都保存在了这个环境变量中,包括服务器信息,客户端信息,请求信息。

   start_response是一个callback函数,wsgi application通过调用start_response,将response headers/status 返回给wsgi server。

   此外这个wsgi application会return一个iterator对象 ,这个iterator就是response body。

1.3 WSGI Middleware

  中间件是为了使应用程序拥有额外的行为而存在的。如果你不能随意决定是否将它放到程序的前面,它就不再是中间件了。而是程序的一部分。

  比如:URL dispatch功能,权限判断。

1.4 WSGI模型示例
 
from wsgiref.simple_server import make_server

URL_PATTERNS= (
('hi/','say_hi'),
('hello/','say_hello'),
) class Dispatcher(object): def _match(self,path):
path = path.split('/')[1]
for url,app in URL_PATTERNS:
if path in url:
return app def __call__(self,environ, start_response):
path = environ.get('PATH_INFO','/')
app = self._match(path)
if app :
app = globals()[app]
return app(environ, start_response)
else:
start_response("404 NOT FOUND",[('Content-type', 'text/plain')])
return ["Page dose not exists!"] def say_hi(environ, start_response):
start_response("200 OK",[('Content-type', 'text/html')])
return ["kenshin say hi to you!"] def say_hello(environ, start_response):
start_response("200 OK",[('Content-type', 'text/html')])
return ["kenshin say hello to you!"] app = Dispatcher() httpd = make_server('', 8000, app)
print "Serving on port 8000..."
httpd.serve_forever()

2.WebOb

  WebOb是一个用于对WSGI Request环境进行包装,以及用于创建WSGI Response的一个包。

  WebOb把WSGI的几个参数、返回的方法都封装成了Reqeust、Response这两个对象,同时还提供了一个使用方便的Exception对象。

  Related API Link: http://docs.webob.org/en/latest/reference.html

2.1 Request

from webob import Request

req = Request.blank('/')

def wsgi_app(environ, start_response):
start_response('200 OK', [('Content-type', 'text/plain')])
return ['Hi!'] print req.call_application(wsgi_app)

2.2 Response

from webob import Response
from pprint import pprint
res = Response(content_type='text/plain', charset=None)
f = res.body_file
f.write('hey')
f.write('test') # pprint(res.status)
# pprint(res.headerlist)
# pprint(res.body)

2.3 Full Sample about Request and Response

from webob import Request
from webob import Response
from webob.dec import wsgify # @wsgify
def my_app(environ, start_response):
req = Request(environ)
res = Response()
res.content_type = 'text/plain'
parts = []
for name, value in sorted(req.environ.items()):
parts.append('%s: %r' % (name, value))
res.body = 'n'.join(parts)
return res(environ, start_response) req = Request.blank('/')
res = req.get_response(my_app)
print res

2.4 Exception

  下述总结了WebOb对于HTTP返回码的类定义。

Exception
HTTPException
HTTPOk
* - :class:`HTTPOk`
* - :class:`HTTPCreated`
* - :class:`HTTPAccepted`
* - :class:`HTTPNonAuthoritativeInformation`
* - :class:`HTTPNoContent`
* - :class:`HTTPResetContent`
* - :class:`HTTPPartialContent`
HTTPRedirection
* - :class:`HTTPMultipleChoices`
* - :class:`HTTPMovedPermanently`
* - :class:`HTTPFound`
* - :class:`HTTPSeeOther`
* - :class:`HTTPNotModified`
* - :class:`HTTPUseProxy`
* - :class:`HTTPTemporaryRedirect`
HTTPError
HTTPClientError
* - :class:`HTTPBadRequest`
* - :class:`HTTPUnauthorized`
* - :class:`HTTPPaymentRequired`
* - :class:`HTTPForbidden`
* - :class:`HTTPNotFound`
* - :class:`HTTPMethodNotAllowed`
* - :class:`HTTPNotAcceptable`
* - :class:`HTTPProxyAuthenticationRequired`
* - :class:`HTTPRequestTimeout`
* - :class:`HTTPConflict`
* - :class:`HTTPGone`
* - :class:`HTTPLengthRequired`
* - :class:`HTTPPreconditionFailed`
* - :class:`HTTPRequestEntityTooLarge`
* - :class:`HTTPRequestURITooLong`
* - :class:`HTTPUnsupportedMediaType`
* - :class:`HTTPRequestRangeNotSatisfiable`
* - :class:`HTTPExpectationFailed`
* - :class:`HTTPUnprocessableEntity`
* - :class:`HTTPLocked`
* - :class:`HTTPFailedDependency`
* - :class:`HTTPPreconditionRequired`
* - :class:`HTTPTooManyRequests`
* - :class:`HTTPRequestHeaderFieldsTooLarge`
* - :class:`HTTPUnavailableForLegalReasons`
HTTPServerError
* - :class:`HTTPInternalServerError`
* - :class:`HTTPNotImplemented`
* - :class:`HTTPBadGateway`
* - :class:`HTTPServiceUnavailable`
* - :class:`HTTPGatewayTimeout`
* - :class:`HTTPVersionNotSupported`
* - :class:`HTTPNetworkAuthenticationRequired`

WSGI学习系列WebOb的更多相关文章

  1. WSGI学习系列Paste

    Paste has been under development for a while, and has lots of code in it. The code is largely decoup ...

  2. WSGI学习系列WSME

    Introduction Web Services Made Easy (WSME) simplifies the writing of REST web services by providing ...

  3. WSGI学习系列Pecan

    Pecan Introduce Pecan是一个轻量级的基于Python的Web框架, Pecan的目标并不是要成为一个“full stack”的框架, 因此Pecan本身不支持类似Session和D ...

  4. WSGI学习系列多种方式创建WebServer

    def application(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) ...

  5. WSGI学习系列eventlet.wsgi

    WSGI是Web Service Gateway Interface的缩写. WSGI标准在PEP(Python Enhancement Proposal)中定义并被许多框架实现,其中包括现广泛使用的 ...

  6. 分布式学习系列【dubbo入门实践】

    分布式学习系列[dubbo入门实践] dubbo架构 组成部分:provider,consumer,registry,monitor: provider,consumer注册,订阅类似于消息队列的注册 ...

  7. Entity Framework Code First学习系列目录

    Entity Framework Code First学习系列说明:开发环境为Visual Studio 2010 + Entity Framework 5.0+MS SQL Server 2012, ...

  8. WCF学习系列汇总

    最近在学习WCF,打算把一整个系列的文章都”写“出来,包括理论和实践,这里的“写”是翻译,是国外的大牛写好的,我只是搬运工外加翻译.翻译的不好,大家请指正,谢谢了.如果觉得不错的话,也可以给我点赞,这 ...

  9. EF(Entity Framework)系统学习系列

    好久没写博客了,继续开启霸屏模式,好了,废话不多说,这次准备重新系统学一下EF,一个偶然的机会找到了一个学习EF的网站(http://www.entityframeworktutorial.net/) ...

随机推荐

  1. 2018.08.28 洛谷P3803 【模板】多项式乘法(FFT)

    传送门 fft模板题. 终于学会fft了. 这个方法真是神奇! 经过试验发现手写的complex快得多啊! 代码: #include<iostream> #include<cstdi ...

  2. git将本地仓库强制替换掉远程仓库

    $ git remote add origin <url> $ git push --force --set-upstream origin master

  3. java浅拷贝和深拷贝

    转:http://blog.csdn.net/u014727260/article/details/55003402 实现clone的2点: 1,clone方法是Object类的一个方法,所以任何一个 ...

  4. NSUserDefaults 简介,使用 NSUserDefaults 存储自定义对象 - lady-奕奕的个人空间 - 开源中国社区

    一.了解NSUserDefaults以及它可以直接存储的类型 NSUserDefaults是一个,在整个程序中只有一个实例对象,他可以用于数据的永久保存,而且简单实用,这是它可以让数据自由传递的一个前 ...

  5. codeforces 702C Cellular Network 2016-10-15 18:19 104人阅读 评论(0) 收藏

    C. Cellular Network time limit per test 3 seconds memory limit per test 256 megabytes input standard ...

  6. hdu 4983 欧拉函数

    http://acm.hdu.edu.cn/showproblem.php?pid=4983 求有多少对元组满足题目中的公式. 对于K=1的情况,等价于gcd(A, N) * gcd(B, N) = ...

  7. delphi 安卓程序如何读取外部配置文件

    1)编辑一个config.txt文件,填写配置系统. 2)有外部加载文件时,安卓发布需要另行指定文件发布目录位置 比如加载config.txt需要在 首先利用Project->Deploymen ...

  8. Python学习-20.Python的Urllib模块

    除了 Http 模块可以模拟 Http 请求外,使用 Urllib 模块也是可以模拟 Http 请求的,只不过功能相对弱一点. import urllib.request opener = urlli ...

  9. Mono For Android 之 配置环境

    下载 Xamarin Mono For Android 4.6.07004 完整离线破解版 (包括除 Android SDK 外的所有文件) Android SDK. 资源源自 http://www. ...

  10. Eclipse 4.2 failed to start after TEE is installed

    ---------------  VM Arguments---------------  jvm_args: -Dosgi.requiredJavaVersion=1.6 -Dhelp.lucene ...