Ross Wan's World!

Python, Ajax, PHP and Linux.

Python ─ 编写仅有15行代码的 HTTP 服务器

Posted by Ross Wan 于 2008/02/14

       这是一个瘦小的 Web 服务器,仅得15行代码,由《Python In A Nutshell》的一个例子改编而成。使用 Python 的 BaseHTTPServer.HTTPServer,可以完成简单的远程请求和应答。

import BaseHTTPServer

class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == ‘/foo’:      # 匹配 url :/foo 的请求
            self.send_response(200)
            self.do_something()
        else:
            self.send_error(404) # 对于错误的请求,返回 404 错误
           
    def do_something(self):
        print ‘hello world’
       
server = BaseHTTPServer.HTTPServer((‘127.0.0.1’,8080), WebRequestHandler)    # 创建 HTTPSever 服务器,绑定地址:http://127.0.0.1:8080
server.serve_forever()   # 启动 HTTPServer 服务器


参考资料:

Advertisements

发表评论

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / 更改 )

Twitter picture

You are commenting using your Twitter account. Log Out / 更改 )

Facebook photo

You are commenting using your Facebook account. Log Out / 更改 )

Google+ photo

You are commenting using your Google+ account. Log Out / 更改 )

Connecting to %s

 
%d 博主赞过: