How to host your Django apps on Azure for free

Microsoft Azure is a feature-rich cloud computing platform. It’s designed to handle the largest projects you can imagine, with datacenters all over the world. You can develop on OSX, Linux, or Windows. You can run Linux and Windows virtual machines, distribute media files through a CDN, create a VPN between Azure and your own datacenter, move virtual machines between Azure and your own datacenter, host a turnkey backend for your mobile apps, use relational and NoSQL databases, and more. Open source SDKs are available for Python, Node.js, Java, PHP, and .NET.

This post describes how to host Django projects in Azure Web Sites, a Platform as a Service (PaaS) offering. As with other PaaS offerings, you the developer concentrate on writing your app and not on infrastructure issues. You deploy to Azure Web Sites, and Azure handles things such as scaling out when your traffic increases, operating system patches, backups, and redundantly storing your data to protect against disasters. PaaS allows developers to focus on their app, and leaves routine maintenance issues to the platform. This post assumes you’re on OSX or Linux, and also using git. If you’re on Windows, use the free Python Tools for Visual Studio.

Here's a screencast which quickly goes over the steps in this post and shows the end result:

 

1. Get a free Azure account

Three options come to mind for getting an Azure account. The best option for many is to enroll in BizSpark. This program from Microsoft gives $150 per month in Azure credits to startups to use as they like. In addition to this Azure benefit, BizSpark members also get MSDN Ultimate subscriptions. Eligible startups need to be in the software business, be privately held, be under 5 years old, and be making less than US$ 1M in revenue. You don’t need to be a legal entity such as a partnership or corporation. Apply at https://www.bizspark.com and the BizSpark team will look at your application. This could take a few days.

If you don’t qualify for BizSpark, you can apply for one year of $150 per month in Azure credits through a program designed for open source developers. Of course, both Python and Django are open source. This offer also gives you a MSDN Ultimate subscription. To apply for this program, email opensource@microsoft.com and tell us how you plan to use open source on Azure. The team is also on Twitter, @OpenAtMicrosoft.

Lastly, you can just use a regular Azure account. All Azure accounts come with 10 free Web Sites and 10 free Mobile Services. Currently the Azure landing page emphasizes the free trial offer of $200 in usage or 30 days, whichever comes first. The free trial applies to everything in Azure: virtual machines, the CDN, directory services, and everything else. However, even after your free trial expires you still get 10 free Azure Web Sites and 10 free Mobile Services. This might not be obvious on the current landing page. You need a credit card to sign up for an Azure account, but the card will not be charged unless you explicitly remove the spending limit.

Pro-tip: You'll be asked for a phone number which will be used to verify your account. This seems to fail when Google Voice numbers are used. Try using a regular phone number instead.

 

2. Run your Django project locally with SQLite

To proceed, you need to have a Django project running locally on your system. Have it working with a local SQLite database. You should be able to successfully run the app with python manage.py runserver. For this post, I’ll be using code from the Django tutorial which creates polls and keeps track of answers. Here’s what my directory structure looks like:

 db.sqlite3
manage.py
polls/
tutorial/

 

3. Provision an empty Azure Web Site

Log onto the portal. Click the New button in the lower left corner. Select Compute –> Web Site –> Quick Create. Choose a host name, and make sure you create your site in a region close to you. I use West US.

image

 

4. Provision a ClearDB MySQL database

You have many options for databases on Azure. This post will use MySQL. Microsoft partners with ClearDB to offer MySQL as a service on Azure. ClearDB handles tasks such as backups and scaling. You get a 20 MB database for free. Create a MySQL database by clicking on Linked Resources. Complete the wizard, making sure you create the database in the same region as your website from step 3, and then click on your database’s name:

SNAGHTML24c3423

This brings you to a management site on https://www.cleardb.com. In the ClearDB portal, click on Endpoint Information and copy your Hostname, Username, and Password. Then click on Dashboard. Download these 3 SSL certificates: ClearDB CA Certificate, Client Certificate, and Client Private Key. You’ll likely need to right-click on the Download link and choose Save target (or link) as.

The Client Private Key contains an embedded password. However, we need this certificate in a format with that stripped out. Use openssl to make the conversion, and note that your filenames will be different:

 openssl rsa –in client-key.pem –out client-key-nopass.pem

Save the 3 SSL certificates in your app's folder

 

5. Edit settings.py to switch to MySQL

To convert from SQLite to MySQL, edit your app’s settings.py file:

 DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'DATABASE_NAME_GOES_HERE',
        'USER': 'USERNAME_GOES_HERE',
        'PASSWORD': 'PASSWORD_GOES_HERE',
        'HOST': 'HOSTNAME_GOES_HERE',
        'PORT': '3306',
        'OPTIONS': {'ssl': {'ca':'tutorial/cleardb-ca.cer', 
            'cert':'tutorial/client-cert.cer', 
            'key':'tutorial/client-key-nopass.cer'},},
    }
}

I placed the 3 SSL certificates in the app’s folder. Make sure you use the certificate key which you processed with openssl in step 4 to remove the embedded password.

You also need to install the MySQL adapter on your system. A portion of the adapter is written in Python, and a portion is compiled for the specific platform you’re on. If you're on OSX, the easiest way forward is to use Homebrew to install MySQL with brew install mysql. You also need Xcode installed so you have a compiler and headers. If you're on Linux, just install MySQL and the development tools through your distribution's package repository. After you have MySQL and a development environment set up on either OSX or Linux, run pip install MySQL-python. Windows users should just install the adapter through WebPI.

Since you’ve switched from SQLite to MySQL, you need to run python manage.py syncdb. This creates your app’s tables on MySQL in Azure. Then, run your app locally and save some data. It will be saved in Azure.

 

6. Set up MySQL Workbench

This step is optional, but worth it. MySQL Workbench is a desktop client from Oracle which talks to any MySQL database, including your database in Azure. Download it from Oracle, and configure it with the hostname, database name, username, password, and SSL certificates you used in step 5. Connect to your database, and you should be able to see your app’s tables and data you entered after running your project in step 5.

 

7. Install django and other modules into a local site-packages directory

The Azure Web Sites platform already contains Python, but it does not contain Django or other modules since versions change so quickly. If you include Django and other modules you’ll need in your project, they’ll be available for you on Azure. Create a directory called site-packages in the same level as your app's folder, and install your modules there. For example:

 mkdir site-packages
pip install --target site-packages django
pip install --target site-packages pytz

In a future release, you’ll be able to simply include requirements.txt, and Azure will install the modules you need.

In step 5, you installed MySQLdb on your system. Remember that it contains both Python and platform-specific code. Since Azure Web Sites run on Windows, you’ll need a Win32 version of MySQLdb. Installing this in the future will be smooth and will use requirements.txt, but here’s how to do it right now. If you don’t have a Windows PC handy, you can download a Win32 version from my OneDrive. After you manually copy those files into into site-packages, it should look like this:

 django/
Django-1.6.3.dist-info/
MySQLdb/
pytz/
pytz-2014.2-py2.7.egg-info/
_mysql.pyd
_mysql_exceptions.py
_mysql_exceptions.pyc
_mysql_exceptions.pyo

Of course, yours will only contain pytz if your app requires it. Mine does. Here’s a good time to mention that you need to move a module out of a Python egg and put it in site-packages. You can’t just include the egg right now.

Be sure to add and commit site-packages to your git repo. When finished, my project looked like this:

 db.sqlite3
manage.py
polls/
site-packages/
tutorial/

 

8. Configure your Azure Web Site

We’re almost done. You need to create 3 key/value pairs in the Azure Web Site environment where your app will run, and you also need to configure the wfastcgi handler. In the Azure portal, click on the Configure tab and scroll down to App Settings. Add these 3 key/value pairs:

 DJANGO_SETTINGS_MODULE    tutorial.settings
PYTHONPATH                D:\home\site\wwwroot;D:\home\site\wwwroot\site-packages
WSGI_HANDLER              django.core.handlers.wsgi.WSGIHandler()

My starting app is called tutorial, so DJANGO_SETTINGS_MODULE is set to tutorial.settings. Your app name will of course will be different.

Scroll down a little further to Handler Mappings and add this:

 EXTENSION                 *
SCRIPT PROCESSOR PATH     D:\python27\python.exe
ADDITIONAL ARGUMENTS      D:\python27\scripts\wfastcgi.py 

 

9. Deploy to Azure

We’ll use git to push your code to Azure. You can push directly from a local repo, GitHub, BitBucket, Dropbox, TFS, or another external repository. In the portal, go to your site's Dashboard and click Set up deployment from source control. In the wizard, select where your repo lives. It’s pretty straightforward. A cool thing about using BitBucket or GitHub is that when you push to a branch there, Azure will pick up your code and deploy it. After you’ve deployed to Azure, simply browse to your site. You’re done!

 

Next steps

If you upgrade your site from the free tier, you can do things such as autoscale to handle traffic bursts, use a custom domain name, and incorporate SSL. Of course your BizSpark credit can be used for this.

Take a look at the cross-platform command line interface to Azure. First install Node.js, then run npm install -g azure-cli. Then run azure account download to download your account's publishing settings. With the Azure CLI, you can create Web Sites, create deployment scripts, create Virtual Machines, start and stop services, and more. All of this can be scripted too.

If you need to see your log files, check out another post from me: Troubleshooting Azure Web Sites.

 

Conclusion

With a PaaS offering, you shouldn’t have to care about the underlying platform. Azure Web Sites run on IIS on Windows, but OSX or Linux users can use it without problem. If you think of any features you’d like added, or something you’d like changed, definitely get in touch with me. We’re always looking for ways to improve things and value customer feedback above everything else. Also, if you end up permanently hosting a Django project on Azure, please let me know. Email me, or hit me up on Twitter @mh415.