【问题标题】:Trying to access my Python flask webservice from Internet, I reach the server howver it return 404 if I use 127.0.0.1 it works but not actual IP尝试从 Internet 访问我的 Python 烧瓶 Web 服务,我到达服务器,但是如果我使用 127.0.0.1 它返回 404 它可以工作但不是实际 IP
【发布时间】:2021-07-01 08:44:08
【问题描述】:

问题: 尝试从 Internet 访问我的网络服务,调用到达服务但服务返回 404,即使我在使用 127.0.0.1:5000 时尝试我的本地 IP 地址同样的问题,它也可以工作

from flask import Flask, jsonify

app = Flask(__name__)
courses= [{'name':"Dirty Corporate Dairy",
           'course_id': "0",
           'Description': "Story about ",
           'Price':"120"},
          {'name': "Dirty Corporate Dairy 2",
           'course_id': "1",
           'Description': "Story about ",
           'Price':"1200"},
          {'name': "Dirty Corporate Dairy3",
           'course_id': "2",
           'Description': "Story about ",
           'Price':"12000"}
          ]


if __name__ == '__main__':
    from waitress import serve
    app.run(host='192.168.0.113',debug=True,port=80)

@app.route('/')
def index():
    return "Welcome To the Course API"

@app.route("/courses", methods=['Get'])
def get():
    return jsonify({'Courses': courses})

@app.route("/courses/<int:course_id>", methods=['Get'])
def get_course(course_id):
    return jsonify({'Courses': courses[course_id]})

@app.route("/courses", methods=['Post'])
def create():
    course={'name': "Dirty Corporate Dairy7",
           'course_id': "6",
           'Description': "Story about",
           'Price':"120000000"}
    courses.append(course)
    return jsonify({'Created': course})

@app.route("/courses/<int:course_id>", methods=['Put'])
def update(course_id):
    courses[course_id]["Description"] = "New Updated Description"
    return jsonify({'Courses': courses[course_id]})

if __name__ == "__main__":
    app.run(debug=True)

日志:

  • 服务 Flask 应用“主”(延迟加载)

  • 环境:生产 警告:这是一个开发服务器。不要在生产部署中使用它。 请改用生产 WSGI 服务器。

  • 调试模式:开启

  • 使用 stat 重启

  • 调试器已激活!

  • 调试器 PIN:186-690-898

  • http://192.168.0.113:80/ 上运行(按 CTRL+C 退出)

    192.168.0.113 - - [05/Apr/2021 18:44:32] “←[33mGET / HTTP/1.1←[0m” 404 - 192.168.0.113 - - [2021 年 4 月 5 日 18:44:40]“←[33mGET / HTTP/1.1←[0m”404 - 157.48.141.253 - - [05/Apr/2021 18:47:41]“←[33mGET /courses HTTP/1.1←[0m”404 -

【问题讨论】:

  • Flask 的内置服务器不适合生产(在本地开发环境之外托管您的应用程序)。请参阅this SO thread 了解更多信息。

标签: python web-services flask public static-ip-address


【解决方案1】:
  1. 192.168.0.113 是本地(家庭)网络上的 IP 地址(请参阅此documentation),默认情况下,您的家庭网络无法访问互联网。这意味着您的程序只能在您的家庭网络中访问。您家庭网络之外的人无法访问它。
  2. 为了能够通过 Internet 访问您的程序,您需要一项服务,该服务实质上将“将此本地 ip”放在网络上,即可以为您的计算机提供隧道的服务。执行此操作且被广泛使用的一项服务是https://ngrok.io。基本上,该服务将为您提供一个映射到您本地 ip 的公共 ip

【讨论】:

    【解决方案2】:

    出于安全考虑,默认情况下,Flask 仅侦听来自本地源 (127.0.0.1) 的请求(这是一项安全功能)。要使服务可从其他 ip 使用,您需要使用 --host 选项 like here 公开它。

    【讨论】:

      猜你喜欢
      • 2020-03-25
      • 2021-09-01
      • 1970-01-01
      • 2012-05-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多