0

I am new to Python Flask. I want my Python application to only start the web server (and the Flask application parts) if the user chooses to do so, at runtime. Otherwise, the application should simply run a program on the terminal. I have used the following code.

User selecting option '1' works fine - the program runs to completion with no web server starting.

However, if the user chooses option '2' below - the whole application re-starts, asking for the same user input again. The html page also does not render at this point. Only if the user chooses option '2' now a second time, do we get the local web server working and the html webpage localhost:5000/index renders as expected.

(User selecting option '2', and then upon restart selects option '1' - ends as the terminal program and webpage never renders)

How can user select to option '2' just once and make the web app component run? Why is this app.run() being executed twice to get the web application running?

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")

The results shown below are from the terminal where the user is forced to selection option '2' twice to get server started .. Webpage renders fine on browser. on pressing Ctrl+C we exit the application (twice!)

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
Ani
  • 15
  • 8

1 Answers1

0

Easiest solution would be to set the debug to false. Or use any of the solutions here: Why does running the Flask dev server run itself twice?

Blue Print
  • 331
  • 3
  • 13