如何使用 Python 设置本地 HTTP 服务器 [英] How do I setup a local HTTP server using Python

查看:26
本文介绍了如何使用 Python 设置本地 HTTP 服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试进行一些基本的 D3 编程.我正在阅读的所有书籍都在谈论设置本地 http 服务器,而这正是我发现自己陷入困境的地方.我输入了以下内容

I am trying to do some basic D3 programming. All the books I am reading talk about setting up a local http server and that is where I am finding myself stuck. I typed the following

python -m http.server 

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

to host the local server. Now, my problem is how to open my html file in this local server? I don't even know how to find the file in the command prompt. Any help will be appreciated. The following is my html file code on aptana. I also have put the d3.js file in the 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 服务器页面中打开.任何提示.

When I am running aptana, the html file is opening in a regular firefox page. I want it to open in the locally hosted http server page. Any hints.

推荐答案

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

The answer is provided when you start the server. In the same directory where you have your HTML file, start the server:

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

(或者,Python2 咒语)

(Or, the Python2 incantation)

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

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

In this message, Python tells you the IP address (0.0.0.0) and the port number (8000).

因此,如果文件名为 d3_template.html,您可以通过 http://0.0.0.0:8000/d3_template.html

So, if the file is named d3_template.html, you can get to this page via http://0.0.0.0:8000/d3_template.html

在大多数机器上你应该也可以使用

On most machines you should also be able to use

http://localhost:8000/d3_template.html或者http://127.0.0.1:8000/d3_template.html

如果你得到这样的错误:

If you get an error like this:

socket.error: [Errno 48] 地址已被使用

您想使用不同的端口:

$ python -m http.server 8888

并加载文件:

http://0.0.0.0:8888/d3_template.html

要了解所有这些工作的原因,您需要了解一些有关网络的知识(端口、DNS、环回接口、多个网卡在同一台机器上的行为,以及如果事情没有按预期工作,防火墙、受限制的端口以及谁知道还有什么).

To understand why all of these work, you'd want to learn a fair bit about networking (ports, DNS, loopback interface, how multiple network cards behave on the same machine and, if things aren't working as expected, firewalls, restricted ports and who knows what else).

这篇关于如何使用 Python 设置本地 HTTP 服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆