2011-12-06 17 views
0

私は、HTTPServerとBaseHTTPRequestHandlerをPythonで使用して簡単なWebサーバーを作成しています。ここで私はこれまで持っているものです。BaseHTTPRequestHandlerに値を送信

from handler import Handler #my BaseHTTPRequestHandler 

def run(self): 
    httpd = HTTPServer(('', 7214), Handler) 
    try: 
     httpd.serve_forever() 
    except KeyboardInterrupt: 
     pass 
    httpd.server_close() 

私はハンドラからファイルを提供するためのベースパスを設定したいが、それはまだインスタンス化されていないので、私はそれを行う方法がわかりませんか?私はこれが本当に簡単/明白だと感じていますが、私はそれをどうやって行うのか考えることはできません。私はHandlerクラスの中でそれを行うことができると知っていますが、私の設定のすべてがここで読み込まれるので、可能ならばここからやりたいと思います。誰もあなたの質問に答えるしたかったんので

+0

ディレクトリからファイルを提供したいですか? SimpleHTTPServerはあなたのために既にデフォルトで... –

+0

私は 'SimpleHTTPServer' /' SimpleHTTPRequestHandler'を使用していたと思いますが、私の質問はこのクラスに対しても有効です。 'SimpleHTTPRequestHandler'に現在のディレクトリだけでなく、特定のディレクトリを使用するように指示するにはどうしたらいいですか?私はそのスーパーをはっきりとさせていないと思う。 – NeilMonday

+0

'python -m SimpleHTTPServer'は必要に応じてCWDからのファイルを提供します。あなたの仕事を簡単にしようとしています。 :) –

答えて

1

...

だけコメント「yourpath」とコードで部品を交換。

import os 
import posixpath 
import socket 
import urllib 
from BaseHTTPServer import HTTPServer 
from SimpleHTTPServer import SimpleHTTPRequestHandler 


class MyFileHandler(SimpleHTTPRequestHandler): 
    def translate_path(self, path): 
     """Translate a /-separated PATH to the local filename syntax. 

     Components that mean special things to the local file system 
     (e.g. drive or directory names) are ignored. (XXX They should 
     probably be diagnosed.) 

     """ 
     # abandon query parameters 
     path = path.split('?',1)[0] 
     path = path.split('#',1)[0] 
     path = posixpath.normpath(urllib.unquote(path)) 
     words = path.split('/') 
     words = filter(None, words) 
     path = '/' # yourpath 
     for word in words: 
      drive, word = os.path.splitdrive(word) 
      head, word = os.path.split(word) 
      if word in (os.curdir, os.pardir): continue 
      path = os.path.join(path, word) 
     return path 

def run(): 
    try: 
     httpd = HTTPServer(('', 7214), MyFileHandler) 
     httpd.serve_forever() 
    except KeyboardInterrupt: 
     pass 
    except socket.error as e: 
     print e 
    else: 
     httpd.server_close() 
+0

ニース!ありがとう。今夜これを試してみる。 – NeilMonday

関連する問題