您的位置:首页 > 理论基础 > 计算机网络

[Python]网络编程--web服务器

2018-01-23 17:24 330 查看

[Python]网络编程–web服务器

‘Festinatione facit vastum’

服务器基础

待续

服务器图示

待续

源代码

# -*- coding: utf-8 -*-
# @Time    : 2018/1/23 16:06
# @Author  : Shylock
# @Email   : JYFelt@163.com
# @File    : server.py
# @Software: PyCharm
# ---------------------------------------------------------
import sys, os, BaseHTTPServer

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

class ServerException(Exception):
"""服务器内部错误"""
pass

class case_no_file(object):
"""该路径不存在"""

def test(self, handler):
return not os.path.exists(handler.full_path)

def act(self, handler):
raise ServerException("'{0}' not found!".format(handler.path))

class case_existing_dile(object):
"""该路径是文件"""

def test(self, handler):
return os.path.isfile(handler.full_path)

def act(self, handler):
handler.handle_file(handler.full_path)

class case_always_fail(object):
"""所有情况都不符合时的默认处理类"""

def test(self, handler):
return True

def act(self, handler):
raise ServerException("Unknown object '{0}'".format(handler.path))

class case_directory_index_dile(object):

def index_path(self, handler):
return os.path.join(handler.full_path, 'index.html')

# 判断目标路径是否是目录&&目录下是否有index.html
def test(self, handler):
return os.path.isdir(handler.full_path) and \
os.path.isfile(self.index_path(handler))

def act(self, handler):
handler.handle_file(self.index_path(handler))

class RequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
"""
请求路径合法则返回相应处理
否则返回错误页面
"""

# 所有的可能性
Cases = [case_no_file(),
case_existing_dile(),
case_always_fail(),
case_directory_index_dile()]

# 错误页面模板
Error_Page = """\
<html>
<body>
<h1>Error accessing {path}</h1>
<p>{msg}</p>
</body>
</html>
"""

def do_GET(self):
try:

# 文件完整路径
self.full_path = os.getcwd() + self.path

# 遍历所有可能的情况
for case in self.Cases:
# 如果满足该类情况
if case.test(self):
# 调用相应函数
case.act(self)
break

"""
# 如果该路径不存在...
if not os.path.exists(full_path):
# 抛出异常:文件未找到
raise ServerException("'{0}' not found".format(self.path))

# 如果该路径是一个文件
elif os.path.isfile(full_path):
# 调用 handle_file 处理该文件
self.handle_file(full_path)

# 如果该路径不是一个文件
else:
# 抛出异常:该路径为不知名对象
raise ServerException("Unknown object '{0}'".format(self.path))
"""
# 处理异常
except Exception as msg:
self.handle_error(msg)

def handle_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)

def handle_file(self, full_path):
try:
with open(full_path, 'rb') as reader:
content = reader.read()
self.send_content(content)
except IOError as msg:
msg = "'{0}' cannot be read: {1}".format(self.path, msg)
self.handle_error(msg)

# ---------------------------------------------------------
if __name__ == '__main__':
serverAddress = ('', 8080)
server = BaseHTTPServer.HTTPServer(serverAddress, RequestHandler)
server.serve_forever()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Python Server 服务器