Flask - Application
Flask – Your First Application
Section titled “Flask – Your First Application”Let’s create a minimal Flask application to verify your setup and understand the basic structure.
Create a file named hello.py (or any other .py name) and add the following code:
# 1. Import the Flask classfrom flask import Flask
# 2. Create an instance of the Flask class# __name__ tells Flask where to look for resources like templates and static files.app = Flask(__name__)
# 3. Define a route using the route() decorator# This binds the URL '/' to the hello_world function.@app.route('/')def hello_world(): # 4. This function is the view function. # It returns the response that will be sent to the browser. return 'Hello, World!'
# 5. Check if the script is executed directly (not imported)if __name__ == '__main__': # 6. Run the application using the built-in development server. # debug=True enables debug mode (explained below). app.run(debug=True)Explanation:
Section titled “Explanation:”- Import
Flask: We start by importing the necessary class from theflaskpackage. - Create
appInstance: We create an instance of theFlaskclass. This instance is our WSGI (Web Server Gateway Interface) application. The__name__argument is a standard Python variable that holds the name of the current module. Flask uses this to determine the application’s root path, which helps locate related resources like templates and static files. - Define a Route (
@app.route): The@app.route('/')decorator registers the following function (hello_world) to handle requests for the root URL (/). - View Function: The
hello_world()function is called when a request comes in for the/URL. It simply returns the string ‘Hello, World!’. This string will be sent back to the client (e.g., web browser) as the HTTP response body. - Run Check (
if __name__ == '__main__':): This standard Python construct ensures that the code inside this block only runs when the script is executed directly (e.g., by runningpython hello.py). It prevents the server from starting if the script is imported into another module. - Start the Server (
app.run()): This method starts Flask’s built-in development web server. It listens for incoming requests and routes them to the appropriate view functions.
Running the Application
Section titled “Running the Application”-
Make sure your virtual environment is activated.
-
Open your terminal, navigate to the directory where you saved
hello.py. -
Run the script using the Python interpreter:
python hello.pyYou should see output similar to this (the exact address and port might vary slightly):
* Serving Flask app 'hello' (lazy loading) * Environment: development * Debug mode: on * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit) * Restarting with stat * Debugger is active! * Debugger PIN: ...This indicates that the development server is running.
- Open your web browser and go to the URL shown:
http://127.0.0.1:5000/(orhttp://localhost:5000/).
You should see the text ‘Hello, World!’ displayed on the page.
Debug Mode
Section titled “Debug Mode”We started the server using app.run(debug=True). Enabling debug mode provides several benefits during development:
- Automatic Reloader: The server automatically restarts whenever you save changes to your code. This saves you from manually stopping and starting the server after every modification.
- Interactive Debugger: If an error occurs during a request, Flask displays a detailed traceback in the browser, allowing you to inspect the code, variables, and execution stack at the point of failure. This is extremely helpful for diagnosing problems.
- Security Warning: Never run a Flask application with
debug=Truein a production environment! The interactive debugger allows arbitrary code execution, which poses a major security risk.
app.run() Parameters
Section titled “app.run() Parameters”The app.run() method accepts several optional parameters:
| Parameter | Description |
|---|---|
| host | The hostname to listen on. Defaults to '127.0.0.1' (localhost), meaning the server is only accessible from your own computer. Set to '0.0.0.0' to make the server accessible from other devices on your network (use with caution). |
| port | The port number to listen on. Defaults to 5000. |
| debug | Set to True to enable debug mode. Defaults to False if the FLASK_ENV environment variable is not set to development. |
| options | Additional options to be forwarded to the underlying Werkzeug server. |
For example, to run on port 8080 and make it accessible on your network:
if __name__ == '__main__': app.run(host='0.0.0.0', port=8080, debug=True)