예제 #1
0
파일: root.py 프로젝트: ralphbean/moksha
 def _get_feed_titles(self, fresh=False):
     results = []
     for feed in moksha.feed_storage.keys():
         if not feed:
             raise Exception('None feed?!')
         if fresh:
             print "Getting fresh data"
             feed_data = moksha.feed_cache.fetch(feed)
         else:
             print "Getting cached data"
             timestamp, feed_data = moksha.feed_storage[feed]
         if not feed_data:
             log.debug("no feed_data, refetching")
             #feed_data = moksha.feed_cache.fetch(feed)
             #if not feed_data:
             #    log.debug("NO FEED DATA AFTER FRESH FETCH!!!!")
             continue
         channel = feed_data.get('channel')
         if not channel:
             continue
         title = channel.get('title')
         results.append({
             'title': title,
             'key': feed,
             'isLazy': False,
             'isFolder': True,
         })
     return json.encode(results)
예제 #2
0
파일: helpers.py 프로젝트: ralphbean/moksha
    def process(self, d=None):
        """Check the predicates and construct the dict

        :returns: a dict with all the configuration data for this application
        """
        if not check_predicates(self.auth):
            return None

        results = super(App, self).process(d)

        css_class = self.css_class
        if css_class == None:
            css_class = ''

        p = _update_params(self.params, d)
        qs = self._create_query_string(p)
        results.update({
            'label': self.label,
            'url': self.url,
            'params': p,
            'json_params': json.encode(p),
            'query_string': qs,
            'content_id': self.content_id + '-' + results['id'],
            'css_class': css_class
        })

        return results
예제 #3
0
 def _get_feed_titles(self, fresh=False):
     results = []
     for feed in moksha.utils.feed_storage.keys():
         if not feed:
             raise Exception('None feed?!')
         if fresh:
             print "Getting fresh data"
             feed_data = moksha.utils.feed_cache.fetch(feed)
         else:
             print "Getting cached data"
             timestamp, feed_data = moksha.utils.feed_storage[feed]
         if not feed_data:
             log.debug("no feed_data, refetching")
             #feed_data = moksha.utils.feed_cache.fetch(feed)
             #if not feed_data:
             #    log.debug("NO FEED DATA AFTER FRESH FETCH!!!!")
             continue
         channel = feed_data.get('channel')
         if not channel:
             continue
         title = channel.get('title')
         results.append({
             'title': title,
             'key': feed,
             'isLazy': False,
             'isFolder': True,
             })
     return json.encode(results)
예제 #4
0
파일: helpers.py 프로젝트: ralphbean/moksha
    def process(self, d=None):
        """Check the predicates and construct the dict

        :returns: a dict with all the configuration data for this application
        """
        if not check_predicates(self.auth):
            return None

        results = super(App, self).process(d)

        css_class = self.css_class
        if css_class == None:
            css_class = ""

        p = _update_params(self.params, d)
        qs = self._create_query_string(p)
        results.update(
            {
                "label": self.label,
                "url": self.url,
                "params": p,
                "json_params": json.encode(p),
                "query_string": qs,
                "content_id": self.content_id + "-" + results["id"],
                "css_class": css_class,
            }
        )

        return results
예제 #5
0
파일: sse.py 프로젝트: 3rd-Eden/orbited
 def write(self, packets):
     payload = json.encode(packets)
     data = (
         'Event: payload\n' +
         '\n'.join(['data: %s' % line for line in payload.splitlines()]) +
         '\n\n'
     )
     self.request.write(data)
예제 #6
0
 def recv_message(self, msg):
     message = json.decode(msg['body'])
     if msg['headers']['destination'] == CHANNEL_MINIDO_WRITE:
         if type(message) is list:
             print(str(datetime.datetime.now()), ": STOMP to RS485 :", message)
             for conn in self.minidoFactory.connections:
                 conn.send_data(message)
             # Also copy it for other listeners.
             self.send(CHANNEL_MINIDO_READ, json.encode(message))
 def recv_message(self, msg):
     message = json.decode(msg['body'])
     if msg['headers']['destination'] == CHANNEL_DISPLAY_NAME:
         print(message)
         if 'ButtonClicked' in message and message['ButtonClicked'] == '1':
             self.send_data({'ButtonClicked': '2'})
         if 'ListGroups' in message and message['ListGroups'] == '1':
             self.send_data({'Group1': 'RDC', 
                 'Group2': 'Etage', 'Group3': 'Grenier'})
     elif msg['headers']['destination'] == CHANNEL_MINIDO_READ:
         self.mpd.recv_minido_packet(message)
     elif msg['headers']['destination'] == CHANNEL_MINIDO_LAYOUT:
         if 'query' in message.keys():
             if message['query'] == 'getLayout':
                 self.send(CHANNEL_MINIDO_LAYOUT, 
                     json.encode({'layout': self.mpd.devdict.keys()}))
             elif message['query'] == 'getStatus':
                 self.send(CHANNEL_MINIDO_LAYOUT, 
                     json.encode({'status': 'This is a status line'}))
예제 #8
0
 def write(self, packets):
     # TODO make some JS code to remove the script elements from DOM
     #      after they are executed.
     payload = '<script>e(%s)</script>' % (json.encode(packets),)
     logger.debug('write ', payload)
     self.request.write(payload);
     self.totalBytes += len(payload)
     if (self.totalBytes > MAXBYTES):
         logger.debug('write: closing because session MAXBYTES was exceeded')
         self.close()
예제 #9
0
    def get_feed(self, key, *args, **kw):
        if '::' in key:
            url, title = key.split('::')
            for entry in moksha.utils.feed_storage[url][1]['entries']:
                content = entry.get('content', entry.get('summary'))
                content = '<span style="line-height:100%%;">%s</span>' % content
                if entry['title'] == title:
                    return json.encode([{'title': content, 'isLazy': False}])
            raise Exception("Cannot find entry by title: %s" % title)

        feed = moksha.utils.feed_storage[key][1]
        entries = []
        for entry in feed['entries']:
            entries.append({
                'title': entry.get('title'),
                'isLazy': True,
                'isFolder': True,
                'key': "%s::%s" % (key, entry.get('title')),
                })
        return json.encode(entries)
예제 #10
0
 def write(self, packets):
     # TODO make some JS code to remove the script elements from DOM
     #      after they are executed.
     payload = '<script>e(%s)</script>' % (json.encode(packets), )
     logger.debug('write ', payload)
     self.request.write(payload)
     self.totalBytes += len(payload)
     if (self.totalBytes > MAXBYTES):
         logger.debug(
             'write: closing because session MAXBYTES was exceeded')
         self.close()
예제 #11
0
파일: root.py 프로젝트: ralphbean/moksha
    def get_feed(self, key, *args, **kw):
        if '::' in key:
            url, title = key.split('::')
            for entry in moksha.feed_storage[url][1]['entries']:
                content = entry.get('content', entry.get('summary'))
                content = '<span style="line-height:100%%;">%s</span>' % content
                if entry['title'] == title:
                    return json.encode([{'title': content, 'isLazy': False}])
            raise Exception("Cannot find entry by title: %s" % title)

        feed = moksha.feed_storage[key][1]
        entries = []
        for entry in feed['entries']:
            entries.append({
                'title': entry.get('title'),
                'isLazy': True,
                'isFolder': True,
                'key': "%s::%s" % (key, entry.get('title')),
            })
        return json.encode(entries)
예제 #12
0
파일: irclib.py 프로젝트: harsa/relayd
	def tojson(self):

		event = {
			'event': {
				'type': self.eventtype(),
				'target': self.target(),
				'source': self.source(),
				'arguments': self.arguments(),
				'timestamp': self._timestamp
			}
		}

		return json.encode(event)
예제 #13
0
 def tree(self, node):
     if node[0] == 'root':
         n = '/target'
     else:
         n = node[0]
     list = self.backend.list_partition([n])
     r = []
     for l in list.splitlines():
         if l[0] == '+':
             r.append({'id': "%s/%s" % (n,l), 'text': l[1:].replace('_',' ')})
         else:
             r.append({'id': "%s/%s" % (n,l), 'text': l.replace('_',' '), 'leaf': True})
     return json.encode(r)
예제 #14
0
    def send_data(self):
	global ac_part, conf

	if isinstance(ac_part, Part):
            ting = {'part': ac_part.__dict__, 'conf': conf.__dict__}
            js = str(json.encode(ting))
        else:
            print "Ingen JS"
            js = ""
        self.send(CHANNEL_NAME, js)

	fp = open("htdocs/" + conf.slug + "/" + ac_part.slug + "/first.json", "w")
	fp.seek(0)
	fp.write(js)
	fp.flush()
	fp.close()
예제 #15
0
파일: hub.py 프로젝트: lmacken/moksha
    def send_message(self, topic, message, jsonify=True):
        """ Send a message to a specific topic.

        :topic: A topic or list of topics to send the message to.
        :message: The message body.  Can be a string, list, or dict.
        :jsonify: To automatically encode non-strings to JSON

        """
        if not isinstance(topic, list):
            topics = [topic]
        else:
            topics = topic
        for topic in topics:
            if jsonify:
                message = json.encode(message)
            if self.amqp_broker:
                AMQPHub.send_message(self, topic, message, routing_key=topic)
            elif self.stomp_broker:
                StompHub.send_message(self, topic, message)
예제 #16
0
파일: hub.py 프로젝트: lmacken/moksha
    def send_message(self, topic, message, jsonify=True):
        """ Send a message to a specific topic.

        :topic: A topic or list of topics to send the message to.
        :message: The message body.  Can be a string, list, or dict.
        :jsonify: To automatically encode non-strings to JSON

        """
        if not isinstance(topic, list):
            topics = [topic]
        else:
            topics = topic
        for topic in topics:
            if jsonify:
                message = json.encode(message)
            if self.amqp_broker:
                AMQPHub.send_message(self, topic, message, routing_key=topic)
            elif self.stomp_broker:
                StompHub.send_message(self, topic, message)
예제 #17
0
파일: helpers.py 프로젝트: ralphbean/moksha
def _update_params(params, d):
    p = {}
    if params:
        for k in params.iterkeys():

            if d and (k in d):
                value = d[k]
            else:
                value = params[k]

            # recursive dicts also get updated
            # by the passed params
            if isinstance(value, dict):
                value = _update_params(value, d)
                value = json.encode(value)
            elif isinstance(value, list):
                value = value

            if value != None:
                p[k] = value

    return p
예제 #18
0
파일: helpers.py 프로젝트: decause/moksha
def _update_params(params, d):
    p = {}
    if params:
        for k in params.iterkeys():

            if d and (k in d):
                value = d[k]
            else:
                value = params[k]

            # recursive dicts also get updated
            # by the passed params
            if isinstance(value, dict):
                value = _update_params(value, d)
                value = json.encode(value)
            elif isinstance(value, list):
                value = value

            if value != None:
                p[k] = value

    return p
예제 #19
0
파일: monitor.py 프로젝트: 3rd-Eden/orbited
 def send(self, data):
     self.transport.write(json.encode(data)+'~')
예제 #20
0
파일: relay.py 프로젝트: liuhuiwisdom/WRed
 def send_data(self, channel, data):
     print "Transmitting: ", data
     # modify our data elements
     self.send(channel, json.encode(data))
예제 #21
0
 def send_uistate(self, component, key, value):
     try:
         encoded = json.encode(value)
         self.send("/flumotion/components/uistate/%s/%s" % (component, key), encoded)
     except Exception, e:
         print "Error %r with uistate %r" % (e, value)
예제 #22
0
 def send_changes(self, changes):
     self.send("/flumotion/components/changes", json.encode(changes))
예제 #23
0
 def send_status(self):
     global main
     data = json.encode(main.components())
     self.send("/flumotion/components/initial", data)
 def send_data(self, data):
     print("Sending : " + str(data))
     self.send(CHANNEL_MINIDO_WRITE, json.encode(data))
예제 #25
0
파일: metrics.py 프로젝트: lmacken/moksha
 def consume(self, message):
     topic = message['headers'].get('topic')
     if topic:
         self.send_message(topic, json.encode(message['body']))
     else:
         log.error('No `topic` specified in moksha_message_metrics message')
예제 #26
0
파일: comet.py 프로젝트: adakkak/djegg
    def send_data(self):
#        print 'sent data'
        self.data = self.edf.next_sample()
        self.send("/comet/plot", json.encode(self.data))
예제 #27
0
def part_new():

    namn = raw_input("namn: ").decode("utf-8")
    slides = raw_input("tal på slides: ")
    kortid = raw_input("kor tid: ")

    return Part(namn, slides, kortid)

#def part_active()
if not parts:
    print "Legg til ny del"
    parts.append(part_new())

fp = open("htdocs/" + conf.slug + "/first.json", "w")
fp.write(json.encode(conf.__dict__))
fp.close()

def chpart(part_no):
    global ac_part

    if ac_part:
        ac_part.active = False

    ac_part = parts[part_no]

    try:
        os.mkdir("htdocs/" + conf.slug + "/" + ac_part.slug)
    except OSError:
        pass
예제 #28
0
 def write(self, packets):
     payload = json.encode(packets)
     data = ('Event: payload\n' +
             '\n'.join(['data: %s' % line
                        for line in payload.splitlines()]) + '\n\n')
     self.request.write(data)
예제 #29
0
 def update(self, data):
     if hasattr(self, 'send'):
         log.msg("Enviando estado al monitor\n")
         self.send(CHANNEL_NAME, json.encode(data))
예제 #30
0
 def json_status(self, _dc=None):
     if hasattr(Host, 'status'):
         return json.encode(Host.status)
     else:
         return json.encode([])
예제 #31
0
파일: metrics.py 프로젝트: ralphbean/moksha
 def consume(self, message):
     topic = message['headers'].get('topic')
     if topic:
         self.send_message(topic, json.encode(message['body']))
     else:
         log.error('No `topic` specified in moksha_message_metrics message')
예제 #32
0
 def send_status(self):
     global main
     data = json.encode(main.components())
     self.send("/flumotion/components/initial", data)
예제 #33
0
 def send_data(self, data):
     print(str(datetime.datetime.now()) + " : RS485 to STOMP : " + str(data))
     self.send(CHANNEL_MINIDO_READ, json.encode(data))
예제 #34
0
 def send_changes(self, changes):
     self.send("/flumotion/components/changes", json.encode(changes))
예제 #35
0
def json_response(data): 
    r = HttpResponse(json.encode(data),content_type='application/json')
    r['Cache-Control'] = 'no-cache, must-revalidate'
    r['Pragma'] = 'no-cache'
    
    return r
예제 #36
0
 def send_uistate(self, component, key, value):
     try:
        encoded = json.encode(value)
        self.send("/flumotion/components/uistate/%s/%s" % (component, key), encoded)
     except Exception, e:
        print "Error %r with uistate %r" % (e, value)
예제 #37
0
 def send(self, data):
     self.transport.write(json.encode(data) + '~')
예제 #38
0
 def send_data(self, channel, data):
     print "Transmitting: ", data
     # modify our data elements
     self.send(channel, json.encode(data))