Services

Python Services

Python functions that are decorated with “@Service” will be exposed as message responders. For example:

@Service(request="friend.add.request", response="friend.add.response")
def add_friend(msg, session, msgname):
    you = Folks.get(session['person_id'])
    friend = Folks.get(msg['friend_id'])
    
    if Friendships.allowed(you, friend):
        fship = Friendships.make(you, friend, now())
        return {'success':True, 'friendship': fship}
    else:
        return {'success':False, 'reason': Friendships.get_reason_blocked(you, friend)}

The “add_friend” service will be called whenever the server receives a “friend.add.request” message.

The arguments passed to the service function are:

  1. The payload of the message, a dict
  2. The user-session of the sender of the event, a Beaker session
  3. The name of the message triggering this call

Service functions can omit parameters that they do not need.

The return value of the function is converted in a JSON object, and returned to the client-side, in this case, as a “friend.add.response” message.

The Service Broker

Passing messages between the client and server is handled transparently by a piece of code called the Service Broker. The python Service Broker is implemented as a WSGI app and is configured in the “development.ini” file. This file is run by PasteScript and combines the Service Broker, a cross-domain proxy (for use with the app:http widget), and the standard Pylons controllers. Because they are wrapped in a common Beaker session middleware, Pylons controllers and Appcelerator services can share user sessions.