Flask Introduction
What is Flask?
The Python micro framework for building web applications.
Flask is a Python framework for building web applications. It is lightweight and modular, and is a great tool for building simple websites. In this guide, we will build a simple website using Flask.
Knowledge Required
Basic familiarity with Python, HTML/CSS and SQL will be needed to build this website and resources can be found here:
Getting Started
Installing flask
To install Flask, you can use pip, which is the package manager for Python. Run the following command in your terminal:
Basic Flask App
Flask applications are relatively simple to create. Here is a basic Flask app that displays “Hello, World!” on the webpage:
To run the Flask app, save the code in a file called app.py
and run the following command in your terminal:
This will start a development server on your local machine, and you can access the website by visiting http://127.0.0.1:5000 in your browser. You should see the text “Hello, World!” displayed on the webpage.
So how does this work?
-
Import the
Flask
class from theflask
module.This imports the Flask class from the Flask module, which is used to create a Flask application.
-
Create the Flask app.
This creates a new Flask application instance. The
__name__
argument is a special Python variable that is set to the name of the current module. This is used by Flask to determine the root path of the application. -
Define a route.
Flask uses things called decorators
@app.route('/')
to map functions to different webpages (routes). In this case, we are mapping theindex
function to the root URL/
. -
Define the
index
function.When a user visits the root URL, the
hello
function is called, and it returns the textHello, World!
. For more complex applications, you can return HTML or JSON data.