我在windows上安装了Vagrant,现在我有一个虚拟的ubuntu,我运行一个python脚本:
vagrant@precise32:/vagrant/FlaskMysql/FlaskApp$ ls
app.py static storedPro.txt templates
vagrant@precise32:/vagrant/FlaskMysql/FlaskApp$ python app.py
* Running on http://127.0.0.1:5002/ (Press CTRL+C to quit)
my Vagrantefile:
config.vm.box = "hashicorp/precise32"
config.vm.provision :shell, path: "bootstrap.sh"
config.vm.network :forwarded_port, guest: 80, host: 4567
config.vm.network :forwarded_port, guest: 5002, host: 5002
我试图从我的窗口中的浏览器访问上述地址,index.html页面在几秒钟后出现,然后消失。
更新:vagrant@precise32:/vagrant/FlaskMysql/FlaskApp$ curl http://127.0.0.1:5000
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN">
<title>500 Internal Server Error</title>
<h1>Internal Server Error</h1>
<p>The server encountered an internal error and was unable to complete your request. Either the server is overloaded or
there is an error in the application.</p>
谢谢。
除了转发端口,你还需要运行Flask应用程序,主机是"0.0.0.0"
:
app.run(host='0.0.0.0', port=5002)
使开发服务器对外可见;在Vagrant的例子中,我们希望应用程序对外部可见(从客户操作系统到主机操作系统)。
感谢chucksmash的回答,这是我的解决方案版本:
我更改了Python App中的主机和端口:
run(host='localhost', port=8080, debug=True)
:
run(host='0.0.0.0', port=5002, debug=True)
和vagrantfile from this:
config.vm.network "forwarded_port", guest: 8080, host: 8080, host_ip: "127.0.0.1"
:
config.vm.network "forwarded_port", guest: 5002, host: 5002
然后测试请求和不要忘记添加资源(URL端点) 'hello'在我的例子中:http://0.0.0.0:5002/hello
我想添加更多的Chucksmash的答案,如果有人仍然面临连接到主机上的flask URL的问题。尝试以下选项之一(两个都应该可以工作):
Vagrantfile:
config.vm.network "forwarded_port", guest: 5000, host: 5000, host_ip: "127.0.0.1"
app.py:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return "Hello world!"
if __name__ == "__main__":
app.run()
方法1。在app.run()中配置主机和端口,并使用python运行flash应用。
if __name__ == "__main__":
app.run(host="0.0.0.0", port=5000)
运行flask app:
$ python3 app.py
方法2。传递host
和port
作为参数给flask run
:
export FLASK_APP=app.py
flask run --host "0.0.0.0" --port 5000
您可以通过在终端上运行以下命令来验证它是否有效:
curl http://127.0.0.1:5000
output: Hello world!