1

I have a very simple Flask app (from https://flask.palletsprojects.com/en/stable/quickstart/)

# File name: app.py

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello_world():
    return "<p>Hello, World!</p>"

print("your server is running at:", "<Insert code here>")

I am using commands like flask run --host 127.0.0.1 --port 8200 to run my app server. I am trying to access the IP and port the development is listening to from the last line of the Python code. Is it possible? How should I do it?

What I am looking for:

$ flask run --host 127.0.0.1 --port 8200
your server is running at: http://127.0.0.1:8200
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:8200
Press CTRL+C to quit

The first line is printed by my code. The rest of lines are printed by Werkzeug.

1
  • 1
    At that print line, the server isn't running yet. At the very least you'd need to create some callback or middleware which is invoked by the server if and when it's running. Commented Oct 29, 2024 at 12:24

1 Answer 1

1

You can do Werkzeug reference 1 reference 2 server hooking as below:

from flask import Flask, request
import os

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

def print_startup_info():
    host = os.getenv("FLASK_RUN_HOST", "127.0.0.1") # 127.0.0.1 is default value when FLASK_RUN_HOST is not set
    port = os.getenv("FLASK_RUN_PORT", "5000") # 5000 is default value when FLASK_RUN_PORT is not set
    print(f"App is running at http://{host}:{port}") #Btw it should be "App is scheduled to run at..."

# Register the function to run on startup without needing `before_first_request`
print_startup_info()

O/P:

App is running at http://127.0.0.1:5000
 * Debug mode: off
WARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead.
 * Running on http://127.0.0.1:8200
Press CTRL+C to quit
  • print_startup_info() (the hook) is run immediately after import, only later is server started
  • the host address is printed using os.getenv which ig is only way to get host before the server starts
  • print_startup_info() need not be function, it may be in main code part itself or even in _name_=='app'
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.