I often run multiple dash applications at once and find it tedious to hardcode open ports so I decided to create a block after the ifmain
entry point that probes for open ports starting at 8050. Good news is that it works, but the odd part is that I get two Running on...
prompts, where the port on the second prompt is not valid. I’m guessing this has something to do with the hot-reloader, but I didn’t really dive too deep into the source code. Any ideas? Also, if someone has a more refined solution/recipe, please let me know.
Thanks!
Probing for an open port before app.run()
:
if __name__ == '__main__':
import socket
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
port = 8050
while True:
try:
s.bind(('', port))
s.close()
break
except OSError:
port += 1
continue
app.run_server(debug=debug, port=port)
Logging text (note that 8051 works, and 8052 does not):
Running on http://127.0.0.1:8051/
Debugger PIN: 997-459-730
* Serving Flask app "app" (lazy loading)
* Environment: development
* Debug mode: on
Running on http://127.0.0.1:8052/
Debugger PIN: 221-228-873