You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让指定Python代码通过公网IP地址正常访问?

问题解决方法

你的问题出在服务绑定的地址上:

  • 当前代码中,HTTPServer的第一个参数是('localhost', APP_PORT),这意味着服务只监听本地回环接口(127.0.0.1),只能接受来自服务器本机的请求,外部通过公网IP发起的请求无法被处理。

修改方案

将绑定地址从localhost改为0.0.0.0,这样服务会监听服务器上所有可用的网络接口,包括公网IP对应的接口:

import http.server
#from prometheus_client import start_http_server

APP_PORT = 8000
#METRICS_PORT = 8001

class HandleRequests(http.server.BaseHTTPRequestHandler):

    def do_GET(self):
        self.send_response(200)
        self.send_header("Content-type", "text/html")
        self.end_headers()
        self.wfile.write(bytes("<html><head><title>First Application</title></head><body style='color: #333; margin-top: 30px;'><center><h2>Welcome to our first Prometheus-Python application.</center></h2></body></html>", "utf-8"))
        self.wfile.close()

if __name__ == "__main__":
    #start_http_server(METRICS_PORT)
    # 把'localhost'替换为'0.0.0.0'
    server = http.server.HTTPServer(('0.0.0.0', APP_PORT), HandleRequests)
    server.serve_forever()

验证步骤

  1. 重启修改后的Python服务
  2. 使用公网IP+8000端口访问,即可正常打开页面

内容的提问来源于stack exchange,提问作者Stan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 18:32:36