App Engine Datastore API – Tutorial 1
Posted: October 11th, 2009 | Author: Giv | Filed under: Python, Tutorials | No Comments »I’ve spent the last few days messing about with Google App Engine and I have to admit I’m liking it – a lot!
As a web engineer, the most tedious part of developing for me is configuring environments and setting up databases. I just want to code and not have to worry about configuration and optimisation. So I guess that’s why I’m enjoying App Engine so much.
One of the really exciting aspects of developing in AE so far has been working with the modeling API. It’s nice not having to deal with messy SQL schemas and complicated joins. It’s all pure OO programming. There’s a lot of good documentation on the Google site but this will help you get going quickly.
For our sample app, we want to create a recipe site. We’ll keep it simple for now. We have recipes and each recipe has a bunch of ingredients so we’ll create an object that represents a single recipe and one that represent a single ingredient.
1 2 3 4 5 6 7 8 | class Recipe(db.Model): title = db.StringProperty() description = db.TextProperty() created = db.DateTimeProperty(auto_now_add=True) class Ingredient(db.Model): name = db.StringProperty() created = db.DateTimeProperty(auto_now_add=True) |
This should be pretty straight forward. In SQL terms, we have created 2 tables with a bunch of fields and each field has a certain property like string, text, datetime etc. You don’t have to run any commands to create the database/tables. It’s all done at runtime.
Now that we have our models, let’s populate them.
1 2 3 4 5 6 7 8 9 | # create a new recipe recipe = Recipe() # set the values of each field recipe.title = "Caprese Salad" recipe.description = "Light Italian classic" # save it! recipe.put |
You can also do the above like this:
1 | recipe = Recipe(title = "Caprese Salad", description = "Light Italian classic").put() |
You can keep adding more recipes by creating a new instance of the Recipe model.
Now that we have a bunch of recipes, let’s get them all out and then output them in our view layer as html
1 2 3 4 5 6 | recipes = Recipe.all() recipes.order("title") recipeResults = recipes.fetch(limit=40) # I'm just using standard Django templates here return render_to_response('index.html', {'recipeResults': recipeResults}) |
And in our template we can just loop through the results
1 2 3 4 5 6 7 | <ul> {% for recipe in recipeResults %} <li> {{ recipe.title }} - {{ recipe.description }} </li> {% endfor %} </ul> |
That’s it! and not a single line of SQL.
In the next tutorial we’ll create some ingredients and I’ll show how to do one-to-many relationships.
No Comments »