Getting Started: Your First Flask App
To build your first web application with Flask, you will create a single Python file that initializes the application, defines a URL route, and starts a development server. By the end of this guide, you will have a running "Hello World" application.
Prerequisites
Before starting, ensure you have Flask installed in your Python environment. You can verify this by trying to import it:
import flask
print(flask.__version__)
Step 1: Create the Application Instance
Create a new file named hello.py and add the following code to initialize the central Flask object:
from flask import Flask
app = Flask(__name__)
The Flask class is the central registry for your application. When you instantiate it, you must provide an import_name.
In Flask, the import_name (the first parameter) tells the application where it is located on the filesystem. Flask uses this path to resolve resources like templates and static files. If you are writing a single module (like hello.py), __name__ is the correct value to provide. If you were building a larger package, you would typically hardcode the package name (e.g., app = Flask("my_package")).
Step 2: Define a Route
Next, tell Flask which URL should trigger your code by defining a view function and decorating it with @app.route():
@app.route("/")
def hello():
return "Hello World!"
The @app.route("/") decorator creates a mapping between the root URL path (/) and the hello function. When a user visits your application's home page, Flask calls this function and uses its return value to create a response. In this case, it returns a simple string that the browser will display as text.
Step 3: Start the Development Server
To see your application in action, add a block at the bottom of hello.py to invoke the built-in development server:
if __name__ == "__main__":
app.run(debug=True)
The app.run() method starts a local WSGI server using Werkzeug. By setting debug=True, you enable the interactive debugger and the auto-reloader, which restarts the server whenever you save changes to your code.
Important Security Note: The app.run() server is designed for development convenience only. It is not intended for production environments as it does not meet the security or performance requirements of a public-facing server.
Step 4: Run the Application
You can now start your application by running the Python file directly:
python hello.py
You should see output similar to this:
* Serving Flask app 'hello'
* Debug mode: on
* Running on http://127.0.0.1:5000
Open http://127.0.0.1:5000 in your web browser to see "Hello World!".
Alternative: Using the Flask CLI
While app.run() is useful for quick scripts, Flask provides a powerful Command Line Interface (CLI) that is the preferred way to run applications during development.
If you use the CLI, you don't need the if __name__ == "__main__": block. You can run your app from the terminal using the flask command:
flask --app hello run --debug
Flask's run() method is designed to detect if it is being called from the CLI. If you try to call app.run() inside a script while also using the flask run command, Flask will ignore the app.run() call and print a warning to prevent starting two conflicting servers.
Complete Example
Your final hello.py file should look like this:
from flask import Flask
# Initialize the app with the module's name
app = Flask(__name__)
# Define the root route
@app.route("/")
def hello():
return "Hello World!"
# Run the development server
if __name__ == "__main__":
app.run(debug=True)
Next Steps
Now that you have a basic app running, you can explore:
- Variable Rules: Use
@app.route("/user/<username>")to capture values from the URL. - Templates: Use
render_template()to return HTML files instead of plain strings. - Blueprints: Organize your application into smaller, reusable components as it grows.