Miniwebserver

Aus C3D2
Version vom 15. November 2007, 00:27 Uhr von Toidinamai (Diskussion | Beiträge) (standard library → beginner version, twisted → advanced version, add guru version)

Wechseln zu: Navigation, Suche


Python

beginner version

#!/usr/bin/env python
import sys
import os

from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler

class ThreadingHTTPServer(ThreadingMixIn, HTTPServer):
    pass

if len(sys.argv) != 3:
    print "Usage: %s <port> <dir>" % (sys.argv[0],)
    sys.exit()

address = ('', int(sys.argv[1]))
server = ThreadedHTTPServer(address, SimpleHTTPRequestHandler)

os.chdir(sys.argv[2])

try:
    server.serve_forever()
except KeyboardInterrupt:
    pass

advanced version

#!/usr/bin/env python
import sys

from twisted.python import log
from twisted.internet import reactor
from twisted.web import server, static

if len(sys.argv) != 3:
    print "Usage: %s <port> <dir>" % (sys.argv[0],)
    sys.exit()

root = static.File(sys.argv[2])
site = server.Site(root)

reactor.listenTCP(int(sys.argv[1]), site)
log.startLogging(sys.stderr)
reactor.run()

guru version

twistd -n web --path $path --port $port

Ruby

#!/usr/local/bin/ruby
require 'webrick'
include WEBrick

if ARGV.size != 2
  puts "Usage: #{$0} <port> <dir>"
  exit
end

s = HTTPServer.new(
  :Port            => ARGV[0].to_i,
  :DocumentRoot    => ARGV[1]
)


trap("INT"){ s.shutdown }
s.start