如何运行提供特定路径的http服务器? [英] How to run a http server which serves a specific path?
问题描述
这是我的Python3项目hiearchy:
this is my Python3 project hiearchy:
projet
\
script.py
web
\
index.html
从script.py
,我想运行提供web
文件夹内容的http服务器.
From script.py
, I would like to run a http server which serve the content of the web
folder.
此处建议使用以下代码来运行简单的http服务器:
Here is suggested this code to run a simple http server:
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
服务的.如何指定要提供服务的文件夹的路径?
but this actually serve project
, not web
. How can I specify the path of the folder I want to serve?
推荐答案
https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler
此类直接提供当前目录及以下目录中的文件 将目录结构映射到HTTP请求.
This class serves files from the current directory and below, directly mapping the directory structure to HTTP requests.
So you just need to change the current directory prior to starting the server - see 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()
这篇关于如何运行提供特定路径的http服务器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!