Skip to content

Instantly share code, notes, and snippets.

@toastdriven
Created November 17, 2010 05:35
Show Gist options
  • Select an option

  • Save toastdriven/703032 to your computer and use it in GitHub Desktop.

Select an option

Save toastdriven/703032 to your computer and use it in GitHub Desktop.
The storage layer for a simple Riak-powered blog.
import riak
import uuid
import time
# For regular HTTP...
# client = riak.RiakClient()
# For Protocol Buffers (go faster!)
client = riak.RiakClient(port=8087, transport_class=riak.RiakPbcTransport)
entry_bucket = client.bucket('entry')
comment_bucket = client.bucket('comment')
def create_entry(entry_dict):
# ``entry_dict`` should look something like:
# {
# 'title': 'First Post!',
# 'author': 'Daniel',
# 'slug': 'first-post',
# 'posted': time.time(),
# 'tease': 'A test post to my new Riak-powered blog.',
# 'content': 'Hmph. The tease kinda said it all...',
# }
entry = entry_bucket.new(entry_dict['slug'], data=entry_dict)
entry.store()
def create_comment(entry_slug, comment_dict):
# ``comment_dict`` should look something like:
# {
# 'author': 'Daniel',
# 'url': 'http://pragmaticbadger.com/',
# 'posted': time.time(),
# 'content': 'IS IT WEBSCALE? I HEARD /DEV/NULL IS WEBSCALE.',
# }
# Error handling omitted for brevity...
entry = entry_bucket.get(entry_slug)
# Give it a UUID for the key.
comment = comment_bucket.new(str(uuid.uuid1()), data=comment_dict)
comment.store()
# Add the link.
entry.add_link(comment)
entry.store()
def get_entry_and_comments(entry_slug):
import pdb; pdb.set_trace()
entry = entry_bucket.get(entry_slug)
comments = []
# They come out in the order you added them, so there's no
# sorting to be done.
for comment_link in entry.get_links():
# Gets the related object, then the data out of it's value.
comments.append(comment_link.get().get_data())
return {
'entry': entry.get_data(),
'comments': comments,
}
# To test:
if __name__ == '__main__':
create_entry({
'title': 'First Post!',
'author': 'Daniel',
'slug': 'first-post',
'posted': time.time(),
'tease': 'A test post to my new Riak-powered blog.',
'content': 'Hmph. The tease kinda said it all...',
})
create_comment('first-post', {
'author': 'Matt',
'url': 'http://pragmaticbadger.com/',
'posted': time.time(),
'content': 'IS IT WEBSCALE? I HEARD /DEV/NULL IS WEBSCALE.',
})
create_comment('first-post', {
'author': 'Daniel',
'url': 'http://pragmaticbadger.com/',
'posted': time.time(),
'content': 'You better believe it!',
})
data = get_entry_and_comments('first-post')
print "Entry:"
print data['entry']['title']
print data['entry']['tease']
print
print "Comments:"
for comment in data['comments']:
print "%s - %s" % (comment['author'], comment['content'])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment