Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Introduction to Flask

What is Flask?

Flask is a lightweight WSGI web application framework in Python. It is designed for simplicity and flexibility, allowing developers to build web applications quickly with minimal boilerplate code.

Key features of Flask include:

  • Lightweight and modular
  • Built-in development server and debugger
  • Support for RESTful request dispatching
  • Integrated support for unit testing
  • Extensive documentation

Flask follows the WSGI (Web Server Gateway Interface) specification, making it compatible with various web servers.

Installation

To install Flask, ensure you have Python installed on your system. You can install Flask using pip:

pip install Flask

To verify the installation, run the following command:

python -m flask --version

Basic Structure

A basic Flask application consists of a single Python file. Below is a simple example:

from flask import Flask

app = Flask(__name__)

@app.route('/')
def hello_world():
    return 'Hello, World!'

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

This code creates a basic web server that responds with "Hello, World!" when accessed at the root URL.

Routing

Routing in Flask allows you to bind URLs to functions. You can create multiple routes for different web pages:

@app.route('/about')
def about():
    return 'About Page'

This example shows how to create an "About" page that responds to the `/about` URL.

Templates

Flask supports Jinja2 templating, allowing you to separate HTML from Python code. Here's an example:

from flask import render_template

@app.route('/hello/')
def hello(name):
    return render_template('hello.html', name=name)

In the `hello.html` template, you can display the `name` variable passed from the route:

<h1>Hello, {{ name }}!</h1>

FAQs

What is the difference between Flask and Django?

Flask is a micro-framework that is lightweight and easy to extend, while Django is a full-fledged framework that includes many built-in features.

Can I use Flask for large applications?

Yes, Flask is suitable for small and large applications due to its modular structure. You can add extensions as needed.

How do I deploy a Flask application?

Flask applications can be deployed using WSGI servers like Gunicorn or uWSGI, and can be hosted on platforms like Heroku or AWS.