2016-10-01 147 views
5

這是我的Python3項目hiearchy:如何運行服務於特定路徑的http服務器?

projet 
    \ 
    script.py 
    web 
    \ 
    index.html 

script.py,我想運行的服務web文件夾的內容HTTP服務器。

Here建議這個代碼來運行一個簡單的HTTP服務器:

import http.server 
import socketserver 

PORT = 8000 
Handler = http.server.SimpleHTTPRequestHandler 
httpd = socketserver.TCPServer(("", PORT), Handler) 
print("serving at port", PORT) 
httpd.serve_forever() 

但其實這成爲project,不web。如何指定我想要提供的文件夾的路徑?

+0

難道你實際上閱讀了其他文檔? –

回答

7

https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler

該類從當前目錄提供文件服務和下文中,直接映射 目錄結構的HTTP請求。

所以你只需要將當前目錄更改啓動服務器之前 - 看到os.chdir

如:

import http.server 
import socketserver 
import os 

PORT = 8000 

web_dir = os.path.join(os.path.dirname(__file__), 'web') 
os.chdir(web_dir) 

Handler = http.server.SimpleHTTPRequestHandler 
httpd = socketserver.TCPServer(("", PORT), Handler) 
print("serving at port", PORT) 
httpd.serve_forever() 
+0

謝謝!注意:我添加了try:'httpd.serve_forever(); KeyboardInterrupt除外:pass; httpd.server_close()'實際關閉端口。 – roipoussiere

4

如果你只是想提供靜態文件,你可以通過運行SimpleHTTPServer做模塊:

python -m SimpleHTTPServer 

這樣你就不需要寫任何腳本。

2

只是爲了完整性,這裏是你如何可以設置實際的服務器類從任意目錄中的文件服務:

try 
    # python 2 
    from SimpleHTTPServer import SimpleHTTPRequestHandler 
    from BaseHTTPServer import HTTPServer as BaseHTTPServer 
except ImportError: 
    # python 3 
    from http.server import HTTPServer as BaseHTTPServer, SimpleHTTPRequestHandler 


class HTTPHandler(SimpleHTTPRequestHandler): 
    """This handler uses server.base_path instead of always using os.getcwd()""" 
    def translate_path(self, path): 
     path = SimpleHTTPRequestHandler.translate_path(self, path) 
     relpath = os.path.relpath(path, os.getcwd()) 
     fullpath = os.path.join(self.server.base_path, relpath) 
     return fullpath 


class HTTPServer(BaseHTTPServer): 
    """The main server, you pass in base_path which is the path you want to serve requests from""" 
    def __init__(self, base_path, server_address, RequestHandlerClass=HTTPHandler): 
     self.base_path = base_path 
     BaseHTTPServer.__init__(self, server_address, RequestHandlerClass) 

然後你可以設置任意路徑代碼:

web_dir = os.path.join(os.path.dirname(__file__), 'web') 
httpd = HTTPServer(web_dir, ("", 8000)) 
httpd.serve_forever() 
相關問題