如何自己实现一个最简单web的服务器呢? 首先,你必须允许外部IP来访问你的IP,并开启一个端口不断的去监听他,python已经有模块实现这样的API供我们监听端口
import BaseHTTPServer
serverip=(' ',8080)
server=BaseHTTPServer.HTTPServer(serverip,RequestHandler)
server.server_forever()
其中RequestHandler表示需要处理的连接,我们说一般最常见的连接时HTTP协议,我们知道HTTP协议中通过请求的方法有两种:GET和POST,这里以GET为例。
def do_GET(self):
self.send_response(200)
self.send_header('content-type','html/txt')
在这里你可以添加想发送的头的关键字和值。然后就是发送请求得到的应答的内容了。 这里是相关的请求说明
self.wfile.write(content)
到这里其实发送一个应答任务已经完成了,但是为了保证传输的质量,所以要对输入进行过滤。
full_path=os.getcwd()+self.path
if not os.path.exists(full_path):
raise Exception("{0} is no found".format(self.path))
elif os.path.isfile(full_path):
self.handler_file(full_path)
else:
raise Exception("unknow error is {0}".format(self.path))
except Exception as msg:
handle_error(self,msg)
这些基本功能保证了请求的规范性,但是对于代码的维护性还是不够,这里可以对每一种错误也转换成类的方式,比如:
class case_no_file(object):
def test(self,handler):
return os.path.exists(handler.full_path)
def act(self,handler):
raise Exception("{0} no found ".format(handler.full_path))
最后再来说下CGI吧,如果想在服务器里添加新的内容该怎么办?直接修改源码那会很麻烦,所以就用到CGI来实现。比如我想增加时间输出的标签该怎么办?先新建一个python文件:time.py
from datetime import datetime
print '''\
<html>
<body>
<p>Generated {0}</p>
</body>
</html>'''.format(datetime.now())
然后只要把这个的输出发送给服务器就可以了。
import subprocess
class case_cgi(object):
def test(self,handler):
return os.path.isfile(handler.full_path) and handler.full_path.endwith('.py')
def act(self,handler):
run_cgi(handler)
def run_cgi(self,handler):
data=subprocess.check_output(['python',handler.full_path])
handler.send_message(data)
OK,这个就是服务器了。虽然是练手,但是细节还是有的。