• Flask + Angular Full-Stack Tutorial Part 2 - VirtualEnvs (5-16-16)


    1. Intro
    2. Python
    3. Is This Tutorial Difficult?
    4. Starting Python
    5. Virtual Python Environments
    6. Installing VirtualEnvWrapper
    7. VIM
    8. Using VirtualEnvWrapper
    9. Wrapping Up


    In Part 1, we created a Cloud9 workspace and reviewed the basics of the bash terminal. In this section, we are going to learn about installing different Python versions using virtual environments and review how to use VIM.


    For our server-side language, we will be using Python. The backend of our app does not have to be written in python, it could be written PHP or Javascript or some other language. Python is good since it offers a lot of flexibility in terms of what tools you can use to build your backend, and since it is a language that many great startup software companies use. One such tool in Python we’ll be using is called Flask, a micro-framework (which means that Flask has a lot functionality built-in, but it is up to the programmer to include the specific dependencies and extensions they need for each app).

    Courtesy of CodingVC

    Is This Tutorial Difficult?

    Sometimes yes, but mostly no. It depends on what your programming backgroud is: if you are new to web app programming, it will seem harder than if you’ve done related web programming before. This tutorial will also be easier if you have previous Python experience, but that is not a requirement. To maximize understanding, we will be examining every line typed into code files and the terminal in detail. That being said, we will be learning how to write Python as it relates to web programming, not necessarily focusing on learning Python the language itself. It might be a good idea to do a basic Python tutorial first before proceeding if you are new to the language. Places where I introduce new Python concepts in this tutorial will be accompanied by links to the official Python documentation, which is relatively easy to read and thorough in explanation of topics. I will also include links to the official docs of any new software we learn about as we go along.

    Note: reading the official documentations of the software from links provided in this tutorial is optional, but they are provided to help minimize confusion and provide additional insight.

    Starting Python

    In a bash terminal, type:


    If Python is installed on your system (it comes pre-installed on Cloud9 and in many linux distributions), you should then see something similar to this (If your system tells you that Python is not installed, you can download version 3.4.3, which is what we will be using, from here):

      Python 2.7.6 (default, Jun 22 2015, 17:58:13) 
      [GCC 4.8.2] on linux2
      Type "help", "copyright", "credits" or "license" for more information.

    This provides information about the default installation of python and enters you into Python’s interactive mode. The > > > is the primary prompt, which lets you type in python-specific commands, similar to how you type in commands in the regular bash terminal. You can execute Python statements while in interactive mode at the prompt, such as:

      print ("whoohoo")

    which (predictably) prints whoohoo. We won’t be using interactive mode for much during the tutorial but it is useful for a few things such as checking what version of python you are currently using. To exit interactive mode, type:


    This returns you to the regular bash terminal. We could get started coding right away, but you may have noticed that I mentioned above we will be using Python version 3.4.3. In Cloud9, our Python interactive mode info says that the default version we are using is 2.7.6. But we don’t need to uninstall version 2.7.6 and install 3.4.3, because there is a much easier solution that will let us have BOTH installations at our disposal: virtual python environments.

    Virtual Python Environments

    Using a Virtual Python Environment (or “virtualenv”) lets us create a local (not system-wide) Python installation with a Python version that we specify. This is very cool, because it lets the python installations for each of our projects that have virtualenvs be independent. If we did not use virtualenvs, and instead relied on the default python installation for our projects, things might start out OK and nothing would break initially. But let’s say that we install/upgrade a package or even upgrade Python itself for a more recent project, and then we go back to discover that upgrading Python has broken our older projects that used the older version. That would be very frustrating. To give you a real-world example of where differnt versions of Python will cause things to break, consider this line of code in interactive mode:

      print "whoohoo"

    In the Python 2.x branch versions, this syntax is perfectly valid and will print “woohoo” as expected. But if you try to execute the same line in python 3.x versions, you will get an error:

        File "\<stdin\>", line 1
          print "woohoo"
      SyntaxError: Missing parentheses in call to 'print'

    :cold_sweat: What!?! Why did that print statement work the first time but not the second? Because the Python developers changed the syntax of certain functions in the 3.x branch (in an effort to continuously improve the language :wink: ). Now imagine that error, and many others, spread throughout the dozens of files and thousands of lines of code in an app after making a seemingly innocent upgrade to Python or an app dependency. By using virtualenvs, we can avoid that sort of nightmare.

    Installing VirtualEnvWrapper

    To use virtual Python environments we can use one of two popular python packages: “virtualenv” or “virtualenvwrapper”. I prefer to use virtualenvwrapper, since it adds some functionality to the virtualenv package making it easier to work with, so we will be installing that. To install things in Python, we use the “pip” command, which stands for “Pip Installs Package” or “Pip Installs Python”. Pip will handle the installation of packages found in the Python Package Index (PyPi). At the bash terminal, type:

      sudo pip install virtualenvwrapper

    The “sudo” part means “Super User DO”, which is a linux command that lets us run pip as a super user (with elevated privileges). We need this part since virtualenvwrapper will try to install itself into a location in the /usr directory, which requires super user permissions to alter. If the install was successful, you should see several lines of messages related to virtualenvwrapper and its dependencies being downloaded and installed. The last few lines or so of output from the pip install command should be similar to this:

      Installing virtualenv-clone script to /usr/local/bin
        Found existing installation: six 1.5.2
        Not uninstalling six at /usr/lib/python2.7/dist-packages, owned by OS
      Successfully installed virtualenvwrapper stevedore virtualenv-clone virtualenv six pbr
      Cleaning up...

    Depending on your linux/python installations, it may be necessary to add the following line to your ~/.bashrc file in order to make virtualenvwrapper commands work (you can test this by trying out the mkvirtualenv command explained futher below):

      source "/usr/local/bin/virtualenvwrapper.sh"

    Close and reopen the terminal to set the changes (or refresh Cloud9 if reopening the terminal does not work). Detailed explanation on what a .bashrc file is and how to edit it below:


    In linux, a .bashrc file is a file containing commands that runs whenever you open a new terminal (or instance of Bash that you start). Adding a source command with the path to the virtualenvwrapper script file as its argument to the .bashrc file tells linux to load the contents of that file when the terminal starts, making the virtualenvwrapper commands available for us to execute. In order to edit the file, we're going to use a text editor called VIM, which comes preinstalled on Cloud9 and many linux distributions (either that or its older brother, VI). VIM lets us edit files right in the terminal and does not have nearly as much unnecessary "fluff" as most text editors, which is very convenient for programming. We will very briefly go over how to create and edit files in VIM, although if you have never used VIM before I highly recommend reading some of the officialy recommended VIM tutorial.

    You can create a new file from any directory you are currently in by typing into the terminal:

      vim test.txt

    This command means "open the file test.txt if it exists, otherwise create a new file if it does not exist". Your terminal display will shift from the regular command-prompt view to VIM's text editor view.

    All About Speed

    This is the point where VIM can be tricky for people who have never used it before: almost all of VIM's useful commands are performed in keystrokes that activate/deactivate certain editing modes, move the cursor around the file, or some other function. In VIM, you can neither point and click to move the cursor to where you want to type, nor can you click to save the document and exit. This is a good thing, because, to quote the movie :checkered_flag: Talladega Nights :checkered_flag:, VIM "is all about speed - hot, nasty, badass speed." Performing keyboard shortcuts to operate all of VIM means your hands never have to leave the keyboard, decreasing the amount of time needed to do things like move around, save, edit, etc. Here is a list of important VIM commands, although we only need to know a handfull to do basic file editing.

    In the VIM text editor view, press "i". This will enter us into "INSERT" mode, which is displayed at the bottom of the text editor view. While we are in insert mode, we can add text by typing normally and remove text with the backspace key. Although there are better ways of positioning the cursor in VIM, you can move the cursor where you want it go with the arrow keys. Type "test" and push the escape key. The INSERT at the bottom of screen should disappear, meaning that we are no longer in insert mode. Now to save the file, we are going to type a VIM command. Type the following and push enter:


    This means "Write, Quit", and it tells VIM to save the file and exit back to the regular bash terminal. Quick recap:

    • to open or make a new file, use "vim filename"
    • to edit a file inside VIM, push escape then push "i" to enter insert mode
    • to save a file, press escape and type :w
    • to quit VIM, press escape and type :q
    • to save a file and quit VIM with one command, press escape and type :wq

    Let's use VIM to add the "source" line for virtualenvwrapper to our ~/.bashrc file:

      vim ~/.bashrc

    Go to the bottom of the file and type on a new line:

      source "/usr/local/bin/virtualenvwrapper.sh"

    Save the file and exit VIM. Close and reopen the terminal to set the changes (or refresh Cloud9 if reopening the terminal does not work).

    Using virtualenvwrapper

    Now we are ready to make a virtual Python environment. At the terminal, type:

      mkvirtualenv pet-app -p python3.4

    This command means “MaKe a new VIRTUAL ENVironment called ‘pet-app’ with Python version 3.4”. Once you execute the command, you’ll notice the name of the virtual environment enclosed in parentheses is now in front of the command prompt:

    (pet-app) prowland:~/workspace $

    This means that the virtual environment pet-app is active. Now type in the terminal:


    Executing this command will enter you into Python interactive mode with Python 3.4.3 (or a version on the 3.4.x branch) listed as the current Python installation. Pretty neat stuff! Now if we want to deactivate the virtual environment and return to the regular bash terminal, exit() Python interactive mode and simply type into the terminal:


    Executing this command will remove the name of the virtual environment you were working on from the front of the command prompt, signifying it has been deactivated. If we forgot the name of our virtual environment and want to see a list of virtualenvs we have created, type into the terminal:


    This is similar to the linux command “ls”, except it will list all of the virtualenvs we have created. Let’s use our pet-app virtualenv again by typing:

      workon pet-app

    The command prompt should change to reflect that we are now using the pet-app virtualenv.

    Wrapping up

    Since we have virtualenvwrapper installed, we can start installing the software packages that will be dependencies for our app (and as long as we have our virtualenv activated when we install the packages, they will be independent from other virtualenvs and stay only in our current virtualenv, which is very useful). In part 3, we will install Flask and learn how to write a very basic app.