Getting Started with Flask: A Lightweight Python Web Framework

Getting Started with Flask: A Lightweight Python Web Framework
Photo by Simone Viani / Unsplash

Flask is a lightweight yet powerful web framework for Python that enables developers to build web applications quickly and efficiently. Unlike Django, Flask follows a minimalistic approach, providing the essential tools without enforcing a specific project structure. This flexibility makes it a popular choice for beginners and advanced developers alike.

Why Choose Flask?

  1. Lightweight and Minimalistic: Flask offers a simple and unopinionated framework, allowing developers to structure their projects as they see fit.
  2. Extensible: You can add extensions for functionalities such as authentication, database integration, and API development.
  3. Built-in Development Server: Comes with a powerful debugger and development server.
  4. Easy to Learn: With a simple syntax and minimal setup, Flask is great for beginners.

Setting Up Flask

Before diving into Flask development, ensure you have Python installed, then follow these steps:

Run the Application:

python app.py

You can now visit http://127.0.0.1:5000/ in your browser to see "Hello, Flask!" displayed.

Create a Simple Flask App: Create a new file called app.py and add the following code:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello, Flask!"

if __name__ == '__main__':
    app.run(debug=True)

Install Flask using pip:

pip install Flask

Understanding Flask's Structure

A typical Flask application consists of:

  • app.py – The main application file containing routes and logic.
  • templates/ – A folder to store HTML templates.
  • static/ – A folder for CSS, JavaScript, and image files.

Creating a Basic Web Page

To serve HTML templates, create a templates directory and add an index.html file inside it:

<!DOCTYPE html>
<html>
<head>
    <title>Flask App</title>
</head>
<body>
    <h1>Welcome to Flask!</h1>
</body>
</html>

Modify app.py to render this template:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

Now, running the application will display the HTML page instead of plain text.

Adding Dynamic Routes

Flask allows URL parameters, making it easy to handle dynamic content:

@app.route('/user/<name>')
def user(name):
    return f"Hello, {name}!"

Visiting http://127.0.0.1:5000/user/Alice will display "Hello, Alice!".

Connecting Flask to a Database

Flask supports various databases through SQLAlchemy. To install it:

pip install flask-sqlalchemy

Example model in models.py:

from flask_sqlalchemy import SQLAlchemy
from flask import Flask

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///database.db'
db = SQLAlchemy(app)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)

To create the database:

python
>>> from app import db
>>> db.create_all()

Conclusion

Flask is an excellent choice for building lightweight web applications quickly. Its minimalistic nature provides flexibility while still allowing powerful integrations. Whether you're creating a small API or a full-fledged web application, Flask is a great tool to have in your development toolkit. Happy coding!