前几天写了 浅谈cgi、wsgi、uwsgi 与 uWSGI 等一些 python web 开发中遇到的一些名词的理解,今天博主就根据 wsgi 标准实现一个 web server,并尝试用它来跑 Django、tornado 框架的 app。
在实现 wsgi server 之前我们先要做一些准备工作。首先,http server 使用 http 协议,而 http 协议封装在 tcp 协议中,所以要建立一个 http server 我们先要建立一个 tcp server。要使用 tcp 协议我们不可能自己实现一个,现在比较流行的解决方案就是使用 socket 套接字编程, socket 已经帮我们实现了 tcp 协议的细节,我们可以直接拿来使用不用关心细节。 socket 编程是语言无关的,不管是以前博主用 MFC 写聊天室还是用 C# 写网络延迟计算还是现在写 http server,它的使用流程都是一样的:
而 client 不需要我们自己实现,我们的浏览器就是一个 client ,现在运行python server.py,然后在浏览器中打开 localhost:8888即可看到浏览器中显示 hello world!,这么快就实现了一个 http server 有木有 hin 激动!
然而想要 Django 这类框架的 app 在我们写的 http server 中运行起来还远远不够,现在我们就需要引入 wsgi 规范,根据这个规范我们就可以让自己的 server 也能运行这些框架的 app啦。
嗯,就是一篇很长的英语阅读理解,大概意思就是如果你想让你的服务器和应用程序一起好好工作,你要遵循这个标准来写你的 web app 和 web server:
这样一个标准的 wsgi app 就写好了,虽然这看上去和我们写的 Django app、 tornado app 大相径庭,但实际上这些 app 都会经过相应的处理来适配 wsgi 标准,这个之后会详谈。
# server.py
# coding: utf-8
from __future__ import unicode_literals
import socket
import StringIO
import sys
import datetime
class
WSGIServer
(
object
)
:
socket_family
=
socket
.
AF_INET
socket_type
=
socket
.
SOCK_STREAM
request_queue_size
=
10
def __init__
(
self
,
address
)
:
self
.
socket
=
socket
.
socket
(
self
.
socket_family
,
self
.
socket_type
)
self
.
socket
.
setsockopt
(
socket
.
SOL_SOCKET
,
socket
.
SO_REUSEADDR
,
1
)
self
.
socket
.
bind
(
address
)
self
.
socket
.
listen
(
self
.
request_queue_size
)
host
,
port
=
self
.
socket
.
getsockname
()[
:
2
]
self
.
host
=
host
self
.
port
=
port
def set_application
(
self
,
application
)
:
self
.
application
=
application
def serve_forever
(
self
)
:
while
1
:
self
.
connection
,
client_address
=
self
.
socket
.
accept
()
self
.
handle_request
()
def handle_request
(
self
)
:
self
.
request_data
=
self
.
connection
.
recv
(
1024
)
self
.
request_lines
=
self
.
request_data
.
splitlines
()
try
:
self
.
get_url_parameter
()
env
=
self
.
get_environ
()
app_data
=
self
.
application
(
env
,
self
.
start_response
)
self
.
finish_response
(
app_data
)
print
'[{0}] "{1}" {2}'
.
format
(
datetime
.
datetime
.
now
().
strftime
(
'%Y-%m-%d %H:%M:%S'
),
self
.
request_lines
[
0
],
self
.
status
)
except
Exception
,
e
:
pass
def get_url_parameter
(
self
)
:
self
.
request_dict
=
{
'Path'
:
self
.
request_lines
[
0
]}
for
itm
in
self
.
request_lines
[
1
:
]
:
if
':'
in
itm
:
self
.
request_dict
[
itm
.
split
(
':'
)[
0
]]
=
itm
.
split
(
':'
)[
1
]
self
.
request_method
,
self
.
path
,
self
.
request_version
=
self
.
request_dict
.
get
(
'Path'
).
split
()
def get_environ
(
self
)
:
env
=
{
'wsgi.version'
:
(
1
,
0
),
'wsgi.url_scheme'
:
'http'
,
'wsgi.input'
:
StringIO
.
StringIO
(
self
.
request_data
),
'wsgi.errors'
:
sys
.
stderr
,
'wsgi.multithread'
:
False
,
'wsgi.multiprocess'
:
False
,
'wsgi.run_once'
:
False
,
'REQUEST_METHOD'
:
self
.
request_method
,
'PATH_INFO'
:
self
.
path
,
'SERVER_NAME'
:
self
.
host
,
'SERVER_PORT'
:
self
.
port
,
'USER_AGENT'
:
self
.
request_dict
.
get
(
'User-Agent'
)
}
return
env
def start_response
(
self
,
status
,
response_headers
)
:
headers
=
[
(
'Date'
,
datetime
.
datetime
.
now
().
strftime
(
'%a, %d %b %Y %H:%M:%S GMT'
)),
(
'Server'
,
'RAPOWSGI0.1'
),
]
self
.
headers
=
response_headers
+
headers
self
.
status
=
status
def finish_response
(
self
,
app_data
)
:
try
:
response
=
'HTTP/1.1 {status}rn'
.
format
(
status
=
self
.
status
)
for
header
in
self
.
headers
:
response
+=
'{0}: {1}rn'
.
format
(
*
header
)
response
+=
'rn'
for
data
in
app_data
:
response
+=
data
self
.
connection
.
sendall
(
response
)
finally
:
self
.
connection
.
close
()
if
__name__
==
'__main__'
:
port
=
8888
if
len
(
sys
.
argv
)
2
:
port
=
sys
.
argv
[
2
]
def generate_server
(
address
,
application
)
:
server
=
WSGIServer
(
address
)
server
.
set_application
(
TestMiddle
(
application
))
return
server
app_path
=
sys
.
argv
[
1
]
module
,
application
=
app_path
.
split
(
'.'
)
module
=
__import__
(
module
)
application
=
getattr
(
module
,
application
)
httpd
=
generate_server
((
''
,
int
(
port
)),
application
)
print
'RAPOWSGI Server Serving HTTP service on port {0}'
.
format
(
port
)
print
'{0}'
.
format
(
datetime
.
datetime
.
now
().
strftime
(
'%a, %d %b %Y %H:%M:%S GMT'
))
httpd
.
serve_forever
()
首先我们看 WSGIServer 类__init__方法主要是初始化 socket 与服务器地址,绑定并监听端口;其次,serve_forever(self): 持续运行 server;handle_request(self):处理请求;最后,finish_response(self, app_data):返回请求响应。
获得地址和端口后先初始化 WSGIServer:server = WSGIServer(address),然后设置加载的wsgi app:server.set_application(TestMiddle(application)),接着持续运行 server:httpd.serve_forever()