Flask Introduction
This content is not available in your language yet.
What is Flask?
Section titled 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
Section titled Knowledge RequiredBasic familiarity with Python, HTML/CSS and SQL will be needed to build this website and resources can be found here:
Getting Started
Section titled Getting StartedInstalling flask
Section titled Installing flaskTo install Flask, you can use pip, which is the package manager for Python. Run the following command in your terminal:
pip install Flask
Basic Flask App
Section titled Basic Flask AppFlask applications are relatively simple to create. Here is a basic Flask app that displays “Hello, World!” on the webpage:
from flask import Flask
app = Flask(__name__)
@app.route("/")def hello(): return "Hello, World!"
To run the Flask app, save the code in a file called app.py
and run the following command in your terminal:
$ flask run * Debug mode: offWARNING: This is a development server. Do not use it in a production deployment. Use a production WSGI server instead. * Running on http://127.0.0.1:5000Press CTRL+C to quit
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?
Section titled So how does this work?-
Import the
Flask
class from theflask
module.from flask import Flask;This imports the Flask class from the Flask module, which is used to create a Flask application.
-
Create the Flask app.
app = Flask(__name__)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.
@app.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.def hello():return 'Hello, World!'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.