Building tiny web services lightning fast with heroku and python
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
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
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 add .
git commit -m "Initial commit"
heroku create --stack cedar
heroku addons:add shared-database
#push to heroku and open in a browser git push heroku master heroku open
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
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(":").replace("//","") password = os.environ["DATABASE_URL"].split(":").split("@") host = os.environ["DATABASE_URL"].split(":").split("@").split("/") dbname = os.environ["DATABASE_URL"].split(":").split("@").split("/") 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 .
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