Commits

Łukasz Fidosz committed a239d13

some small fixes

Comments (0)

Files changed (3)

gevent_cometd/app_views.py

 
 try:
     import json
-except ImportError, e:
+except ImportError:
     import simplejson as json
 import uuid
 
     res.headers.add('Access-Control-Allow-Headers', 'Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control, Pragma, Origin')
     res.headers.add('Access-Control-Max-Age', '86400')
 
+
 def get_channel(channel):
     # create new channel if it doesnt exist yet
     if channel and channel not in channels:
         return channels[channel]
     return None
 
+
 class DateTimeEncoder(json.JSONEncoder):
     def default(self, obj):
         if isinstance(obj, datetime.date):
             return obj.isoformat()      
         return json.JSONEncoder.default(self, obj)
 
+
 class Channel(object):
     
     def __init__(self, name, long_name=None):
         self.persistance = False
         
     def add_message(self, message, exclude_user=None):
-        message.update({'channel':self.name})
+        message.update({'channel': self.name})
         for client in self.clients:
             if client.user != exclude_user:
                 client.add_message(message)
         res.status = 403
     try:
         request_data = json.loads(request.body)
-    except ValueError, e:
+    except ValueError:
         res = Response(json.dumps({'error':"Malformed json"}),
                        request=request)
         res.status = 400
-    return request_data , res
+    return (request_data, res)
 
 class Client(object):
     def __init__(self, user):
     user = request_data.get('user')
     subscribe_to_channels = request_data.get('channels')
     if not user:
-        res = Response(json.dumps({'error':"No username specified"}),
+        res = Response(json.dumps({'error': "No username specified"}),
                        request=request)
         res.status = 400
     elif not subscribe_to_channels:
-        res = Response(json.dumps({'error':"No channels specified"}),
+        res = Response(json.dumps({'error': "No channels specified"}),
                        request=request)
         res.status = 400        
     else: 
             #user gets assigned to a channel
             channel.add_client(client)
             if channel.persistance:
-                message = {'user':client.user,
-                   'message':None,
-                   'type':'join',
-                   'timestamp':timestmp
+                message = {'user': client.user,
+                   'message': None,
+                   'type': 'join',
+                   'timestamp': timestmp
                    }
                 stats['total_unique_messages'] += 1
                 channel.add_message(message, exclude_user=client.user)
                 if client.user == chan_client.user:
                     send_join_msg = False
             if send_join_msg: 
-                message = {'user':client.user,
-                   'message':None,
-                   'type':'join',
-                   'timestamp':timestmp
+                message = {'user': client.user,
+                   'message': None,
+                   'type': 'join',
+                   'timestamp': timestmp
                    }
                 stats['total_unique_messages'] += 1
                 channel.add_message(message, exclude_user=client.user)                        
     if res:
         return res
     timestmp = datetime.datetime.utcnow()
-    message = {'user':request_data.get('user'),
-               'message':request_data['message'],
+    message = {'user': request_data.get('user'),
+               'message': request_data['message'],
                'type':'message',
-               'timestamp':timestmp
+               'timestamp': timestmp
                }
     channel = get_channel(request_data.get('channel'))
     pm_user = request_data.get('pm_user')
     """this is where we pick up our responses"""
     client = clients.get(request.params.get('conn_id'))
     if not client:
-        res = Response(json.dumps({'error':"Unknown client"}),
+        res = Response(json.dumps({'error': "Unknown client"}),
                        request=request)
         res.status = 400
         return res
     client.gc_marker()
     if request.method.upper() == 'OPTIONS':
         #preflight
-        res = Response(' '*2048, request=request,
+        res = Response(' ' * 2048, request=request,
                        content_type='application/json')
         add_cors_headers(res)
         return res

gevent_cometd/start.py

 from gevent_cometd import config
 from webob import Request, exc
 
+
 log = logging.getLogger(__name__)
 
 
-
 class WSGIHandler(object):
         
     def __call__(self, environ, start_response):
         """ try to find the right request"""
         req = Request(environ)
+
+        #pop the / from path
+        query_parts = req.path[1:].split('/')
+        action = query_parts[0]
+        if not action:
+            action = 'index'
+
+        #try to find the action
         try:
-            #try to find the action
-            try:
-                #pop the / from path
-                query_parts = req.path[1:].split('/')
-                action = query_parts[0]
-                if action in ['', '/']:
-                    action = 'index'
-                method = getattr(app_views, action)
-            except AttributeError, e:
-                raise exc.HTTPBadRequest('No such action %r' % action)
+            method = getattr(app_views, action)
+        except AttributeError:
+            raise exc.HTTPBadRequest('No such action %r' % action)
+
+        try:
             res = method(req, *query_parts[1:])
         except exc.HTTPException, e:
             # The exception object itself is a WSGI application/response:
             res = e
+
         #return proper response
         return res(environ, start_response)
     
                 if channel.clients[x].conn_id in to_remove:
                     del channel.clients[x]
         if removed_total:
-            print "GC'd %s users" % len(to_remove)
+            print "GC'd %i users" % removed_total
         
 
 def cli_start():
     print 'Serving on 0.0.0.0:%s' % config['port'] 
     app = WSGIHandler()
     gevent.spawn(garbage_control)
-    pywsgi.WSGIServer(('', config['port']), app).serve_forever()
+    pywsgi.WSGIServer(('', config['port']), app).serve_forever()
       packages=find_packages(),
       install_requires=[
           'gevent',
-          "webob",
+          'webob',
+          'tempita'
       ],
       entry_points="""
       [console_scripts]