如何运行提供特定路径的http服务器? [英] How to run a http server which serves a specific path?

查看:184
本文介绍了如何运行提供特定路径的http服务器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆