Commits

Ginés Martínez Sánchez committed 489b242 Draft

periodic callback of sockjs done

Comments (0)

Files changed (14)

 - Coverage 100% tests.
 - SSL
 - Auth
-- Periodic Callback

ginsfsm/__init__.py

 """
 A python library to do development based in Finite State Machines.
 """
-__version__ = '0.5.0'
+__version__ = '0.5.1'
 __title__ = 'ginsfsm'
 __author__ = 'Ginés Martínez'
 __license__ = 'MIT License'

ginsfsm/c_timer.py

         )
 
     def _got_timer(self):
-        """ Callback timer
+        """ callback timer
         """
         self.broadcast_event(self.config.timeout_event_name)

ginsfsm/examples/sockjs/test_sockjs_apps/pyramid_main.py

 from .test import (
     EchoConnection,
     CloseConnection,
-    TickerConnection,
-    AmplifyConnection,
-    BroadcastConnection,
     CookieEcho,
 )
 
             self,
             sockjs_app_class=CloseConnection,
         )
-        self.disabled_websocket_echo = self.create_gobj(
-            'ticker',
-            GSockjsServer,
-            self,
-            sockjs_app_class=TickerConnection,
-        )
-        self.disabled_websocket_echo = self.create_gobj(
-            'amplify',
-            GSockjsServer,
-            self,
-            sockjs_app_class=AmplifyConnection,
-        )
+        #self.disabled_websocket_echo = self.create_gobj(
+        #    'ticker',
+        #    GSockjsServer,
+        #    self,
+        #    sockjs_app_class=TickerConnection,
+        #)
+        #self.disabled_websocket_echo = self.create_gobj(
+        #    'amplify',
+        #    GSockjsServer,
+        #    self,
+        #    sockjs_app_class=AmplifyConnection,
+        #)
         self.disabled_websocket_echo = self.create_gobj(
             'cookie_needed_echo',
             GSockjsServer,
             self,
             sockjs_app_class=CookieEcho,
         )
-        self.disabled_websocket_echo = self.create_gobj(
-            'broadcast',
-            GSockjsServer,
-            self,
-            sockjs_app_class=BroadcastConnection,
-        )
+        #self.disabled_websocket_echo = self.create_gobj(
+        #    'broadcast',
+        #    GSockjsServer,
+        #    self,
+        #    sockjs_app_class=BroadcastConnection,
+        #)

ginsfsm/examples/sockjs/test_sockjs_apps/test.py

         pass
 
 
-class TickerConnection(SockJSConnection):
-    def on_open(self, info):
-        self.timeout = self.gaplic.PeriodicCallback(self._ticker, 1000)
-        self.timeout.start()
-
-    def on_close(self):
-        self.timeout.stop()
-
-    def _ticker(self):
-        self.send('tick!')
-
-
-class BroadcastConnection(SockJSConnection):
-    clients = set()
-
-    def on_open(self, info):
-        self.clients.add(self)
-
-    def on_message(self, msg):
-        self.broadcast(self.clients, msg)
-
-    def on_close(self):
-        self.clients.remove(self)
-
-
-class AmplifyConnection(SockJSConnection):
-    def on_message(self, msg):
-        n = int(msg)
-        if n < 0 or n > 19:
-            n = 1
-
-        self.send('x' * int(math.pow(2, n)))
-
-
 class CookieEcho(SockJSConnection):
     def on_message(self, msg):
         self.send(msg)

ginsfsm/gaplic.py

     GSock,
 )
 from ginsfsm.gobj import GObj
-from ginsfsm.router import GRouter
 
 
 def _start_timer(seconds):
     """ Start a timer of :param:`seconds` seconds.
     The returned value must be used to check the end of the timer
-    with _test_timer() function.
+    with _elapsed_timer() function.
     """
     timer = time.time()
     timer = timer + seconds
     return timer
 
 
-def _test_timer(value):
+def _elapsed_timer(value):
     """ Check if timer :param:`value` has ended.
     Return True if the timer has elapsed, False otherwise.
     WARNING: it will fail when system clock has been changed.
 class _XTimer(object):
     """  Group attributes for timing.
     :param:`got_timer` callback will be executed :param:`sec` seconds.
-    The callback will be called with :param:`param1` parameter.
     If :param:`autostart` is True, the timer will be cyclic.
     """
-    def __init__(self, sec, got_timer_func, param1, autostart):
+    def __init__(self, sec, timer_callback, autostart):
         self.sec = sec
-        self.got_timer_func = got_timer_func
-        self.param1 = param1
+        self.timer_callback = timer_callback
         self.autostart = autostart
+        self.next_run = 0
+
+
+class Callback(object):
+    """Custom implementation of the Tornado.Callback with support
+    of callback timeout delays.
+    """
+    def __init__(self, callback, callback_time, gaplic):
+        """Constructor.
+
+        `callback`
+            Callback function
+        `callback_time`
+            Callback timeout value (in seconds)
+        `gaplic`
+            gaplic (io_loop) instance
+        """
+        self.callback = callback
+        self.callback_time = callback_time
+        self.gaplic = gaplic
+        self._running = False
+        self.next_run = None
+
+    def start(self, timeout=None):
+        """Start callbacks"""
+        self._running = True
+
+        if timeout is None:
+            timeout = self.callback_time
+
+        self.gaplic.add_timeout(timeout, self._run)
+
+    def stop(self):
+        """Stop callbacks"""
+        self._running = False
+
+    def delay(self):
+        """Delay callback"""
+        self.next_run = _start_timer(self.callback_time)
+
+    def _run(self):
+        if not self._running:
+            return
+        # Support for shifting callback window
+        if self.next_run and not _elapsed_timer(self.next_run):
+            self.start(self.next_run)
+            self.next_run = None
+            return
+
+        next_call = None
+        try:
+            next_call = self.callback()
+        except (KeyboardInterrupt, SystemExit):
+            raise
+        except:
+            self.gaplic.logger and self.gaplic.logger.exception(
+                "ERROR in periodic callback")
+
+        if self._running:
+            self.start(next_call)
 
 
 GAPLIC_FSM = {}
         self.logger and self.logger.info('GAplic (%r) initiated' % self.name)
 
     def start_up_router(self, pyramid_url=None, pyramid_root=None):
+        from ginsfsm.router import GRouter
         self.router = self.create_gobj(
             'router',
             GRouter,
                     # timer deleted while loop.
                     continue
                 some_event = True
-                if value and _test_timer(value):
+                if value and _elapsed_timer(value):
                     if xtimer.autostart:
-                        self._gotter_timers[xtimer] = _start_timer(xtimer.sec)
+                        next_run = _start_timer(xtimer.sec)
+                        xtimer.next_run = next_run
+                        self._gotter_timers[xtimer] = next_run
                     else:
                         self._gotter_timers[xtimer] = 0
-                    if xtimer.param1 is None:
-                        xtimer.got_timer_func()
-                    else:
-                        xtimer.got_timer_func(xtimer.param1)
+                        xtimer.next_run = 0
+                    if xtimer.timer_callback:
+                        xtimer.timer_callback()
                     if not xtimer.autostart:
                         self._gotter_timers.pop(xtimer)
         except RuntimeError:
             some_event = True
         return some_event
 
-    def _setTimeout(self, sec, got_timer_func, param1=None, autostart=False):
+    def _setTimeout(self, sec, timer_callback, autostart=False):
         """ Set a callback to be executed in ``sec`` seconds.
         Function used by :class:`GTimer` gobj. Not for general use.
         Return an object to be used in :func:`clearTimeout`.
         """
-        xtimer = _XTimer(sec, got_timer_func, param1, autostart)
-        self._gotter_timers[xtimer] = _start_timer(sec)
+        xtimer = _XTimer(sec, timer_callback, autostart)
+        next_run = _start_timer(sec)
+        xtimer.next_run = next_run
+        self._gotter_timers[xtimer] = next_run
         return xtimer
 
     def _clearTimeout(self, xtimer):
         Function used by :class:`GTimer` gobj. Not for general use.
         """
         t = self._gotter_timers.get(xtimer, None)
-        if t:
+        if t is not None:
             # prevent timer cleared in proces_timer loop
-            self._gotter_timers[xtimer] = 0
             self._gotter_timers.pop(xtimer)
+            xtimer.next_run = 0
+            xtimer.timer_callback = None
 
     def add_timeout(self, deadline, callback):
         """ Compatible with tornado.io_loop
         Instead, you must use `add_callback` to transfer control to the
         IOLoop's thread, and then call `add_timeout` from there.
         """
-        timer_id = self._setTimeout(deadline, callback)
-        return timer_id
+        xtimer = self._setTimeout(deadline, callback)
+        return xtimer
 
-    def remove_timeout(self, timeout):
+    def remove_timeout(self, xtimer):
         """ Compatible with tornado.io_loop
 
         Cancels a pending timeout.
         # http://docs.python.org/library/heapq.html).
         # If this turns out to be a problem, we could add a garbage
         # collection pass whenever there are too many dead timeouts.
-        timeout.callback = None
-        self._clearTimeout(timeout)
+        xtimer.timer_callback = None
+        self._clearTimeout(xtimer)
 
     def add_callback(self, callback, *args, **kwargs):
         """ Call the given callback in the next I/O loop iteration.
                 ret = False
                 if isinstance(sub.subscriber_gobj, Deferred):
                     # outside world
-                    sub.subscriber_gobj(event=oevent)
+                    if hasattr(sub, '__deferred_witout_oevent__'):
+                        sub.subscriber_gobj()
+                    else:
+                        sub.subscriber_gobj(event=oevent)
                 else:
                     # gobj-ecosistema
                     if hasattr(sub, '__use_post_event__'):
               If exists, it will be added as kw in the event broadcast.
               Can be used by the subscriptor for general purposes.
 
+            * `__deferred_witout_oevent__`:  ``Bool``
+
+              If True, the callback is called without event keyword parameter.
         """
         #if subscriber_gobj is not None:
         if not (isinstance(subscriber_gobj, string_types) or

ginsfsm/protocols/sockjs/server/c_sockjs_server.py

     GInfo,
     GIFrame,
 )
+from ginsfsm.c_timer import GTimer
+from ginsfsm.deferred import Deferred
 from ginsfsm.protocols.sockjs.server.c_transport_websocket import GRawWebsocket
 from ginsfsm.protocols.sockjs.server import session, sessioncontainer
 from ginsfsm.protocols.sockjs.server import stats
 
     # like tornado settings
     'session_check_interval': [
-        int, 1, 0, None, "Sessions check interval in seconds"
+        int, 5, 0, None, "Sessions check interval in seconds"
     ],
     'disconnect_delay': [
-        int, 5, 0, None, "Session expiration in seconds"
+        int, 10, 0, None, "Session expiration in seconds"
     ],
     'heartbeat_delay': [
         int, 25, 0, None,
         # Sessions
         self._sessions = sessioncontainer.SessionContainer()
 
-        #check_interval = self.settings['session_check_interval'] * 1000
-        #self._sessions_cleanup =ioloop.PeriodicCallback(self._sessions.expire,
-        #                                                 check_interval,
-        #                                                 self.io_loop)
+        check_interval = self.config.session_check_interval
+
+        self.timer = self.create_gobj(
+            None,       # unnamed gobj
+            GTimer,     # gclass
+            self        # parent
+        )
+        self.timer.delete_all_subscriptions()
+        deferred = Deferred(None, self._sessions.expire)
+        self.timer.subscribe_event(
+            'EV_TIMEOUT',
+            deferred,
+            __deferred_witout_oevent__=True,
+        )
+        self.send_event(
+            self.timer,
+            'EV_SET_TIMER',
+            seconds=check_interval,
+            autostart=True)
+
+        #self._sessions_cleanup = PeriodicCallback(
+        #    self._sessions.expire,
+        #    check_interval,
+        #    self.gaplic)
         #self._sessions_cleanup.start()
 
         # Stats

ginsfsm/protocols/sockjs/server/c_static.py

 import hashlib
 from pyramid.view import view_config
 
-from ginsfsm.protocols.sockjs.server.proto import json
+from ginsfsm.compat import bytes_
+from ginsfsm.protocols.sockjs.server.proto import json_encode
 from ginsfsm.protocols.sockjs.server.basehandler import (
     PreflightHandler,
     BaseHandler,
             'origins': ['*:*'],
             'entropy': random.randint(0, MAXSIZE),
         }
-        response.body = json.dumps(info).encode()
+        response.body = bytes_(json_encode(info))
         return response
 
 

ginsfsm/protocols/sockjs/server/periodic.py

-# -*- coding: utf-8 -*-
-"""
-    This module implements customized PeriodicCallback from tornado with
-    support of the sliding window.
-"""
-
-import time
-import logging
-
-
-class Callback(object):
-    """Custom implementation of the Tornado.Callback with support
-    of callback timeout delays.
-    """
-    def __init__(self, callback, callback_time, gaplic):
-        """Constructor.
-
-        `callback`
-            Callback function
-        `callback_time`
-            Callback timeout value (in milliseconds)
-        `gaplic`
-            gaplic (io_loop) instance
-        """
-        self.callback = callback
-        self.callback_time = callback_time
-        self.io_loop = gaplic
-        self._running = False
-
-        self.next_run = None
-
-    def calculate_next_run(self):
-        """Caltulate next scheduled run"""
-        return time.time() + self.callback_time / 1000.0
-
-    def start(self, timeout=None):
-        """Start callbacks"""
-        self._running = True
-
-        if timeout is None:
-            timeout = self.calculate_next_run()
-
-        self.io_loop.add_timeout(timeout, self._run)
-
-    def stop(self):
-        """Stop callbacks"""
-        self._running = False
-
-    def delay(self):
-        """Delay callback"""
-        self.next_run = self.calculate_next_run()
-
-    def _run(self):
-        if not self._running:
-            return
-
-        # Support for shifting callback window
-        if self.next_run is not None and time.time() < self.next_run:
-            self.start(self.next_run)
-            self.next_run = None
-            return
-
-        next_call = None
-        try:
-            next_call = self.callback()
-        except (KeyboardInterrupt, SystemExit):
-            raise
-        except:
-            logging.error("Error in periodic callback", exc_info=True)
-
-        if self._running:
-            self.start(next_call)

ginsfsm/protocols/sockjs/server/session.py

 
 import logging
 
-from ginsfsm.protocols.sockjs.server import sessioncontainer, periodic, proto
+from ginsfsm.gaplic import Callback
+from ginsfsm.protocols.sockjs.server import sessioncontainer, proto
 from ginsfsm.protocols.sockjs.server.util import bytes_to_str
 
 
 
         # Heartbeat related stuff
         self._heartbeat_timer = None
-        #self._heartbeat_interval = self.server.config.heartbeat_delay * 1000
-        self._heartbeat_interval = self.server.config.heartbeat_delay  # TODO?
+        self._heartbeat_interval = self.server.config.heartbeat_delay
 
         self._immediate_flush = self.server.config.immediate_flush
         self._pending_flush = False
             # If IP address doesn't match - refuse connection
             if handler.request.remote_addr != self.conn_info.ip:
                 logging.error(
-                    'Attempted to attach to session %s (%s) from different IP (%s)' % (
+                    'Attempted to attach to session %s (%s) '
+                    'from different IP (%s)' % (
                         self.session_id,
                         self.conn_info.ip,
                         handler.request.remote_addr
         """Reset hearbeat timer"""
         self.stop_heartbeat()
 
-        self._heartbeat_timer = periodic.Callback(
+        self._heartbeat_timer = Callback(
             self._heartbeat,
             self._heartbeat_interval,
             self.server.gaplic
 
         for msg in msg_list:
             self.conn.on_message(msg)
-
-
-
-
-
-
-
-
-
-
-
-
-
-#
-#
-#
-## -*- coding: utf-8 -*-
-#"""
-#    SockJS session implementation.
-#"""
-#
-#import logging
-#
-#from ginsfsm.protocols.sockjs.server import sessioncontainer, periodic, proto
-#
-#
-#class ConnectionInfo(object):
-#    """Connection information object.
-#
-#    Will be passed to the ``on_open`` handler of your connection class.
-#
-#    Has few properties:
-#
-#    `ip`
-#        Caller IP address
-#    `cookies`
-#        Collection of cookies
-#    `arguments`
-#        Collection of the query string arguments
-#    `headers`
-#        Collection of explicitly exposed headers from the request including:
-#        origin, referer, x-forward-for (and associated headers)
-#    `path`
-#        Request uri path
-#    """
-#    _exposed_headers = set(['referer', 'x-client-ip', 'x-forwarded-for',
-#                            'x-cluster-client-ip', 'via', 'x-real-ip'])
-#
-#    def __init__(self, ip, cookies, arguments, headers, path):
-#        self.ip = ip
-#        self.cookies = cookies
-#        self.arguments = arguments
-#        self.headers = {}
-#        self.path = path
-#
-#        for header in headers:
-#            if header.lower() in ConnectionInfo._exposed_headers:
-#                self.headers[header] = headers[header]
-#
-#    def get_argument(self, name):
-#        """Return single argument by name"""
-#        val = self.arguments.get(name)
-#        if val:
-#            return val[0]
-#        return None
-#
-#    def get_cookie(self, name):
-#        """Return single cookie by its name"""
-#        return self.cookies.get(name)
-#
-#    def get_header(self, name):
-#        """Return single header by its name"""
-#        return self.headers.get(name)
-#
-#
-## Session states
-#CONNECTING = 0
-#OPEN = 1
-#CLOSING = 2
-#CLOSED = 3
-#
-#
-#class BaseSession(object):
-#    """Base session implementation class"""
-#
-#    def __init__(self, conn, server):
-#        """Base constructor.
-#
-#        `conn`
-#            Connection class
-#        `server`
-#            GSockjsServer instance
-#        """
-#        self.server = server
-#        self.stats = server.stats
-#        self.gaplic = server.gaplic
-#
-#        self.send_expects_json = False
-#
-#        self.handler = None
-#        self.state = CONNECTING
-#
-#        self.conn_info = None
-#
-#        self.conn = conn(self)
-#
-#        self.close_reason = None
-#
-#    def set_handler(self, handler):
-#        """Set transport handler
-#        ``handler``
-#            Handler, should derive from the `sockjs.tornado.transports.base.BaseTransportMixin`.
-#        """
-#        if self.handler is not None:
-#            raise Exception('Attempted to overwrite BaseSession handler')
-#
-#        self.handler = handler
-#        self.transport_name = self.handler.name
-#
-#        if self.conn_info is None:
-#            self.conn_info = handler.get_conn_info()
-#            self.stats.on_sess_opened(self.transport_name)
-#
-#        return True
-#
-#    def verify_state(self):
-#        """Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
-#        if self.state == CONNECTING:
-#            self.state = OPEN
-#
-#            self.conn.on_open(self.conn_info)
-#
-#    def remove_handler(self, handler):
-#        """Remove active handler from the session
-#
-#        `handler`
-#            Handler to remove
-#        """
-#        # Attempt to remove another handler
-#        if self.handler != handler:
-#            raise Exception('Attempted to remove invalid handler')
-#
-#        self.handler = None
-#
-#    def close(self, code=3000, message='Go away!'):
-#        """Close session or endpoint connection.
-#
-#        `code`
-#            Closing code
-#        `message`
-#            Close message
-#        """
-#        if self.state != CLOSED:
-#            try:
-#                self.conn.on_close()
-#            except:
-#                logging.debug("Failed to call on_close().", exc_info=True)
-#            finally:
-#                self.state = CLOSED
-#                self.close_reason = (code, message)
-#
-#            # Bump stats
-#            self.stats.on_sess_closed(self.transport_name)
-#
-#            # If we have active handler, notify that session was closed
-#            if self.handler is not None:
-#                self.handler.session_closed()
-#
-#    def delayed_close(self):
-#        """Delayed close - won't close immediately, but on next ioloop tick."""
-#        self.state = CLOSING
-#        self.server.gaplic.add_callback(self.close)
-#
-#    def get_close_reason(self):
-#        """Return last close reason tuple.
-#
-#        For example:
-#
-#            if self.session.is_closed:
-#                code, reason = self.session.get_close_reason()
-#
-#        """
-#        if self.close_reason:
-#            return self.close_reason
-#
-#        return (3000, 'Go away!')
-#
-#    @property
-#    def is_closed(self):
-#        """Check if session was closed."""
-#        return self.state == CLOSED or self.state == CLOSING
-#
-#    def send_message(self, msg, stats=True, binary=False):
-#        """Send or queue outgoing message
-#
-#        `msg`
-#            Message to send
-#        `stats`
-#            If set to True, will update statistics after operation completes
-#        """
-#        raise NotImplemented()
-#
-#    def send_jsonified(self, msg, stats=True):
-#        """Send or queue outgoing message which was json-encoded before.
-#        Used by the `broadcast` method.
-#
-#        `msg`
-#            JSON-encoded message to send
-#        `stats`
-#            If set to True, will update statistics after operation completes
-#        """
-#        raise NotImplemented()
-#
-#    def broadcast(self, clients, msg):
-#        """Optimized `broadcast` implementation. Depending on type of the session, will json-encode
-#        message once and will call either `send_message` or `send_jsonifed`.
-#
-#        `clients`
-#            Clients iterable
-#        `msg`
-#            Message to send
-#        """
-#        self.server.broadcast(clients, msg)
-#
-#
-#class Session(BaseSession, sessioncontainer.SessionMixin):
-#    """SockJS session implementation.
-#    """
-#
-#    def __init__(self, conn, server, session_id, expiry=None):
-#        """Session constructor.
-#
-#        `conn`
-#            Default connection class
-#        `server`
-#            `GSockjsServer` instance
-#        `session_id`
-#            Session id
-#        `expiry`
-#            Session expiry time
-#        """
-#        # Initialize session
-#        sessioncontainer.SessionMixin.__init__(self, session_id, expiry)
-#        BaseSession.__init__(self, conn, server)
-#
-#        self.send_queue = ''
-#        self.send_expects_json = True
-#
-#        # Heartbeat related stuff
-#        self._heartbeat_timer = None
-#        self._heartbeat_interval = self.server.config.heartbeat_delay
-#
-#        self._immediate_flush = self.server.config.immediate_flush
-#        self._pending_flush = False
-#
-#        self._verify_ip = self.server.config.verify_ip
-#
-#    # Session callbacks
-#    def on_delete(self, forced):
-#        """Session expiration callback
-#
-#        `forced`
-#            If session item explicitly deleted, forced will be set to True. If
-#            item expired, will be set to False.
-#        """
-#        # Do not remove connection if it was not forced and there's running connection
-#        if not forced and self.handler is not None and not self.is_closed:
-#            self.promote()
-#        else:
-#            self.close()
-#
-#    # Add session
-#    def set_handler(self, handler, start_heartbeat=True):
-#        """Set active handler for the session
-#
-#        `handler`
-#            Associate active Tornado handler with the session
-#        `start_heartbeat`
-#            Should session start heartbeat immediately
-#        """
-#        # Check if session already has associated handler
-#        if self.handler is not None:
-#            handler.send_pack(proto.disconnect(2010, "Another connection still open"))
-#            return False
-#
-#        if self._verify_ip and self.conn_info is not None:
-#            # If IP address doesn't match - refuse connection
-#            if handler.request.remote_addr != self.conn_info.ip:
-#                logging.error('Attempted to attach to session %s (%s) from different IP (%s)' % (
-#                              self.session_id,
-#                              self.conn_info.ip,
-#                              handler.request.remote_addr
-#                              ))
-#
-#                handler.send_pack(proto.disconnect(2010, "Attempted to connect to session from different IP"))
-#                return False
-#
-#        if self.state == CLOSING or self.state == CLOSED:
-#            handler.send_pack(proto.disconnect(*self.get_close_reason()))
-#            return False
-#
-#        # Associate handler and promote session
-#        super(Session, self).set_handler(handler)
-#
-#        self.promote()
-#
-#        if start_heartbeat:
-#            self.start_heartbeat()
-#
-#        return True
-#
-#    def verify_state(self):
-#        """Verify if session was not yet opened. If it is, open it and call connections `on_open`"""
-#        # If we're in CONNECTING state - send 'o' message to the client
-#        if self.state == CONNECTING:
-#            self.handler.send_pack(proto.CONNECT)
-#
-#        # Call parent implementation
-#        super(Session, self).verify_state()
-#
-#    def remove_handler(self, handler):
-#        """Detach active handler from the session
-#
-#        `handler`
-#            Handler to remove
-#        """
-#        super(Session, self).remove_handler(handler)
-#
-#        self.promote()
-#        self.stop_heartbeat()
-#
-#    def send_message(self, msg, stats=True, binary=False):
-#        """Send or queue outgoing message
-#
-#        `msg`
-#            Message to send
-#        `stats`
-#            If set to True, will update statistics after operation completes
-#        """
-#        self.send_jsonified(proto.json_encode(msg), stats)
-#        # self.send_jsonified(proto.json_encode(bytes_to_str(msg)), stats)
-#
-#    def send_jsonified(self, msg, stats=True):
-#        """Send JSON-encoded message
-#
-#        `msg`
-#            JSON encoded string to send
-#        `stats`
-#            If set to True, will update statistics after operation completes
-#        """
-#        assert isinstance(msg, basestring), 'Can only send strings'
-#
-#        if isinstance(msg, unicode):
-#            msg = msg.encode('utf-8')
-#
-#        if self._immediate_flush:
-#            if self.handler and self.handler.active and not self.send_queue:
-#                # Send message right away
-#                self.handler.send_pack('a[%s]' % msg)
-#            else:
-#                if self.send_queue:
-#                    self.send_queue += ','
-#                self.send_queue += msg
-#
-#                self.flush()
-#        else:
-#            if self.send_queue:
-#                self.send_queue += ','
-#            self.send_queue += msg
-#
-#            if not self._pending_flush:
-#                self.server.gaplic.add_callback(self.flush)
-#                self._pending_flush = True
-#
-#        if stats:
-#            self.stats.on_pack_sent(1)
-#
-#    def flush(self):
-#        """Flush message queue if there's an active connection running"""
-#        self._pending_flush = False
-#
-#        if self.handler is None or \
-#                not self.handler.active or not self.send_queue:
-#            return
-#
-#        self.handler.send_pack('a[%s]' % self.send_queue)
-#        self.send_queue = ''
-#
-#    def close(self, code=3000, message='Go away!'):
-#        """Close session.
-#
-#        `code`
-#            Closing code
-#        `message`
-#            Closing message
-#        """
-#        if self.state != CLOSED:
-#            # Notify handler
-#            if self.handler is not None:
-#                self.handler.send_pack(proto.disconnect(code, message))
-#
-#        super(Session, self).close(code, message)
-#
-#    # Heartbeats
-#    def start_heartbeat(self):
-#        """Reset hearbeat timer"""
-#        self.stop_heartbeat()
-#
-#        self._heartbeat_timer = periodic.Callback(
-#            self._heartbeat,
-#            self._heartbeat_interval,
-#            self.server.gaplic
-#        )
-#        self._heartbeat_timer.start()
-#
-#    def stop_heartbeat(self):
-#        """Stop active heartbeat"""
-#        if self._heartbeat_timer is not None:
-#            self._heartbeat_timer.stop()
-#            self._heartbeat_timer = None
-#
-#    def delay_heartbeat(self):
-#        """Delay active heartbeat"""
-#        if self._heartbeat_timer is not None:
-#            self._heartbeat_timer.delay()
-#
-#    def _heartbeat(self):
-#        """Heartbeat callback"""
-#        if self.handler is not None:
-#            self.handler.send_pack(proto.HEARTBEAT)
-#        else:
-#            self.stop_heartbeat()
-#
-#    def on_messages(self, msg_list):
-#        """Handle incoming messages
-#
-#        `msg_list`
-#            Message list to process
-#        """
-#        self.stats.on_pack_recv(len(msg_list))
-#
-#        for msg in msg_list:
-#            self.conn.on_message(msg)

ginsfsm/protocols/sockjs/server/sessioncontainer.py

 
 from heapq import heappush, heappop
 from time import time
-from hashlib import md5
-from random import random
 from ginsfsm.utils import random_key
 
 
         """Expire any old entries
 
         `current_time`
-            Optional time to be used to clean up queue (can be used in unit tests)
+            Optional time to be used to clean up queue
+            (can be used in unit tests)
         """
         if not self._queue:
             return

ginsfsm/protocols/sockjs/server/stats.py

         # TODO: implement the periodic callbacks
         #self._callback = ioloop.PeriodicCallback(self._update,
         #                                         1000,
-        #                                         io_loop)
+        #                                         gaplic)
         #self._callback.start()
 
     def _update(self):

ginsfsm/protocols/wsgi/server/c_wsgi_server.py

                 self.config.maximum_simultaneous_requests,
         )
         self.serversock = self.ghttpserver.gserversock.socket
-
         # Used in environ
         self.effective_host, self.effective_port = self.getsockname()
         self.server_name = self._get_server_name(self.config.host)