Python HTTP服务器只提供一个文件
我正在尝试使用PythonHttpServer创建一个网站,我知道我可以使用任何框架,比如flask或Django,但我不想这样做 python代码是:Python HTTP服务器只提供一个文件,python,apache,http,Python,Apache,Http,我正在尝试使用PythonHttpServer创建一个网站,我知道我可以使用任何框架,比如flask或Django,但我不想这样做 python代码是: from http import server from http.server import HTTPServer, BaseHTTPRequestHandler import json # importing all the modules with open('settings.json', 'r') as json_file:
from http import server
from http.server import HTTPServer, BaseHTTPRequestHandler
import json
# importing all the modules
with open('settings.json', 'r') as json_file:
setting = json.load(json_file)
port = setting['port']
start_at = setting['start_at']
# loading settings
class Serv(BaseHTTPRequestHandler):
def do_GET(self):
try:
file_to_open = open(start_at).read()
self.send_response(200)
except:
file_to_open = "File not found"
self.send_response(404)
self.end_headers()
self.wfile.write(bytes(file_to_open, 'utf-8'))
def start_server():
"""
Starts the server
"""
try:
server = HTTPServer(('', port), Serv)
print(f"[SERVER] Starting the server at port {port}")
server.serve_forever()
except KeyboardInterrupt:
print(f"[CLOSING] Closing the editor, see you again next time...")
if __name__ == "__main__":
start_server()
当我尝试为它提供服务时,index.html文件工作得很好,但图标和js文件不工作。我知道我可以使用python-mhttp.server
,但我不喜欢
我会给你一些截图
app.js在HTML中显示相同的代码,但实际上,我没有向javascript文件写入任何内容,这可能有助于您的回答:
正如其他人所说,看起来您正在打开同一个文件。要为其他文件提供服务器,您需要解析
self.path
并基于此打开。这是因为您每次都在读取相同的文件,即file\u To\u open=open(start\u at).read()
。您应该从请求中获取请求的文件并读取该文件。您的服务器甚至没有尝试提供任何文件,除了设置['start\u at']
…?!提示:path=self.translate\u路径(self.path)