Flask a web framework that can be used to build web apps with Python. It’s a scaleable Web Framework, it was used to create Pinterest amongst others.
It’s a micro framework, meaning Flask isn’t in the way of your architecture. This is great for making a SaaS app, because you are in full control of everything.
Related course: Python Flask: Make Web Apps with Python
Btw, you can easily Deploy your Flask app
Flask installation
First install Flask, you can do so with pip (the Python package manager). Open a terminal and type the command shown:
pip install flask
That installs the Flask module to your computer. It’s recommended that you do that inside a virtal environment.
If you are a PyCharm user, installation is done a bit differently.
- Open Settings(Ctrl+Alt+s)
- Goto Project Interpreter
- Double click pip, Search for flask
- Select and click install Package
Flask hello world
We’ll create a “Hello world” app for the web. If you load the website url, it will show you the message “Hello world”.
Now let’s build our app! The first thing to do is to import the Flask module.
from flask import Flask |
Then create the app object.
app = Flask(__name__) |
Start the server with:
app.run(host='0.0.0.0', port=5000) |
This starts the server on your computer at port 5000. If you try a port like 80, it will complain because that’s a reserved port.
Finally you’ll want a route (‘/hello’) to display the ‘Hello World’ message.
|
A route maps a web url (in this case ‘/hello’) to a Python function. Whatever the function returns is shown to the user in the browser.
Copy the file below and save as web.py
from flask import Flask |
Start with:python web.py
Python will show:# python web.py
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
This means you have a web server running on port 5000.
Open your web browser and type http://127.0.0.1:5000/hello
This will show you the hello world message.
If you want to put your web app online, you can use PythonAnywhere.
Routes
A Flask web app can have many routes. Recall that a route is a mapping of a web link to a Python function. You defined the route (‘/hello’) and mapped it to a function:
|
That would be /hello
.
If you leave it blank you’ll have the index route /
.
|
You can create any route you want. If you want the /food
route. But it’s important that both the route name and the function name are unique.
|
Routes are one of the key things to remember from this tutorial.