예제 #1
0
def test():
    import tempfile
    import shutil
    import pubsub

    watched_path = tempfile.mkdtemp()
    print "Temp folder: " + watched_path

    events = pubsub.PubSub()
    w = WatchCoordinator(events)

    def display_changes(watch_path, changed_path, change_action):
        print "Watched path '%s'\nChanged path '%s'\nChange action '%s'" % (
            watch_path, changed_path, change_action)

    token = events.subscribe('TaskHive.1.PathWatcher.1', display_changes)

    try:
        th = w.watch(watched_path, token['topic'])
        l = threading.Event()
        l.clear()
        l.wait(2)
        open(watched_path + '/testfile.txt', 'w').write('')
        l.wait(50)
    except Exception, e:
        raise
예제 #2
0
def shout():
    """Creates a new shout request.  Returns status of the pending request."""
    token = werkzeug.urls.url_decode(request.form['token'])
    # Insert a status log entity into data store.
    entity = ShoutStatusLog()
    entity.combined_shout_id = combine_ids(token['browserId'],
                                           request.form['shoutId'])
    entity.status = STATUS_MAP['new']
    entity.host = socket.gethostname()
    async_put = entity.put_async()

    # Insert the task into the work queue.
    deadline = utctimestamp() + TIMEOUT_SECONDS
    ps = pubsub.PubSub(APP_ID)
    query = werkzeug.urls.url_encode({
        'browserId': token['browserId'],
        'shoutId': request.form['shoutId'],
    })
    ps.publish(TOPIC, request.form['text'], {
        'deadline': str(deadline),
        'postStatusUrl': 'https://%s/post_shout_status?%s' %
                         (socket.getfqdn(socket.gethostname()), query),
        'postStatusToken': purse.get_tokens()[0],
    })
    async_put.get_result()
    # Wait for a result.
    return poll_shout_status(token['browserId'], request.form['shoutId'], 'new')
예제 #3
0
def subscribeToChannel():
    global pubSubClient
    pubSubClient = pubsub.PubSub(addr=ServerAdd,
                                 username=usrnANDpassw,
                                 password=usrnANDpassw,
                                 organization=routingKey)
    pubSubClient.create_queue(queue_name=queueName, auto_delete=True)
    pubSubClient.subscribe(receiveMessages, queueName, no_ack=True)
예제 #4
0
def init():
    """Called once by an admin to create pubsub topics and subscriptions."""
    ps = pubsub.PubSub(APP_ID)
    errors = []
    for lam in (lambda: ps.create_topic(TOPIC),
                lambda: ps.subscribe(TOPIC, SUBSCRIPTION),
                lambda: purse.init(new_random_id())):
        try:
            lam()
        except:
            errors.append(traceback.format_exc())
    if errors:
        return "\n".join(errors), 500
    return "ok"
예제 #5
0
    def start_fresh_game(self):
        logging.basicConfig(
            filename=
            f'{resource_path("log")}/{datetime.datetime.now().strftime("%Y%m%d%H%M%S")}.log',
            filemode='w',
            format='%(asctime)s - %(message)s',
            datefmt='%d-%b-%y %H:%M:%S',
            level=CONFIG.get('logging_level'))

        pubsub.pubsub = pubsub.PubSub()

        self.message_log = MessageLog(CONFIG.get('message_width'),
                                      CONFIG.get('message_height'))
        pubsub.pubsub.subscribe(
            pubsub.Subscription(self.message_log, pubsub.PubSubTypes.MESSAGE,
                                pubsub.add_to_messages))

        self.player = create_player()

        self.game_map = GameMap()
        self.game_map.create_floor(self.player)

        self.start_game()
예제 #6
0
import pubsub
__author__ = 'David'

sample = pubsub.PubSub(addr='localhost',
                       queue_name='guest',
                       username='******',
                       password='******',
                       auto_delete=True)

print("Listening on hello")

MESSAGES_EXCHANGE = sample.get_messageexchange()
PRESENCE_EXCHANGE = sample.get_presenceexchange()


def callback(channel, method_frame, header_frame, body):
    exchange = method_frame.exchange
    if exchange == PRESENCE_EXCHANGE:
        action = header_frame.headers['action']
        who = header_frame.headers['key']
        if action == 'bind':
            print('User %s entered the room.' % (who, ))
        elif action == 'unbind':
            print('User %s left the room.' % (who, ))
    elif exchange == MESSAGES_EXCHANGE:
        who = method_frame.routing_key
        print('%s: %s' % (who, body))


try:
    sample.subscribe(callback, queue_name='guest', no_ack=True)
예제 #7
0
#!/usr/bin/env python
import pubsub
import threading

__author__ = 'David'

sample = pubsub.PubSub(addr='addigy-dev.cis.fiu.edu',
                       queue_name='david',
                       username='******',
                       password='******',
                       auto_delete=True,
                       heartbeat_interval=60,
                       organization='testcorp')

MESSAGES_EXCHANGE = sample.get_messageexchange()
PRESENCE_EXCHANGE = sample.get_presenceexchange()


def callback(channel, method_frame, header_frame, body):
    exchange = method_frame.exchange
    if exchange == PRESENCE_EXCHANGE:
        action = header_frame.headers['action']
        who = header_frame.headers['key']
        if action == 'bind':
            print('User %s entered the room.' % (who, ))
        elif action == 'unbind':
            print('User %s left the room.' % (who, ))
    elif exchange == MESSAGES_EXCHANGE:
        who = method_frame.routing_key
        print('%s: %s' % (who, body))