码迷,mamicode.com
首页 > 编程语言 > 详细

深入了解一下PYTHON中关于SOCKETSERVER的模块-B

时间:2015-09-16 14:07:51      阅读:245      评论:0      收藏:0      [点我收藏+]

标签:

请求多个文件的原型。

这个是最草的情况,就是硬编码到内存中的字符串,

真实的应用还是会转到其它端口处理,或是读到硬盘上的文件吧。

#!/usr/bin/env python

from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import time

starttime = time.time()

class RequestHandler(BaseHTTPRequestHandler):
    """Definintion of the request hadnler."""
    def _writeheaders(self, doc):
        """Write the HTTP headers for the document. If there is no
        documnet, send a 404 error code;"""
        if doc is None:
            self.send_response(404)
        else:
            self.send_response(200)
        #Always server up HTML for now.
        self.send_header(Content-type, text/html)
        self.end_headers()

    def _getdoc(self, filename):
        """Handle a request for a document """
        global starttime
        if filename == /:
            return """
                    <HTML><HEAD><TITLE>sample python page</TITLE></HEAD>
                    <BODY> THIS IS A SAMPLE PAGE.
                    </BODY></HTML>
                    """
        elif filename == /stats.html:
            return """
                    <HTML><HEAD><TITLE>Status</TITLE></HEAD>
                    <BODY> This server has veen running for %d seconds.
                    </BODY></HTML>
                    """ % int(time.time() - starttime)
        else:
            return None

    def do_HEAD(self):
        """Handle a request for headers only"""
        doc = self._getdoc(self.path)
        self._writeheaders(doc)

    def do_GET(self):
        """Handle a request for headers and body"""
        doc = self._getdoc(self.path)
        self._writeheaders(doc)
        if doc is None:
            self.wfile.write("""
            <HTML><HEAD><TITLE>Not found</TITLE></HEAD>
            <BODY> The requested document ‘%s‘ was not found.
            </BODY></HTML>""" % self.path)
        else:
            self.wfile.write(doc)
serveraddr = (‘‘,8765)
srvr = HTTPServer(serveraddr, RequestHandler)
srvr.serve_forever()

技术分享

深入了解一下PYTHON中关于SOCKETSERVER的模块-B

标签:

原文地址:http://www.cnblogs.com/aguncn/p/4813026.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!