python 开源web服务器_[转] Python实现简单的Web服务器

#-*- coding:utf-8 -*-

importsys, os, BaseHTTPServer, subprocess#-------------------------------------------------------------------------------

classServerException(Exception):'''服务器内部错误'''

pass

#-------------------------------------------------------------------------------

classbase_case(object):'''条件处理基类'''

defhandle_file(self, handler, full_path):try:

with open(full_path,'rb') as reader:

content=reader.read()

handler.send_content(content)exceptIOError as msg:

msg= "'{0}' cannot be read: {1}".format(full_path, msg)

handler.handle_error(msg)defindex_path(self, handler):return os.path.join(handler.full_path, 'index.html')deftest(self, handler):assert False, 'Not implemented.'

defact(self, handler):assert False, 'Not implemented.'

#-------------------------------------------------------------------------------

classcase_no_file(base_case):'''文件或目录不存在'''

deftest(self, handler):return notos.path.exists(handler.full_path)defact(self, handler):raise ServerException("'{0}' not found".format(handler.path))#-------------------------------------------------------------------------------

classcase_cgi_file(base_case):'''可执行脚本'''

defrun_cgi(self, handler):

data= subprocess.check_output(["python", handler.full_path])

handler.send_content(data)deftest(self, handler):return os.path.isfile(handler.full_path) and\

handler.full_path.endswith('.py')defact(self, handler):

self.run_cgi(handler)#-------------------------------------------------------------------------------

classcase_existing_file(base_case):'''文件存在的情况'''

deftest(self, handler):returnos.path.isfile(handler.full_path)defact(self, handler):

self.handle_file(handler, handler.full_path)#-------------------------------------------------------------------------------

classcase_directory_index_file(base_case):'''在根路径下返回主页文件'''

deftest(self, handler):return os.path.isdir(handler.full_path) and\

os.path.isfile(self.index_path(handler))defact(self, handler):

self.handle_file(handler, self.index_path(handler))#-------------------------------------------------------------------------------

classcase_always_fail(base_case):'''默认处理'''

deftest(self, handler):returnTruedefact(self, handler):raise ServerException("Unknown object '{0}'".format(handler.path))#-------------------------------------------------------------------------------

classRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):'''请求路径合法则返回相应处理

否则返回错误页面'''Cases=[case_no_file(),

case_cgi_file(),

case_existing_file(),

case_directory_index_file(),

case_always_fail()]#错误页面模板

Error_Page = """\

Error accessing {path}

{msg}

"""

defdo_GET(self):try:#得到完整的请求路径

self.full_path = os.getcwd() +self.path#遍历所有的情况并处理

for case inself.Cases:ifcase.test(self):

case.act(self)break

#处理异常

exceptException as msg:

self.handle_error(msg)defhandle_error(self, msg):

content= self.Error_Page.format(path=self.path, msg=msg)

self.send_content(content,404)#发送数据到客户端

def send_content(self, content, status=200):

self.send_response(status)

self.send_header("Content-type", "text/html")

self.send_header("Content-Length", str(len(content)))

self.end_headers()

self.wfile.write(content)#-------------------------------------------------------------------------------

if __name__ == '__main__':

serverAddress= ('', 8080)

server=BaseHTTPServer.HTTPServer(serverAddress, RequestHandler)

server.serve_forever()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值