Install pip first.
For python 2.7
sudo apt-get install python-pip
For python 3
sudo apt-get install python3-pip
Install virtual environment
sudo pip3 install virtualenv
Now create a virtual environment
You can also use a Python interpreter of your choice
virtualenv -p /usr/bin/python2.7 /virtualenvspath/
virtualenv -p /usr/bin/python3 /virtualenvspath/
Activate your virtual enviornment
To deactivate virtual enviorment
Let’s start Flask project
We have already get information, how can setup our virtual environment. So let’s create a virtual environment. For this example am using python3 and virtual environment name is flask_demo. Let do that.
virtualenv -p /user/bin/python3.5 /path/flask_demo
Let’s activate virtual environment and install flask.
You can confirm like this:
Am assuming you have already setup pip/pip3, if not please above instructions to setup pip. So let’s install Flask
pip3 install flask
You can confirm with pip freeze command, that basically list down all the packages installed in virtual environment. Here is my pip freeze command output after flask installed.
Click==7.0 Flask==1.1.1 itsdangerous==1.1.0 Jinja2==2.10.1 MarkupSafe==1.1.1 pkg-resources==0.0.0 Werkzeug==0.15.5
Greet ! Let’s create your first Flask project
mkdir myproject cd myproject mkdir app cd app vi __init__.py
Let write some few lines of code in __init__.py under myproject/app folder. This is basically a main file that initialize a flask application.
from flask import Flask # you can choose any name instead app. app = Flask(__name__) from app import routes
Right now project has no any routes file, let’s create that. This file will basically hold url route and related code.
Under the same directory myproject/app/routes.py
from app import app @app.route('/') def index(): return "Welcome to flask demo application"
To complete the application, you need to have a Python script at the top-level that defines the Flask application instance. Let’s call this script main.py, and define it as a single line that imports the application instance.
from app import app
Let’s do last thing but not least. Install one new package that will help to set environment variable that use by flask to start application. The name of the python-dotenv
pip install python-dotenv
Then you can just write the environment variable name and value in a .flaskenv file in the top-level directory of the project
flask run * Serving Flask app "main" * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)