Flask
Flask is a lightweight, Python-based web framework that is used to build Python based Web applications.
Install Flask
To use Flask, you first have to install it! You should also have Python installed as a prerequisite.
You can follow the below steps by first creating a virtual environment for your project.
From the command line run the below command:
pip install flask
First Flask App
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello_world():
return "Hello World!"
if __name__ == "__main__":
app.run()
Flask Class
The 'app' is an instance of Flask class. The Flask object is a WSGI (Web Server Gateway Interface) application that is the main entry point for your web application. This object acts as a central registry for the view functions, the URL routing, template configuration and more.
Definition of some of these terms:
- View Function: A view function (a.k.a view), is a Python function that receives an HTTP request and returns an HTTP response.
- URL Routing: Ability to receive requests at certain URL end points and route them to a specific function. In this example the
@app.route("/")decorator configures the Flask object to route all root invocations of the application to the hello_world() function - Template Configuration: Flask uses Jinja2 as its default template engine. No template is used in the hello world example above but you will see that in the next one.
The Flask class is instantiated with the name of the application's module or package. This is why we pass the __name__ variable, as it tells Flask where to look for resources like templates and static files.
Here is the init definition from the open source Flask code and as you can see the only required attribute is import_name:
def __init__(
self,
import_name: str,
static_url_path: t.Optional[str] = None,
static_folder: t.Optional[str] = "static",
static_host: t.Optional[str] = None,
host_matching: bool = False,
subdomain_matching: bool = False,
template_folder: t.Optional[str] = "templates",
instance_path: t.Optional[str] = None,
instance_relative_config: bool = False,
root_path: t.Optional[str] = None,
):
Are you wondering why there is a colon and data type declared in the parameter list? That is because this project is written using Python's type hints.
Also the following:
- Default templates folder is 'templates'
- Default static files folder is 'static'