Flask is a micro web framework written in Python. It is classified as a “micro” framework because it does not require particular tools or libraries, nor does it have a specific pattern for building applications, like Django’s Model-View-Controller (MVC) pattern. However, this does not mean Flask is limited; rather, it gives developers more flexibility on how they want to implement things.
Here’s a quick introduction to Flask:
- Installation
You can install Flask via pip:
pip install Flask
- Basic Application
Here’s a basic Flask application:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def hello_world():
return 'Hello, World!'
if __name__ == '__main__':
app.run(debug=True)
- Routing
Flask provides an easy way to define routes:
@app.route('/about')
def about():
return 'About page'
- Variables in Routes
You can capture variables from routes as well:
@app.route('/user/<username>')
def show_user_profile(username):
return f'User {username}'
- Templates
Flask can be used with the Jinja2 template engine. For example:
from flask import render_template
@app.route('/hello/<name>')
def hello(name=None):
return render_template('hello.html', name=name)
And in a templates
folder, you’d have a hello.html
file:
<!DOCTYPE html>
<html>
<head>
<title>Hello, {{ name }}!</title>
</head>
<body>
<h1>Hello, {{ name }}!</h1>
</body>
</html>
- Static Files
By default, Flask looks for static files (like CSS and JavaScript) in a folder named “static”:
<link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
- Flask Extensions
Flask has a thriving ecosystem of extensions that you can use to add functionality to your applications. For example, Flask-SQLAlchemy adds ORM capabilities, Flask-WTF aids in form handling, Flask-Login helps with user authentication, and many more. - Development & Deployment
- During development, use
app.run(debug=True)
to activate debug mode, which provides helpful error messages and auto-reloads the app upon changes. - For production deployment, using Flask’s built-in server isn’t recommended. Instead, deploy Flask apps using a more robust server, like Gunicorn, and a reverse proxy, like Nginx or Apache.
- Documentation
Flask has excellent official documentation, which includes quick starts, patterns, and links to helpful resources.
Sure, below is a basic example of using Flask to create a simple web application.
Installation
If you haven’t installed Flask, you can do so using pip:
pip install Flask
Simple Flask App
Here’s a straightforward example of a Flask application. This app initializes a Flask object, defines a route (URL pattern), and starts a development server.
Create a file named app.py
:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello, Flask!"
@app.route("/greet/<name>")
def greet(name):
return f"Hello, {name}!"
if __name__ == "__main__":
app.run(debug=True)
Let’s go through the code:
app = Flask(__name__)
: Create a Flask web server from the Flask module.@app.route("/")
: A decorator to tell Flask what URL should trigger the functionhome()
.def home()
: The function to be triggered when the URL pattern specified by@app.route("/")
is accessed.return "Hello, Flask!"
: The response returned to the user in their web browser.@app.route("/greet/<name>")
: A parameterized route that allows dynamic URL patterns.def greet(name)
: The function that uses a URL parameter and returns a personalized greeting.if __name__ == "__main__": app.run(debug=True)
: Start the server and allow for debugging (restarts server on code changes and provides detailed error messages).
Running the App
To run the app, open a terminal and navigate to the directory containing app.py
. Then execute:
python app.py
Your app should be running on localhost:5000
or 127.0.0.1:5000
. Open this URL in your web browser, and you should see the “Hello, Flask!” message. To test the parameterized route, try visiting localhost:5000/greet/YourName
.
Note
- Flask’s built-in server is not suitable for production. For deployment in a production environment, consider using server options like Gunicorn combined with Nginx or Apache.
- Ensure you have Flask installed in your Python environment before running the application. If you’re using a virtual environment (recommended), activate it before installing Flask and running the app.
This is just a brief overview, and Flask offers many more features and options. Depending on your needs, Flask can be a simple and lightweight solution or be scaled up with extensions and various configurations for more complex applications.