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:
- The payload of the message, a dict
- The user-session of the sender of the event, a Beaker session
- 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.