Header Ads

Um simples Webserver em Python

Vamos implementar um simples webserver em Python ?
Segue o código:
 
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import os,glob
 
class RequestHandler(BaseHTTPRequestHandler):
    def do_GET(self):
        fpath = os.path.join(os.getcwd(),self.path[1:])
        response = ""
        if os.path.isfile(fpath):
                response = open(fpath,"rb").read()                               
                if fpath[-3:] == 'php':
                    response = os.popen("php5 -f " + fpath).read()
                if fpath[-2:] == 'py':
                    response = os.popen("python " + fpath).read()
                if fpath[-3:] == 'pyc':
                    response = os.popen("python " + fpath).read()
        elif os.path.isdir(fpath):
                dirlist = glob.glob(fpath + "/*")
                response = "Directory Listing of "</span> + <span style="color: rgb(220, 20, 60);">os</span>.<span style="color: black;">path</span>.<span style="color: black;">basename</span><span style="color: black;">(</span>fpath<span style="color: black;">)</span> + <span style="color: rgb(72, 61, 139);">""
                response += ""
                for x in dirlist:
                    response += "\"" + os.path.basename(x) + "\">" + os.path.basename(x) + "
"
                response += ""
 
        self.send_response(200)
        self.send_header("Content-type","text/html")
        self.end_headers()
        self.wfile.write(str(response))
 
httpd = HTTPServer(('',7676),RequestHandler)
httpd.serve_forever()

Para executar:
python server.py
Fonte: http://masnun.com/2010/01/16/a-simple-web-server-in-30-lines-of-python-code/

Nenhum comentário