英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论