找到了我自己解决这个问题的方法。诀窍是在将session_key
djangorequest
对象发送到服务器之前将其添加到 django-socketio 消息中;然后回到服务器端,您可以将其解析session_key
为 User 对象。这是代码:
模板文件:(由 django 服务器提供)
<input type="hidden" id="session_key" value="{{ request.session.session_key }}">
...
<script type="text/javascript" charset="utf-8">
function someHandler(action, post_id, some_val){
var data = {
'action': action,
'post_id': post_id,
'value': some_val,
'session_key': $("#session_key").val()
};
socket.send(data);
}
</script>
events.py:(由 django-socketio 服务器处理)
from django.contrib.sessions.models import Session
from django.contrib.auth.models import User
def message(request, socket, context, message):
session = Session.objects.get(session_key=message['session_key'])
uid = session.get_decoded().get('_auth_user_id')
user = User.objects.get(pk=uid)
利润!