Flask Python-基本程序不起作用

我开始学习Flask。

我写了这个超级基本的应用程序。它运行但不执行任何操作:

from flask import Flask

app = Flask(__name__)


@app.route('/')
def Index():
    return "<h1>Hello!</h1>"


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

控制台显示:

C:\ Users \ TalT \ PycharmProjects \ FlaskBeginners \ venv \ Scripts \ python.exe   C:/用户/TalT/PycharmProjects/FlaskBeginners/MyFirstWebPage.py      流程结束,退出代码为0

我在Win10,PyCharm 2019.3.3和Python 3.7上工作。 我不明白问题出在哪里?是python问题还是项目配置? 你能告诉我吗?

谢谢!

评论
  • aet
    aet 回复

    您的问题是:

    if __name__ == "__name__":
    

    必须更改为:

    if __name__ == '__main__':
    

    要启动烧瓶应用程序,您有2种简单的不同方法。

    1. Rename your main file to app.py or wsgi.py and go to path of the file in terminal and type flask run. In this way, if you want to run app in debug mode, In the same path, type set FLASK_ENV=development in terminal (Windows) and then write flask run.

    提示:这样,您必须从项目中删除以下代码:

    if __name__ == '__main__':
        app.run()
    

    2. Write your code in a python file (name is not matter) for example with main.py name write like this:

    from flask import Flask
    
    app = Flask(__name__)
    app.config['DEBUG']=True
    
    @app.route('/')
    def Index():
        return '<h1>Hello!</h1>'
    
    
    if __name__ == '__main__':
        app.run()
    

    And run the application by running this command in the path of your file: python main.py . Remember, add this code app.config['DEBUG']=True only if you want to run your code in debug mode.