通过PasteDeploy+Webob来配置WSGI服务器接口
Webob是一种封装了HTTP协议的模块,具体课参考官方文档,不过这两天不知为什么不能访问,我是直接下载的源代码,源代码下docs自带本地文档,可以通过sphnix-builder的命令来生成本地文档
测试了两种方案
一种是不使用Webob装饰器的方式
一种是使用Webob装饰器的方式
配置文件如下test-deploy.ini
[DEFAULT]
key1=value1
key2=value2
key3=values
[composite:main]
use=egg:Paste#urlmap
/=show
/auther=auther
/version=version
[pipeline:show]
pipeline = auth root
[pipeline:version]
pipeline = logrequest showversion
[pipeline:auther]
pipeline = logrequest showauther
[filter:logrequest]
username = root
password = 123
paste.filter_factory = test.testdeploy:log_factory
[app:showversion]
version = 1.0.0
paste.app_factory = test.testdeploy:version_factory
[app:showauther]
auther = bluefire1991
paste.app_factory = test.testdeploy:showauther_factory
[app:root]
paste.app_factory = test.testdeploy:show_factory
[filter:auth]
paste.filter_factory = test.testdeploy:filter_factory
配置方案用的类似openstack实现的配置方案,paste.xxx_factory和pipeline的方式实现配置,不过路径的配置openstack源代码实现的是用Routes实现RESTful的功能,这里没有用Routes直接在ini文件下配置的路径。为什么这样配置可以参考我的上一篇博客。
代码文件testdeploy.py
'''
Created on 2013-10-28
@author: root
'''
import logging
import os
import sys
import webob
from webob import Request
from webob import Response
from webob.dec import *
from webob.exc import *
from paste.deploy import loadapp
from wsgiref.simple_server import make_server
import signal
def sigint_handler(signal, frame):
"""Exits at SIGINT signal."""
logging.debug('SIGINT received, stopping servers.')
sys.exit(0)
#用于封装app
@wsgify
def test(request):
return Response('Here!')
#用于封装app
@wsgify
def application(request):
return Response('Hello and Welcome!')
#wsgify.middleware用于wsgi的对外filter层,必须要两个参数,request对象和app对象,app用于向下一个filter或者app传递参数
@wsgify.middleware
def auth_filter(request, app):
if request.headers.get('X-Auth-Token') != 'bluefire1991':
#类似于在这里写了start_response和return函数,只不过这里由webob的Request对象封装好了,本来test是一个函数对象,调用需要test(req),
#通过装饰器@wsgi直接变成一个对象,参数在装饰器内部实现wsgify(test)
return test
return app(request)
#app_factory
def show_factory(global_conf,**local_conf):
return application
#app_factory
def version_factory(global_conf,**local_conf):
return ShowVersion(global_conf,local_conf)
#app_fatory
def showauther_factory(global_conf,**local_conf):
return ShowAuther(global_conf,local_conf)
#filter_factory
def filter_factory(global_conf, **local_conf):
return auth_filter
#filter_factory
def log_factory(global_conf,**local_conf):
def filter(app):
return LogFilter(app,global_conf,local_conf)
return filter
class LogFilter():
def __init__(self,app,global_conf,local_conf):
self.app = app
self.global_conf=global_conf
self.local_conf=local_conf
def __call__(self,environ,start_response):
print "filter:LogFilt