python 简单的Http服务器

代码:

'''
Created on 2012-3-13

@author: Administrator
'''
#!/usr/bin/env python

from os import curdir,sep
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer


class MyHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        try:
            f=open(curdir+sep+self.path)
            self.send_response(200)
            self.send_header('Content-type','text/html')
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError:
            self.send_error(404, 'File Not Found: %s' % self.path)
            
    
def main():
    try:
        server = HTTPServer(('',80),MyHandler)
        print 'welcome to the ,machine...',
        print 'Press ^C once or twice to quit'
        server.serve_forever()
    except KeyboardInterrupt:
        print '^C received,shutting down server'
        server.socket.close()

if __name__=='__main__':
    main()

运行:

welcome to the ,machine... Press ^C once or twice to quit
yushh-PC - - [13/Mar/2012 10:19:13] code 501, message Unsupported method ('HEAD')
yushh-PC - - [13/Mar/2012 10:19:13] "HEAD / HTTP/1.1" 501 -
yushh-PC - - [13/Mar/2012 10:19:51] code 404, message File Not Found: /
yushh-PC - - [13/Mar/2012 10:19:51] "GET / HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:19:51] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:19:51] "GET /favicon.ico HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:08] code 501, message Unsupported method ('HEAD')
yushh-PC - - [13/Mar/2012 10:20:08] "HEAD / HTTP/1.1" 501 -
yushh-PC - - [13/Mar/2012 10:20:10] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:20:10] "GET /favicon.ico HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:51] code 404, message File Not Found: /a.html
yushh-PC - - [13/Mar/2012 10:20:51] "GET /a.html HTTP/1.1" 404 -
yushh-PC - - [13/Mar/2012 10:20:51] code 404, message File Not Found: /favicon.ico
yushh-PC - - [13/Mar/2012 10:20:51] "GET /favicon.ico HTTP/1.1" 404 -

页面访问:

Error response

Error code 404.

Message: File Not Found: /a.html.

Error code explanation: 404 = Nothing matches the given URI.

注意:

1、HTTPServer是基本的服务类

2、BaseHTTPServer除了0获得客户请求外不做其他事情

3、BaseHTTPResquestHandler执行标准的GET和HEAD请求并可以通过调用cgi脚本生成html返回给客户端

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值