WSGI 是Web Services Gateway Interface的缩写. 如果想深入了解,可以阅读 PEP 333 文档,包含有任何你想要的:)community errata, .这篇文章将手把手教你写一个简单的WSGI例子。

注意:我用的Python版本是.2.7.x.

最经典,最简答的WSGI样当属 Hello World app.

咱们将要用到 virtualenv 去创建一个封闭的Python项目环境:

$ virtualenv wsgi-example
$ cd wsgi-example
$ source bin/activate

然后在该目录下新建一个文件: wsgi_app.py 并且添加如下的代码 :

from __future__ import print_function
 
from wsgiref.simple_server import make_server
 
 
def myapp(environ, start_response):
     response_headers = [( 'content-type' , 'text/plain' )]
     start_response( '200 OK' , response_headers)
     return [ 'Hello World' ]
 
app = myapp
 
httpd = make_server('', 8080 , app)
print ( "Starting the server on port 8080" )
httpd.serve_forever()

把项目跑起来:

$ python wsgi_app.py

之后就可以测试啦,测试有浏览器或者命令cURL两种方式,返回的应该是hello world 哦:

$ curl http://localhost:8080 -v

上面这个例子虽然清晰,但是一点都不爽啊so easy。let's high 起来。接下来我们继续往里面赛一条消息 。

修改 wsgi_app.py 文件成下面这个样纸:

from __future__ import print_function
 
from wsgiref.simple_server import make_server
from urlparse import parse_qs
 
 
def myapp(environ, start_response):
     msg = 'No Message!'
 
     response_headers = [( 'content-type' , 'text/plain' )]
     start_response( '200 OK' , response_headers)
     qs_params = parse_qs(environ.get( 'QUERY_STRING' ))
 
     if 'msg' in qs_params:
             msg = qs_params.get( 'msg' )[ 0 ]
 
     return [ 'Your message was: {}' . format (msg)]
 
app = myapp
 
httpd = make_server('', 8080 , app)
print ( "Starting the server on port 8080" )
httpd.serve_forever()

把程序跑起来,测试还是刚才那样。如果程序还在运行中,可以CTRL+C快捷键暂停并且重启。

$ curl http://localhost:8080/?msg=Hello -v

接下来,让我们继续聊中间件。你可以在这里 获得一些信息。这里我会写一个添加了HTTP 头回复的中间层例子。中间件可以做任何你能够想象的到的事情,例如session,认证等等。

中间件例子:

from __future__ import print_function
 
from wsgiref.simple_server import make_server
 
 
def myapp(environ, start_response):
 
     response_headers = [( 'content-type' , 'text/plain' )]
     start_response( '200 OK' , response_headers)
     return [ 'Check the headers!' ]
 
 
class Middleware:
     def __init__( self , app):
         self .wrapped_app = app
 
     def __call__( self , environ, start_response):
 
         def custom_start_response(status, headers, exc_info = None ):
             headers.append(( 'X-A-SIMPLE-TOKEN' , "1234567890" ))
             return start_response(status, headers, exc_info)
 
         return self .wrapped_app(environ, custom_start_response)
 
app = Middleware(myapp)
 
httpd = make_server('', 8080 , app)
print ( "Starting the server on port 8080" )
httpd.serve_forever()

访问终端:

$ curl http://localhost:8080/ -v

结果差不多应该是介个样子的:

* Connected to localhost (127.0.0.1) port 8080 (#0)
> GET / HTTP/1.1
> User-Agent: curl/7.30.0
> Host: localhost:8080
> Accept: */*
>
* HTTP 1.0, assume close after body
< HTTP/1.0 200 OK
< Date: Sat, 08 Feb 2014 00:16:00 GMT
< Server: WSGIServer/0.1 Python/2.7.5
< content-type: text/plain
< X-A-SIMPLE-TOKEN: 1234567890
< Content-Length: 18
<
* Closing connection 0


Logo

权威|前沿|技术|干货|国内首个API全生命周期开发者社区

更多推荐