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

[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()
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值