Flask Tutorial [1]
If you want to learn flask by developing a project by yourself, this tutorial will be helpful to you.
This tutorial covered with
- Flask introduction
- How Flask works
- How to use Flask Plugin
- Flask-SQLAlchemy
- Flask-WTF
- Flask-Bootstrap
- Install a Python 3.6 up interpreter
And we are going to use these things to create a simple posting web application
Prerequired
- Basic Python knowledges
- Basic shell commands (cd, mkdir, rm….)
- Basic Object Oriented Program knowledges
- Maybe some HTML basis
Flask Introduction
Flask is a web framework written in Python. And it’s micro framework, which means it doesn’t have too many out-of-the-box features, such as ORM, Form validation functions, etc…. Everything is depending on what you want to use. Compare to Django (Another Python web framework, which has a lot built-in funtionalities.), Flask is more freedom. And you can also find many useful plugin of Flask, like Flask-SQLAlchemy, which intergrates SQLAlchemy into Flask.
But how can we get started. Let’s dive into the next part.
Set the developement environment for Flask
We have to set an virtual environment for our project first.
Why we need to use the virtual environment? Well, this is because if we just pip install
something without any setup beforehand, it will install the packages into global environment which makes us hard to controll our packages version in each project also it can lead to the dirty global pip environemnt.
1. Create a virutal environment
So…. how can we create a virtual environment?
-
If you are on Windows, just go to the path where you want to develop the project and type
python -m venv venv
in terminal of that path. -
If you are on Linux or MacOS, you can just go into the project folder and type
python3 -m venv venv
2. Activate the virtual environment
And after we made a virutal environment, you will see a folder called venv
but now it is not usable because we have to activate it.
-
Windows: Type
\venv\Scripts\activate
to activate the environment -
Linux & MacOS: Type
source ./venv/bin/activate
After doing so, you will see something like the text I framed in front of your promt. (Don’t be worried if yours shows different)
3. Install Flask
After activated the virtual environment, we can install the packages and them will just be installed inside this virtual environemnt.
Type pip install flask
inside this virtual environment
Then we create a file called app.py
inside this directory
And we can start to develop our web application in this file
Add these codes to file
from flask import Flask
app = Flask(__name__)
@app.route('/')
def index():
return "<h1>Hello My First Flask Web App !!!</h1>"
And type flask run
in the project root directory
And you can go to localhost:5000
in your browser