Re: data from bus to publishing function

IngoognI <[email protected]> Mon, 16 Jan 2017 02:43:31 -0800 (PST)
Newsgroups gmane.comp.python.cherrypy
Message-ID <[email protected]>
Got it working over coffee break so I can now push data from the web to the 
web or from a tool to the web. May need some polish, appreciate input on 
that.


import cherrypy
import os
import time
import threading

e = threading.Event()

class Var(object):

    @property
    def x(self): 
        return self._x

    @x.setter
    def x(self, value): 
        e.set()
        self._x = value


class Root():

    @cherrypy.expose
    @cherrypy.tools.json_in()
    def sensor(self, **kwargs):
        input_json = cherrypy.request.json
        cherrypy.engine.publish("cpu", str(input_json['cpu']))

    @cherrypy.expose
    def pubcpu(self):
        cherrypy.response.headers["Content-Type"] = "text/event-stream"
        k = Var()
        def value(v):
            k.x = v
        cherrypy.engine.subscribe("cpu", value)    
        def pub():
            while True:
                e.wait()
                yield "event: time\n" + "data: " + k.x + "\n\n"
                e.clear()
        return pub()        
    pubcpu._cp_config = {'response.stream': True}

    @cherrypy.expose
    def index(self):
        return '''<!DOCTYPE html>
<html>
 <head>
  <title>Server-sent events test</title>
 </head>
 <body>
  <script type="text/javascript">
    document.addEventListener('DOMContentLoaded', function () {
      var source = new EventSource('pubcpu');
      source.addEventListener('cpu', function (event) {
        document.getElementById('test').innerHTML = event.data;
      });
      source.addEventListener('error', function (event){
        console.log('SSE error:', event);
        console.log('SSE state:', source.readyState);
      });
    }, false);
  </script>
  <p><span id="test"></span></p>
 </body>
</html>'''

if __name__ == '__main__':
    cherrypy.quickstart(Root(), '/')

-- 
You received this message because you are subscribed to the Google Groups "cherrypy-users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to cherrypy-users+unsubscribe-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
To post to this group, send email to cherrypy-users-/JYPxA39Uh5TLH3MbocFF+G/[email protected]
Visit this group at https://groups.google.com/group/cherrypy-users.
For more options, visit https://groups.google.com/d/optout.