Python Web Applications With Flask - Part II

2013-12-03

Welcome back to the Flask-Tracking development series! For those of you who are just joining us, we are implementing a web analytics application that conforms to this napkin specification. For all those of you following along at home, you may check out today's code with:

$ git checkout part-2

or you may download it from the releases page on Github. Those of you who are just joining us may wish to read a note on the repository structure as well.

Housekeeping

To quickly review, in our last article we set up a bare-bones application which enabled sites to be added and visits recorded against them via a simple web interface or over HTTP.

Today we will add users, access control, and enable users to add visits from their own websites using tracking beacons. We will also be diving into some best practices for writing templates, keeping our models and forms in sync, and handling static files.

From single to multi-package.

When last we left our application, the directory structure looked something like this:

flask-tracking/
    flask_tracking/
        templates/    # Holds Jinja templates
        __init__.py   # General application setup
        forms.py      # User data to domain data mappers and validators
        models.py     # Domain models
        views.py      # well ... controllers, really.
    config.py         # Configuration, just like it says on the cover
    README.md
    requirements.txt
    run.py            # `python run.py` to bring the application up locally.

Migrating your Django Project to Heroku

2013-11-05

In this tutorial, we'll be taking a simple local Django project, backed by a MySQL database, and converting it to run on Heroku. Amazon S3 will be used to host our static files, while Fabric will automate the deployment process.

The Project is a simple message system. It could be a todo app or a blog or even a Twitter clone. To simulate a real-live scenario, the Project will first be created with a MySQL backend, then converted to Postgres for deployment on Heroku. I've personally had five or six projects where I've had to do this exact thing: convert a local Project, backed with MySQL, to a live app on Heroku.

Setup

Pre-requisites:

  1. Read the official Django Quick Start guide over at Heroku. Just read it. This will help you get a feel for what we'll be accomplishing in this tutorial. We'll be using the official tutorial as a guide for our own, more advanced deployment process.
  2. Create an AWS account and set up an active S3 bucket.
  3. Install MySQL.

Let's begin:

  1. Start by downloading the test Project here, unzip, then activate a virtualenv:

    $ cd django_heroku_deploy
    $ virtualenv --no-site-packages myenv
    $ source myenv/bin/activate
    
  2. Create a new repository on Github:

    $ curl -u 'USER' https://api.github.com/user/repos -d '{"name":"REPO"}'
    

    Make sure to replace the all caps KEYWORDS with your own settings. For example - curl -u 'mjhea0' https://api.github.com/user/repos -d '{"name":"django-deploy-heroku-s3"}'

  3. Add a readme file, initialize the local Git repo, then PUSH the local copy to Github:

    $ touch README.md
    $ git init
    $ git add .
    $ git commit -am "initial"
    $ git remote add origin https://github.com/username/Hello-World.git 
    $ git push origin master
    

    Be sure to change the URL to your repo's URL that you created in the previous step.

  4. Set up a new MySQL database called django_deploy:

    $ mysql.server start
    $ mysql -u root -p
    Enter password: 
    Welcome to the MySQL monitor.  Commands end with ; or \g. Your MySQL connection id is 1
    Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
    mysql>
    mysql> CREATE DATABASE django_deploy;
    Query OK, 1 row affected (0.01 sec)
    mysql>
    mysql> quit
    Bye
    
  5. Update settings.py:

    DATABASES = {
    'default': { 
        'ENGINE': 'django.db.backends.mysql', 
        'NAME': 'django_deploy',                     
        'USER': 'root',
        'PASSWORD': 'your_password',
    }
    }
    
  6. Install the dependencies:

    $ pip install -r requirements.txt
    $ python manage.py syncdb
    $ python manage.py runserver
    
  7. Run the server at http://localhost:8000/admin/, and make sure you can log in to the admin. Add a few items to the Whatever object. Kill the server.

Generating Code Documentation with Pycco

2013-10-11

As developers we love to write code, and even though it makes sense to us at the time, we must think of our audience. Someone has to read, use, and/or maintain said code. It could be another developer, a customer, or our future selves, three months later. Even a beautiful language like Python can be difficult to understand at times. So as good programming citizens who care deeply about our fellow coders (or more likely because our boss wants us to) we should write some documentation.

But there are rules:

  1. Writing documentation must not suck (i.e. we cannot use MS Word).
  2. Writing documentation must be as effortless as possible.
  3. Writing documentation must not require us to leave our favorite text editor / IDE.
  4. Writing documentation must not require us to do any formatting or care at all about the final presentation.

This is where Pycco comes in:

"Pycco" is a Python port of Docco: the original quick-and-dirty, hundred-line-long, literate-programming-style documentation generator. It produces HTML that displays your comments alongside your code. Comments are passed through Markdown and SmartyPants, while code is passed through Pygments for syntax highlighting.

So basically that means that Pycco can auto-generate decent looking code documentation for us. Pycco also adheres to the four rules of code documentation stated above. So what's not to love? Let's jump into to some examples of how to use it.

For this article, I've started off with a simple TODO app written in Django, which you can grab from the repo. The app allows a user to add items to a list and delete them upon completion. This app probably isn't going to win me a Webby, but it should serve the purpose for this article.

Please note, the files in the repo already contain the final code, already documented. You can still create the seperate documented files though, so feel free to clone the repo and follow along with me.

An Effective Sales Page with Bootstrap 3

2013-10-01

What originally was a 2-part series on Bootstrap has shifted to three parts with the addition of this blog post by William Ghelfi. You can grab the final styles/pages from this repo.

In the first post, we took a look at the basics of Bootstrap 3 and how to design a basic web site. Let's take it a step further and create a nice sales landing page.


One of the most common myths about Bootstrap is that you can't actually use it for anything so different and highly specialized as, say, a sales page.

And that's what it is. A myth.

Let's debunk it together in the best possible way: building it.

Highly specialized pages are highly specialized

Successful sales pages follow precise rules. I don't know them all, and I'm not going to tell you everything there is to learn about the ones I know.

Instead, I'll try to reduce them to little effective pills you can start experimenting with.

Attention grabbing and first steps

Integration testing with pyVows and Django

2013-09-23

pyVows' Series:


If you've been following this series (part 1, part 2) you should now have a basic understanding of what pyVows is all about and how it can be used for asynchronous test execution for a Django project. We will continue in this final article of the three part series to explore how pyVows can be used for integration testing django and testing of django models.

There is much debate across the web about unit testing as it pertains to models. According to the most rigid definition a unit test shouldn't rely on a database being around as that means you are technically doing an integration test. I personally am not so rigid on the definition and tend to be more pragmatic. In other words, if it makes it easier / quicker to write tests with a database back end and you can still achieve stable, reusable tests with good coverage than I'm all for it.

One of the biggest (and most valid) arguments against using an actual database in unit tests is that they are slow. While that is true, you will see in this article that running your tests asynchronously against a multi-threaded database can help to improve performance of the unit test runs. While it's true testing against a live database backend will probably never be as fast as testing without the database we can make it reasonably fast with asynchronous testing.

Furthermore, by including the database back-end we can actually improve test coverage by validating that our database queries are actually performed successfully. Because when we hit the database we can test things like database constraints or that we are not trying to put a VARCHAR in a NUMBER field. And when we don't hit the database with a "pure" unit test, we can't verify these things. Anyways, lets get started.

A "Pure" unit test for a Django Model

Starting with the sample login application we have been using in this series, lets write a simple model to take us through some examples. Add the following code to /accounts/models.py:

class Account(models.Model):
    username = models.CharField(max_length=100)
    password = models.CharField(max_length=100)