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

rryofs0p  于 2022-11-12  发布在  Python
关注(0)|答案(3)|浏览(141)

我正在尝试做一些基本的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服务器页面中打开。任何提示。

dphi5xsq

dphi5xsq1#

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

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

(Or,《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.htmlhttp://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、环回接口、多个网卡在同一台计算机上的行为方式,以及防火墙、受限端口等,如果没有按预期工作,谁知道还有什么)。

b09cbbtk

b09cbbtk2#

试试看:

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文件。

tct7dpnv

tct7dpnv3#

我已经创建了一个小型的可移植python3脚本(应该可以在MacOS/Linux上工作)来本地渲染使用d3的html文件或更一般的网站。我认为这对其他人可能有用。
实际上,它使用一个子进程创建一个本地服务器,打开浏览器进行渲染,然后关闭服务器以便快速重用。你可以在这里找到Python 3脚本(关于如何使用它的一些细节):https://github.com/alexandreday/local_server。使用示例为:

$ python custom_server.py index.html

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

相关问题