DEV Community

Jack Darracott
Jack Darracott

Posted on

Setup a Virtual Python Environment and a new Flask Project on WSL2

This post will guide you through setting up basic local python development environment on a Windows PC using WSL 2.

Click here for steps for setting up WSL 2 and installing the Ubuntu 20.04 LTS distribution.

Install Python

Open Ubuntu 20.04 LTS Terminal:
image

Download available package information

sudo apt-get update
Enter fullscreen mode Exit fullscreen mode

Install python pacakges

sudo apt-get install python3 python3-venv pythonpy
Enter fullscreen mode Exit fullscreen mode

Create Project Environment

You'll want to keep your projects separated, so create a new directory, navigate to it, then set up a python virtual environment.

Create a directory for the project

mkdir python-project
cd python-project
Enter fullscreen mode Exit fullscreen mode

Create a virtual environment for the project

python3 -m venv venv
Enter fullscreen mode Exit fullscreen mode

Activate The Project Environment

You'll need to remember to do this each time you start work on the project.

. venv/bin/activate
Enter fullscreen mode Exit fullscreen mode

If done correctly, your terminal commands should be prefixed with (venv) - indicating you're in the python virtual environment.

Get Started With Flask

Ensuring the project environment has been activated, run the below command to install Flask into the project.

pip install Flask
Enter fullscreen mode Exit fullscreen mode

Now you can create the first script:

touch index.py
Enter fullscreen mode Exit fullscreen mode

Finally, open the project in Visual Studio Code:

code .
Enter fullscreen mode Exit fullscreen mode

Hello World!

Enter the below code into index.py. This will import the flask package you installed previously and store it in the "app" variable.

from flask import Flask

app = Flask(__name__)

@app.route("/")
def home():
    return "Hello World";

if __name__ == "__main__":
    app.run()
Enter fullscreen mode Exit fullscreen mode

Save the file and return to the terminal, you can now use python3 to serve the script, so you can view it in a web browser:

python3 index.py
Enter fullscreen mode Exit fullscreen mode

You'll be prompted with the access URL:
image

Which when accessed via a web browser, displays the return returned in the "home" function:
image

Disclaimer

This was written for a friend in my lunch break. I don't know anything about Flask or Python so do not use for production.

Top comments (0)