Build a Simple Voting App With Flask

Flask

Flask is a micro web framework powered by Python that is designed to make getting started quick and easy. It has the ability to scale up to complex applications.

Flask offers suggestions but doesn’t enforce any dependencies or project layout as opposed to Django. As a developer, it is up to you to choose the tools and libraries you want to use.

We’ll be creating a simple web page with Flask in this tutorial.

Assuming that you have Python installed, next we’ll install a virtual environment so that we can isolate Python dependencies used by different Python projects.

Virtual Environment

The virtual environment is also important when you come across a new Python library that you want to experiment with. A system-wide installation risks messing up other libraries that you might have installed. However, using virtualenv to create a sandbox, comes in handy since you can install and use the library without affecting the rest of your system. This enables you to keep using this sandbox for ongoing development work and you can simply delete it once you’ve finished using it. Either way, your system remains organized.

Install virtualenvwrapper, a set of extensions that makes it easy to use a virtual environment.

We then create and activate a new virtual environment.

Your virtual environment (venv) is now activated. Go ahead and create a directory to host our project.

Install Flask

We finally install Flask using this command:

Let’s go ahead and display stuff on our web page. Open your favorite editor and type in the following in your hello.py file:

We first import Flask class then create the application object on the second line.
@app.route is a decorator that maps the URL(for our case /) to function (home).

Fire up your development server by running:

Navigate to: http://0.0.0.0:81/

and you should see “Hello, World!” on your browser.

In your root directory, create a directory and name it templates. Create a file named hello.html inside templates directory and paste the following code:

Create another directory in the root and name it static. Inside static create two folders css and img to store your stylesheet and images, respectively.

NOTE: Remember to replace the links to images and stylesheet with your own path. E.g replace:

with your own image path.

Learning by Building

Save it and then add the following to hello.py to render the HTML page rather than “Hello World!“.

Restart your server by pressing Ctrl + C  then running:

and Voila your app is now up and running!!

Related Posts