我正在尝试做一些基本的 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 服务器页面中打开。任何提示。
启动服务器时就会提供答案。在 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、环回接口、多个网卡在同一台计算机上的行为方式,如果事情没有按预期工作,还需要了解防火墙、受限端口,谁知道还有什么)。
试试这个:
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 文件。
我创建了一个小型便携式 python 3 脚本(应该在 MacOS/Linux 上工作)来本地渲染使用 d3 或更常见网站的 html 文件。我认为这对其他人可能有用。
本质上,它使用子进程创建本地服务器,打开浏览器进行渲染,然后正确关闭服务器以快速重用。您可以在此处找到 Python 3 脚本(包含有关如何使用它的一些详细信息):https://github.com/alexandreday/local_server。一个使用示例是:
$ python custom_server.py index.html
这将渲染您的 index.html 文件,该文件使用 d3.js 或更普遍的网站。
您的本地环境有Python3,那么您可以运行以下命令。
python3 -m http.server
python -m http.server
然后你需要在浏览器中访问8000端口,如
http://localhost:8000
或http://0.0.0.0:8000
。