使用Django / Redis / Node.js实时推/拉

我正在尝试在Django应用程序上添加实时更新,该应用程序具有与此处所述类似的体系结构: http : //lincolnloop.com/blog/2012/apr/23/ginger-tech-stack/ 。 基本上,更新从Django通过Redis发送到Node.js,然后通过Socket.io推送到连接的客户端。 现在,我可以向所有连接的客户端进行广播,但是我只需要通过一个动作(例如,用户发送消息,只有他的联系人/订阅者收到此消息)将数据发送给相关客户。 所以我需要在Node.js上进行一些authentication来知道谁是谁。 这怎么能实现?

       

网上收集的解决方案 "使用Django / Redis / Node.js实时推/拉"

这里是我的解决scheme到目前为止在socket.io/node.js(如果你有更好的解决scheme,随时发布)获得连接的用户的身份:

在Django方面:

  • 补丁Django使用json而不是pickle对象来存储会话数据:

    diff --git a/django/contrib/sessions/backends/base.py b/django/contrib/sessions/backends/base.py index 5a637e2..cb4db54 100644 --- a/django/contrib/sessions/backends/base.py +++ b/django/contrib/sessions/backends/base.py @@ -2,9 +2,9 @@ import time from datetime import datetime, timedelta try: - import cPickle as pickle + import json except ImportError: - import pickle + import simplejson as json from django.conf import settings from django.core.exceptions import SuspiciousOperation @@ -75,21 +75,21 @@ def _hash(self, value): return salted_hmac(key_salt, value).hexdigest() def encode(self, session_dict): - "Returns the given session dictionary pickled and encoded as a string." - pickled = pickle.dumps(session_dict, pickle.HIGHEST_PROTOCOL) - hash = self._hash(pickled) - return base64.encodestring(hash + ":" + pickled) + "Returns the given session dictionary as json and encoded as a string." + data = json.dumps(session_dict) + hash = self._hash(data) + return base64.encodestring(hash + ":" + data) def decode(self, session_data): encoded_data = base64.decodestring(session_data) try: # could produce ValueError if there is no ':' - hash, pickled = encoded_data.split(':', 1) - expected_hash = self._hash(pickled) + hash, data = encoded_data.split(':', 1) + expected_hash = self._hash(data) if not constant_time_compare(hash, expected_hash): raise SuspiciousOperation("Session data corrupted") else: - return pickle.loads(pickled) + return json.loads(data) except Exception: # ValueError, SuspiciousOperation, unpickling exceptions. If any of # these happen, just return an empty dictionary (an empty session). 

在Node.js端:

  • 从“sessionid”cookie中读取会话密钥:

     socket.on('connection', function(client) { ... var cookie_string = client.handshake.headers.cookie; var parsed_cookies = connect.utils.parseCookie(cookie_string); var sessionid = parsed_cookies['sessionid']; ... }); 
  • 从sessionid对应的db中检索并解码会话数据以获取用户标识。