I often build scripts that need to have some kind of network persistance layer or tiny web services that munge files or json or whatever. When I have to do this I don't immediately reach for rails, or any of these other super heavyweight frameworks. The reason for this being that I don't need all the extra super powers those frameworks come with, and I can instead deal with a little more of the manual stuff because I'm not going to be spending much time doing any of that anyway. This article will try to serve as a guide to setting up tiny python projects on heroku. Using the Notely Server as an example.

Set up your project

Make sure you've got the heroku gem,foreman and venv installed and run the following commands #create diriectory mkdir appname && cd appname #create a virtual python environment that won't screw with your global one virtualenv venv --distribute #use python environment and install dependancies source venv/bin/activate pip install flask pip install psycopg2 #create a base app.py file wget http://samphippen.com/app.py -O app.py #create files necessary for heroku to run pip freeze > requirements.txt echo "web: python app.py" > Procfile #add everything into git wget http://samphippen.com/pyapp.gitignore -O .gitignore git init git add . git commit -m "Initial commit" #setup heroku heroku create --stack cedar heroku addons:add shared-database
#push to heroku and open in a browser git push heroku master heroku open

Change something

In app.py, you can see a route that matches "/" and returns the text 'Hello World!'. This is the base point for our app, use the Flask docs to change something, run the server with forman start and see what it's doing locally before pushing back to heroku

Persist stuff

When you ran the giant blob of commands up there, you added a database to heroku using postgres. You can interface with this database by using a psycopg connection. To create one you can use the following python snippet

username = os.environ["DATABASE_URL"].split(":")[1].replace("//","")
password = os.environ["DATABASE_URL"].split(":")[2].split("@")[0]
host = os.environ["DATABASE_URL"].split(":")[2].split("@")[1].split("/")[0]
dbname = os.environ["DATABASE_URL"].split(":")[2].split("@")[1].split("/")[1] 
conn = psycopg2.connect(dbname=dbname, user=username, password=password, host=host) 

once you've got a database connection you can query it using Psycopg's interface .

Conclusions

This is, I'm pretty sure, the fastest way to get from nothing to a running web service with a database that you can use to build stuff in existence at the moment. For me it's been incredibly useful to be able to throw these services up. I wouldn't have been able to do that with heroku.

Let me know if you've done something cool with this by mailing me