首页 > 解决方案 > 为什么 Python Flask 应用程序仅在第二次重启后才呈现?

问题描述

我是 Python Flask 的新手。如果用户选择在运行时启动,我希望我的 Python 应用程序仅启动 Web 服务器(和 Flask 应用程序部分)。否则,应用程序应该只是在终端上运行一个程序。我使用了以下代码。

用户选择选项 '1' 工作正常 - 程序运行完成,没有 Web 服务器启动。

但是,如果用户选择下面的选项“2” - 整个应用程序将重新启动,再次要求相同的用户输入。html 页面此时也不会呈现。只有当用户现在第二次选择选项“2”时,我们才能让本地 Web 服务器正常工作并且 html 网页localhost:5000/index会按预期呈现。

(用户选择选项'2',然后在重新启动时选择选项'1' - 以终端程序和网页从不呈现而结束)

用户如何只选择一次选项“2”并让 Web 应用程序组件运行?为什么app.run()要执行两次以使 Web 应用程序运行?

import flask

app = flask.Flask(__name__)
app.config["DEBUG"]= True

@app.route('/index', methods=['GET'])
def home():
    print("came home!..")
    return flask.render_template('index.html')


print('hello there')
a = input("do you want 1. Normal app or  2.Web app? (1/2): ")

if a=='2':
    #do the flask thing
    print("Woo! the next line should start off the web server too .. but does it?")
    b = input("press enter to continue .. and then check with web browser")
    app.run()
else:
    print("Well done. This should end the terminal program cleanly.")
    b = input("press enter to continue .. and end.")

print(".. AND we are out of the main block")

下面显示的结果来自终端,用户被迫选择选项“2”两次以启动服务器。网页在浏览器上呈现良好。按 Ctrl+C 我们退出应用程序(两次!)

hello there
do you want 1. Normal app or  2.Web app? (1/2): 2
Woo! the next line should start off the web server too .. but does it?
press enter to continue .. and then check with web browser
 * Serving Flask app "try" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: on
 * Restarting with stat
hello there
do you want 1. Normal app or  2.Web app? (1/2): 2
Woo! the next line should start off the web server too .. but does it?
press enter to continue .. and then check with web browser
 * Debugger is active!
 * Debugger PIN: 132-339-530
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
came home!..
127.0.0.1 - - [26/Apr/2020 18:12:38] "GET /index HTTP/1.1" 200 -
.. AND we are out of the main block
.. AND we are out of the main block

标签: pythonflask

解决方案


最简单的解决方案是将调试设置为 false。或者在这里使用任何解决方案:为什么运行 Flask 开发服务器会自行运行两次?


推荐阅读