如何使用Python设置本地HTTP服务器

sha*_*rky 3 python d3.js

我正在尝试做一些基本的D3编程.我正在阅读的所有书籍都谈到了建立一个本地的http服务器,这就是我发现自己陷入困境的地方.我键入以下内容

python -m http.server 
Run Code Online (Sandbox Code Playgroud)

托管本地服务器.现在,我的问题是如何在本地服务器中打开我的html文件?我甚至不知道如何在命令提示符中找到该文件.任何帮助将不胜感激.以下是我在aptana上的html文件代码.我也把d3.js文件放在aptana中.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <title>
            D3 Page Template
        </title>
        <script type="text/javascript" src="d3.js"></script>
    </head>
    <script type="text/javascript">
        //D3 codes will go here
    </script>
</html>
Run Code Online (Sandbox Code Playgroud)

当我运行aptana时,html文件在常规的firefox页面中打开.我希望它在本地托管的http服务器页面中打开.任何提示.

stv*_*stv 13

启动服务器时提供答案.在您拥有HTML文件的同一目录中,启动服务器:

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...
Run Code Online (Sandbox Code Playgroud)

(或者,Python2咒语)

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...
Run Code Online (Sandbox Code Playgroud)

在此消息中,Python会告诉您IP地址(0.0.0.0)和端口号(8000).

因此,如果文件名为d3_template.html,则可以通过此页面访问此页面 http://0.0.0.0:8000/d3_template.html

在大多数机器上,您也应该能够使用

http://localhost:8000/d3_template.html 要么 http://127.0.0.1:8000/d3_template.html

如果你得到这样的错误:

socket.error: [Errno 48] Address already in use

您想使用其他端口:

$ python -m http.server 8888

并加载文件:

http://0.0.0.0:8888/d3_template.html

要理解为什么所有这些工作,你想要了解一些关于网络(端口,DNS,环回接口,多个网卡如何在同一台机器上运行,如果事情没有按预期工作,防火墙,限制)端口和谁知道还有什么).


小智 6

尝试这个:

from http.server import HTTPServer, BaseHTTPRequestHandler

class Serv(BaseHTTPRequestHandler):

    def do_GET(self):
       if self.path == '/':
           self.path = '/test.html'
       try:
           file_to_open = open(self.path[1:]).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'))

httpd = HTTPServer(('localhost',8080),Serv)
httpd.serve_forever()
Run Code Online (Sandbox Code Playgroud)

test.html你写的HTML文件在哪里。