【问题标题】:How do I setup a local HTTP server using Python如何使用 Python 设置本地 HTTP 服务器
【发布时间】:2015-01-16 05:46:26
【问题描述】:

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

【问题讨论】:

  • 问题不在于 d3。 d3 并且您的内联
  • 但是我正在阅读的所有书籍都在谈论本地托管的 http 服务器。你是说d3编程不需要这个服务器?
  • 我同意 Taysky,这个问题需要重新命名和重新标记。意识到大多数编程任务将由许多较小的任务组成,其中一些与您的核心任务完全无关。学习提出适合任务的问题是一项基本技能。
  • 令人惊讶的是,谷歌搜索 Taysky 的建议标题或用它开始一个 SO 问题并没有提供任何有用的信息。更不用说 Python2 和 Python3 的差异可能会让初学者感到困惑。

标签: python d3.js


【解决方案1】:

在您启动服务器时提供答案。在您拥有 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、环回接口、多个网卡在同一台机器上的行为方式,以及如果事情没有按预期工作,防火墙,受限端口,还有谁知道呢)。

【讨论】:

    【解决方案2】:

    试试这个:

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

    【讨论】:

      【解决方案3】:

      我创建了一个小型便携式 python 3 脚本(应该在 MacOS/Linux 上工作)来本地呈现使用 d3 或更一般网站的 html 文件。我认为这对其他人可能有用。

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

      $ python custom_server.py index.html
      

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

      【讨论】:

        猜你喜欢
        • 2020-04-16
        • 2014-06-27
        • 2011-12-18
        • 2010-09-15
        • 2016-04-15
        • 1970-01-01
        • 2013-10-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多