Games Brainiac Games Brainiac - 2 months ago 10
Python Question

Creating a user in Google App Engine and migrations the easy way

I am a bit new to GAE, so I wanted to ask, how do you create a user model for something as trivial as a blog.

So, far, this is all I got:

class User(db.Model): # Todo create a user model, that works with your login page
username = db.UserProperty()
password = db.StringProperty()


But this looks very primitive. How would one go about creating a user in google app engine, as in what is the best practice, of creating such fields where uniqueness is an important factor.
Also, how would you link a user to a blog post, since links are not allowed in google data-store.
Finally is there an app that manages all your migrations? Like south for GAE? There seems to be a way to migrate, but it involved a great deal of boiler-plate code.

Also, I come from a django background, so I am finding all of this a little counter-intuitive, since this is not a relational database.

Answer

Your User class is fine for now, you can add fields to your model as you need them during development. But you should use ndb rather than db. ndb handles much more features (like automatic caching). You can find more details in the documentation.

If you want to learn more advanced user or datastore models, you can look at gae-boilerplate, which already handles user login and signup (even from facebook/twitter/...). The README is very well documented : https://github.com/coto/gae-boilerplate

You can implement some kind of relations in your models, either by using a KeyProperty() or by setting a parent entity when you create one. For example :

class BlogPost(ndb.Model):
    title = ndb.StringProperty()
    content = ndb.TextProperty()
    timestamp = ndb.DateTimeProperty(auto_add_now=True)

# Then you can specify a parent in the constructor (where user is a User entity)
blog_post = BlogPost(parent=user)
blog_post.title = 'Post title'
blog_post.content = 'Post content'
blog_post.put()

Then use Ancestor queries to retrieve all blog posts published by a user.