[英]Flask hello.py basic app not running?
when I enter python hello.py in the command line, I get another bash prompt.当我在命令行中输入 python hello.py 时,我得到另一个 bash 提示符。 I'm not sure what could be the problem since I'm able to run a virtualenv and when I check which version of flask I have the latest version,
>>> '0.10.1'
installed.我不确定可能是什么问题,因为我能够运行 virtualenv,当我检查 flask 的哪个版本时,我安装了最新版本,
>>> '0.10.1'
。
Opals-MacBook-Pro:~ opalkale$ cd myproject
Opals-MacBook-Pro:myproject opalkale$ ls
hello.py venv
Opals-MacBook-Pro:myproject opalkale$ . venv/bin/activate
(venv)Opals-MacBook-Pro:myproject opalkale$ python hello.py
(venv)Opals-MacBook-Pro:myproject opalkale$
The code for hello.py looks like: hello.py 的代码如下所示:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
This code was taken from: http://flask.pocoo.org/docs/quickstart/#quickstart这段代码摘自: http://flask.pocoo.org/docs/quickstart/#quickstart
Your file does not match the example in the documentation.您的文件与文档中的示例不匹配。 You've placed the
if __name__ == '__main__':
block inside the definition of hello()
.您已将
if __name__ == '__main__':
块放在hello()
的定义中。
Whitespace is significant in Python.空格在 Python 中很重要。 It needs to be placed outside the function definition (ie, aligned all the way to the left).
它需要放置在函数定义之外(即一直向左对齐)。 Doing so will execute the
if
when the script is run.这样做将在脚本运行时执行
if
。 The way it exists now, you would need to import the hello
module and call the hello
function.按照它现在的存在方式,您需要导入
hello
模块并调用hello
函数。 That isn't what you want.那不是你想要的。 Fix the indentation and you will be all set.
修复缩进,您将一切就绪。
If the server already works and when you back after a while you get this error: flask command not defined
.如果服务器已经工作,当您稍后返回时会收到此错误:
flask command not defined
。
First run this command:首先运行这个命令:
pip list
... if flask is not there reinstall it again. ...如果 flask 不存在,请重新安装。
# In mac
venv/bin/activate
# or Windows
venv/Scripts/activate
pip install Flask
export FLASK_APP=yourServerName
flask run
Python always is a headache with these spaces. Python 总是对这些空间感到头疼。 I use sublime text editor that helps me to figure out these spacing syntax issues really quick.
我使用 sublime 文本编辑器来帮助我快速找出这些间距语法问题。
In your case, just move if name == " main ": to the left, so that that if is out of the function return above.在您的情况下,只需将 if name == " main ": 移动到左侧,以便 if 不在上面的函数返回中。
Hope that helps.希望有帮助。
You must take care of Indentation .你必须照顾Indentation 。 Tab and four blank spaces are different in it.
Tab 和四个空格在里面是不一样的。 Go with four blank spaces.
去四个空格。 You can re-create like below.
您可以像下面那样重新创建。 I'm providing custom port also.
我也提供自定义端口。
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run(host='0.0.0.0', port=5000)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.