4.5.2. The Server Application

Now let's look at the code for these two applications, which are each based on the skeleton shown at Section 4.1, “Creating and Closing Sessions”. In this application, both programs send and receive messages. The server sets up a queue called request, and binds it to the amq.direct exchange with the binding key request. Clients post all requests to the amq.direct exchange using the routing key request. Each client creates its own private response queue and a corresponding routing key, which it places in the reply-to property of each request it writes to the exchange.
server.py creates a request queue, which is used for all clients, reads requests from this queue, and sends responses to the client who made each request. Here is the code that creates the request queue and subscribes to it:
session.queue_declare(queue="request", exclusive=True)
session.exchange_bind(exchange="amq.direct", queue="request", binding_key="request")

local_queue_name = "local_queue"

session.message_subscribe(queue="request", destination=local_queue_name)

queue = session.incoming(local_queue_name)
The server then creates a local queue, using the destination used in the above subscription, and waits for messages to arrive. If a message arrives, it calls the respond() function:
queue = session.incoming(local_queue_name)

# If we get a message, send it back to the user (as indicated in the
# ReplyTo property)

while True:
    request = queue.get(timeout=100)
    respond(session, request)
  except Empty:
    print "No more messages!"
In the respond function, the server takes the body of the message, converts it to upper case, and writes the result to the amq.direct exchange using a routing key specified by the client using the message's reply_to property, which contains a routing_key property:
def respond(session, request):

    # The routing key for the response is the request's reply-to
    # property.  The body for the response is the request's body,
    # converted to upper case.

    message_properties = request.get("message_properties")
    reply_to = message_properties.reply_to
    if reply_to == None:
       raise Exception("This message is missing the 'reply_to' property, which is required")   
    props = session.delivery_properties(routing_key=reply_to["routing_key"]) 
    session.message_transfer(destination=reply_to["exchange"], message=Message(props, request.body.upper()))