The code for this project is located on github: https://github.com/bilalaslam/django-heroku-addon
Herok has a fantastic add-on marketplace that gives developers like me a set of services we can use to build apps:
If you're a startup or a small developer, getting featured on the Heroku marketplace can mean extra cash in your bank account every month. Who would say no to that? In this blog post, I'm going to walk you through writing a Heroku addon in Python and Django. Heroku has excellent documentation on their addon program, so I'm going to try my best not to regurgitate it here.
For the purposes of this blog post, imagine that you are a small startup which is creating the next generation cloud key-value store. Let's call it Guples (great tuples .. I guess). The Guples app is really simple - each user gets a Guple Store, which is protected by a secret key. If the user provides the secret key, she can get and set values for keys.
Our goal is to take our existing app and add a few view methods, which will allow Heroku users to provision our addon.
1. Setup your workstation
git clone my repo. This app is already structured for deployment on Heroku.
Install the 'kensa' gem using your favorite technology (gem install or bundler). This gem simulates the Heroku API so you can do your development 100% locally without ever deploying to production!
2. Add routes to urls.py
Heroku's addon API spec is really simple - it just requires you to implement RESTful methods for a few scenarios: Provision, Deprovision, Plan Change, and SSO. I am using django-reroute to make RESTful routing a little easier.
3. Add Provision, Deprovision and Plan Change views
These views are dead simple. They check if the request is authorized and, if so, they create or delete the resource, or change the plan. Provision returns some JSON to indicate the ID of the resource that was just provisioned, as well as some config variables that will be available via heroku config. So how we do do auth? Since doesn't doesn't have built-in support for basic auth (something I miss from Sinatra!), we have to inspect the HTTP auth header to check if the username and password are correct.
4. Add SSO
SSO is the trickier view to implement. The dosso method encapsulates all the logic - we take the id that is in the request parameters, salt it, append the timestamp and check if it makes the token passed by Heroku. We also have to check if the token has expired. If everything is hunky dorey, we set a few session variables and redirect the user to the landing page where they can manage their resource.
5. Test with Kensa
I love Kensa - it's a little Ruby gem that simulates Provision, Deprovision, Plan Change and SSO calls so you can test your addon locally. Kensa worked like a charm for me - here it shows our Guples addon passing the SSO test:
I hope this helps you get started with your own Heroku addon development.