e-Book - Redis in Action

This book covers the use of Redis, an in-memory database/data structure server.
  • Foreword
  • Preface
  • Acknowledgments
  • About this Book
  • About the Cover Illustration
  • Part 1: Getting Started
  • Part 2: Core concepts
  • Part 3: Next steps
  • Appendix A
  • Appendix B
  • Buy the paperback

    8.1.2 Status messages

    As we mentioned earlier, whereas user profiles store information about an individual,
    the ideas that people are trying to express are stored in status messages. As was the
    case with user information, we’ll store status message information inside a HASH.

    Figure 8.2Example status message stored in a HASH

    In addition to the message itself, we’ll store when the status message was posted, the user ID and login of the user who posted it (so that if we have a status object, we don’t need to fetch the user object of the poster to discover their login name), and any additional information that should be stored about the status message. Figure 8.2 shows an example status message.

    And that’s everything necessary for a basic status message. The code to create such a status message can be seen in the next listing.

    Listing 8.2How to create a status message HASH
    def create_status(conn, uid, message, **data):
        pipeline = conn.pipeline(True)
        pipeline.hget('user:%s'%uid, 'login')

    Get the user’s login name from their user ID.


    Create a new ID for the status message.

        login, id = pipeline.execute()
        if not login:
            return None

    Verify that we have a proper user account before posting.

            'message': message,
            'posted': time.time(),
            'id': id,
            'uid': uid,
            'login': login,
        pipeline.hmset('status:%s'%id, data)

    Prepare and set the data for the status message.

        pipeline.hincrby('user:%s'%uid, 'posts')

    Record the fact that a status message has been posted.

        return id

    Return the ID of the newly created status message.

    There isn’t anything surprising going on in the status creation function. The function
    fetches the login name of the user, gets a new ID for the status message, and then combines
    everything together and stores it as a HASH.

    We’ll talk about making the status message visible to followers in section 8.4, so sit
    tight for now, as we now examine the most commonly used view into lists of status messages:
    a user’s home timeline.