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

时间:2015-01-16 05:46:27

标签: python d3.js

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

python -m http.server 

托管本地服务器。现在,我的问题是如何在本地服务器中打开我的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>

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

3 个答案:

答案 0 :(得分:8)

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

$ python -m http.server
Serving HTTP on 0.0.0.0 port 8000 ...

(或者,Python2咒语)

$ python -m SimpleHTTPServer
Serving HTTP on 0.0.0.0 port 8000 ...

在此消息中,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,环回接口,多个网卡如何在同一台机器上运行,如果事情不是很重要)按预期工作,防火墙,受限制的端口以及谁知道还有什么。)

答案 1 :(得分:0)

我已经创建了一个小型便携式python 3脚本(应该可以在MacOS / Linux上运行)来本地渲染使用d3或更多网站的html文件。我认为这对其他人有用。

本质上,它使用子进程创建本地服务器,打开浏览器进行渲染,然后正确关闭服务器以便快速重用。您可以在此处找到Python 3脚本(有关如何使用它的一些详细信息):https://github.com/alexandreday/local_server。一个示例用法是:

$ python custom_server.py index.html

这将呈现您的index.html文件,该文件更常用的是d3.js或网站。

答案 2 :(得分:0)

尝试一下:

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()

test.html是您编写的HTML文件。