浙江省高等学校教师教育理论培训

微信搜索“教师资格证岗前培训”小程序

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

Goldblog - Python - 15 Line HTTP Server - Web Interface For Your Tools - Corey Goldberg

AS OF MAY 2008, THIS BLOG IS NO LONGER BEING UPDATED.

Visit the new blog at: http://coreygoldberg.blogspot.com




 2008年2月12日

Python - 15 Line HTTP Server - Web Interface For Your Tools

I write a lot of command line tools and scripts in Python. Sometimes I need to kick them off remotely. A simple way to do this is to launch a tiny web server that listens for a specific request to start the script.

I add a "WebRequestHandler" class to my script and call it from my main method. There is a "do_something()" method in the class. You call your code from this method.

All you have to do is launch your script and it will sit there and wait for requests. If the request is bad, it spits back a 404 error. If the request path matches what we are looking for (in this case "/foo"), the code is launched.

Now you have an easy way to call your script remotely. Just open a browser and type in the URL: http://your_server/foo, or call it with a tool like 'wget' or 'curl'.


import BaseHTTPServer

class WebRequestHandler(BaseHTTPServer.BaseHTTPRequestHandler):
    def do_GET(self):
        if self.path == '/foo':
            self.send_response(200)
            self.do_something()
        else:
            self.send_error(404)

    def do_something(self):
        print 'hello world'

server = BaseHTTPServer.HTTPServer(('',80), WebRequestHandler)
server.serve_forever()
posted on 2012-04-29 21:36  lexus  阅读(267)  评论(0编辑  收藏  举报