创建可以通过Flask框架在同一台计算机上的其他计算机调用的端点。

huangapple go评论61阅读模式
英文:

Create endpoint which can be called by other computers on same machine using flask framework

问题

我目前正在尝试创建一个可以被同一网络上的其他计算机调用的端点。以下是我正在使用的示例代码:

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)

countries = [
    {"id": 1, "name": "Thailand", "capital": "Bangkok", "area": 513120},
    {"id": 2, "name": "Australia", "capital": "Canberra", "area": 7617930},
    {"id": 3, "name": "Egypt", "capital": "Cairo", "area": 1010408},
]

@app.route("/countries", methods=["GET"])
def get_countries():
    return jsonify(countries)

目前,可以通过以下方式调用上述端点:

http://127.0.0.1:5000/countries

从我的个人电脑上。我应该如何配置它,以便可以从网络上的其他计算机调用它呢?我尝试将 127.0.0.1 替换为我的计算机名称,但连接被拒绝。

英文:

I am currently trying to create an endpoint which can be called by other computers on the same network as me. Following is the sample code I am working with

from flask import Flask, request, jsonify
import requests

app = Flask(__name__)


countries = [
    {"id": 1, "name": "Thailand", "capital": "Bangkok", "area": 513120},
    {"id": 2, "name": "Australia", "capital": "Canberra", "area": 7617930},
    {"id": 3, "name": "Egypt", "capital": "Cairo", "area": 1010408},
]

@app.get("/countries")
def get_countries():
    return jsonify(countries)

Currently the above endpoint can be called at

http://127.0.0.1:5000/countries

from my own PC. How can I configure it such that it can be called from other computers on my network. I tried replacing 127.0.0.1 with my PC name but connection was refused.

答案1

得分: 1

你可以使用主机参数:

if __name__ == "__main__":
   app.run(host="0.0.0.0", port=5000)

使用你的电脑的IP地址,你可以从网络中的任何电脑访问它。

最后,不要忘记打开端口,例如在这个示例中是5000。如果是Windows系统,你需要允许Windows Defender接收传入连接;如果是Linux系统,你可以检查netstat的选项。

英文:

You can use the host argument

if __name__ = "__main__":
   app.run(host="0.0.0.0", port=5000)

With your pc's ip you can access to it from any pc in the network.

And lastly do not forget to open your port for this example it is 5000, if windows you need to allow incoming at the windows defender and if linux you can check netstat options.

huangapple
  • 本文由 发表于 2023年7月13日 18:18:37
  • 转载请务必保留本文链接:https://go.coder-hub.com/76678289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定