-6

Browser is opening the URL automatically twice, but I want only once. What to do to open the URL automatically only once?

from flask import Flask,render_template
import webbrowser

app = Flask(__name__)



@app.route('/')
def index():
    return render_template('index.html')

webbrowser.open("http://localhost:5000/")

if __name__ == '__main__':
   app.run(debug = True)
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

Firstly I have no idea why you are doing this. With debug mode and loading your site manually in the browser the server will automatically refresh the code. This is what is causing the double execution due to a child process that is spawned. I believe it is similar to this question - Why does running the Flask dev server run itself twice?

If you want to continue doing it this way and want to only open it once the only way I can see to do it is to not run in debug mode. But honestly I don't think that's a reasonable trade off for a small piece of convenience that won't be relevant once your application is deployed.

Tim Thompson
  • 301
  • 2
  • 7
  • but when i'm executing 1st time,it opens twice? As per your view, URL wil refresh when i press ctrl+S – vinay nimmalapudi Jul 20 '18 at 09:59
  • Yes I know. And I'm saying that's because you're in debug mode and the code runs through once, a child process is then spawned and it runs again. That's why you get two windows. To prove this change `app.run(debug = True)` to `app.run(debug = False)` and you'll see it only opens once. But you lose the debug functionality. Though i'm still not clear on why you're opening the web browser from code in the first place – Tim Thompson Jul 20 '18 at 10:01
  • i'm doing this,to escape from 1st time entering url on browser – vinay nimmalapudi Jul 20 '18 at 10:01
  • Well that might just have to be something you live with if you want debug functionality and don't want the server opening twice. I may be wrong but from my knowledge there is no way around this without turning off debug mode. – Tim Thompson Jul 20 '18 at 10:03
  • Thank u for your advice – vinay nimmalapudi Jul 20 '18 at 10:07