Flask is a lightweight Python web framework used to build web applications quickly. It provides the essential tools, libraries, and features you need to create simple single-page apps or larger, more complex web applications.
Flask is often called a micro-framework because it keeps the core minimal and lets you add only the components you need, making it easy to learn and flexible to use.
Flask(__name__).@app.route().app.run().debug=True for automatic reload and better error messages during development.Install Flask using pip from your terminal or command prompt:
# Install Flask using pip
pip install Flask
At the core of a Flask app, you usually have these pieces:
app = Flask(__name__).@app.route() decorator to connect a URL (like '/') to a Python function.if __name__ == '__main__': block to run the app when the file is executed directly.app.run(debug=True) starts the development server with debug mode enabled.Here is a minimal Flask application that returns a simple message at the home page:
# Import the Flask class
from flask import Flask
# Create the Flask application instance
app = Flask(__name__)
# Define a route for the homepage
@app.route('/')
def home():
# Return a simple response
return "Hello, Flask!"
# Run the app only if this file is executed directly
if __name__ == '__main__':
# Start the development server in debug mode
app.run(debug=True)
Save the file as something like app.py, then run it from your terminal:
# Run the Flask app
python app.py
After running, Flask starts a development server (by default on port 5000). Open your browser and visit:
http://127.0.0.1:5000/
You can define additional routes to serve different pages, like an About page:
# Define a new route for the About page
@app.route('/about')
def about():
# Return a simple text response for this route
return "This is the About page."
Now, visiting http://127.0.0.1:5000/about will show the text from the about() function.
http://127.0.0.1:5000/, the browser displays: Hello, Flask!http://127.0.0.1:5000/about, the browser displays: This is the About page.Each route corresponds to a Python function. Flask calls the function when the URL is requested and sends its return value back to the browser as the response.
debug=True only in development, not in production./contact and /services.<h1>Welcome</h1>) instead of plain text./hello/<name>) and display the name in the response.