Flask Fundamentals - benhall/flask-demo

Flask Fundamentals

This document covers the fundamentals of Flask, a popular web framework for Python. It will explain key concepts, provide examples, and link to external resources for further reading.

What is Flask?

Flask is a micro web framework written in Python. It is designed to make getting started quick and easy, with the ability to scale up to complex applications. It is a minimalistic framework, meaning that it lacks many features and functionality that full-stack frameworks like Django offer. Instead, Flask allows you to add extensions and libraries as needed.

Key Concepts

  • Routing: Flask uses routes to determine how to respond to a client request. A route is a rule that tells Flask which function to call when a specific URL is requested.
  • Views: In Flask, a view is a function that handles a request and produces a response.
  • Templates: Flask uses the Jinja2 template engine to generate HTML dynamically. Templates are text files that contain placeholders for dynamic content.
  • Static Files: Flask can serve static files, such as images, CSS, and JavaScript, directly to the client.
  • Extensions: Flask has a modular design, allowing you to add functionality through extensions. Examples include Flask-SQLAlchemy for database support and Flask-WTF for form handling.

Getting Started

To create a new Flask application, you will need Python and Flask installed. You can install Flask using pip:

pip install flask

Here is a simple “Hello, World!” Flask application:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def hello():
return "Hello, World!"

if __name__ == "__main__":
app.run()

This application creates a new Flask web server from the Flask module and defines a single route that returns the string “Hello, World!” when the root URL is requested.

Routing

Flask uses routes to determine how to respond to a client request. A route is a rule that tells Flask which function to call when a specific URL is requested. Routes are defined using the @app.route decorator.

Here is an example of a Flask application with multiple routes:

from flask import Flask
app = Flask(__name__)

@app.route("/")
def home():
return "Welcome to the home page!"

@app.route("/about")
def about():
return "This is the about page."

if __name__ == "__main__":
app.run()

In this example, the application has two routes: the root URL (“/”) and “/about”. When the root URL is requested, the home function is called. When “/about” is requested, the about function is called.

Views

In Flask, a view is a function that handles a request and produces a response. A view takes a request as input and returns a response. The response can be a string, a rendered template, or a redirect.

Here is an example of a Flask application with a view:

from flask import Flask, render_template
app = Flask(__name__)

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

if __name__ == "__main__":
app.run()

In this example, the home function is a view that returns a rendered template. The render_template function takes the name of a template file and returns the rendered template as a string.

Templates

Flask uses the Jinja2 template engine to generate HTML dynamically. Templates are text files that contain placeholders for dynamic content.

Here is an example of a simple Jinja2 template:

<!DOCTYPE html>
<html>
<head>
<title>{{ title }}</title>
</head>
<body>
<h1>{{ heading }}</h1>
<p>{{ message }}</p>
</body>
</html>

In this example, the template contains three placeholders: title, heading, and message. These placeholders are replaced with dynamic content when the template is rendered.

Static Files

Flask can serve static files, such as images, CSS, and JavaScript, directly to the client. Static files are stored in a directory called “static” in the root of the application.

Here is an example of serving a static file:

from flask import Flask, send_from_directory
app = Flask(__name__)

@app.route("/style.css")
def serve_css():
return send_from_directory("static", "style.css")

if __name__ == "__main__":
app.run()

In this example, the serve_css function serves the “style.css” file from the “static” directory.

Extensions

Flask has a modular design, allowing you to add functionality through extensions. Examples include Flask-SQLAlchemy for database support and Flask-WTF for form handling.

Here is an example of using Flask-SQLAlchemy:

from flask import Flask
from flask_sqlalchemy import SQLAlchemy

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

class User(db.Model):
id = db.Column(db.Integer, primary_key=True)
username = db.Column(db.String(80), unique=True, nullable=False)
email = db.Column(db.String(120), unique=True, nullable=False)

def __repr__(self):
return f"User('{self.username}', '{self.email}')"

@app.route("/")
def home():
user = User.query.first()
return f"Hello, {user.username}!"

if __name__ == "__main__":
db.create_all()
app.run()

In this example, the application uses Flask-SQLAlchemy to define a User model and interact with a SQLite database.

Further Reading