为什么仅在第二次重启后才呈现Python Flask应用程序?

时间:2020-04-26 12:46:24

标签: 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

1 个答案:

答案 0 :(得分:0)

最简单的解决方案是将调试设置为false。或在此处使用任何解决方案:Why does running the Flask dev server run itself twice?