如何本身实现一个最简单web的服务器呢? 首先,你必须容许外部IP来访问你的IP,并开启一个端口不断的去监听他,python已经有模块实现这样的API供咱们监听端口html
import BaseHTTPServer serverip=(' ',8080) server=BaseHTTPServer.HTTPServer(serverip,RequestHandler) server.server_forever()
其中RequestHandler表示须要处理的链接,咱们说通常最多见的链接时HTTP协议,咱们知道HTTP协议中经过请求的方法有两种:GET和POST,这里以GET为例。python
def do_GET(self): self.send_response(200) self.send_header('content-type','html/txt')
在这里你能够添加想发送的头的关键字和值。而后就是发送请求获得的应答的内容了。 这里是相关的请求说明web
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)
这些基本功能保证了请求的规范性,可是对于代码的维护性仍是不够,这里能够对每一种错误也转换成类的方式,好比:code
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.pyorm
from datetime import datetime print '''\ <html> <body> <p>Generated {0}</p> </body> </html>'''.format(datetime.now())
而后只要把这个的输出发送给服务器就能够了。server
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,这个就是服务器了。虽然是练手,可是细节仍是有的。htm