Python - Flask - Open A Webpage In Default Browser
I am working on a small project in Python. It is divided into two parts. First part is responsible to crawl the web and extract some infromation and insert them into a database. Se
Solution 1:
I use similar code on Mac OS X (with Safari, Firefox, and Chrome browsers) all the time, and it runs fine. Guessing you may be running into Flask's auto-reload feature. Set debug=False
and it will not try to auto-reload.
Other suggestions, based on my experience:
- Consider randomizing the port you use, as quick edit-run-test loops sometimes find the OS thinking port 5000 is still in use. (Or, if you run the code several times simultaneously, say by accident, the port truly is still in use.)
- Give the app a short while to spin up before you start the browser request. I do that through invoking
threading.Timer
.
Here's my code:
import random, threading, webbrowser
port = 5000 + random.randint(0, 999)
url = "http://127.0.0.1:{0}".format(port)
threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
app.run(port=port, debug=False)
(This is all under the if __name__ == '__main__':
, or in a separate "start app" function if you like.)
Post a Comment for "Python - Flask - Open A Webpage In Default Browser"