当我登录到我的前端时,我在django channels中的friends.consumer.py中调用self.scope['user']返回AnonymousUser,但当登录并在chat.consumer.py中调用self.scope['user']时,它显示为已登录的用户。出于某种原因,我的一个应用程序中的scope['user']可以工作,而另一个应用程序却不行。我不明白问题出在哪里。我在我的django项目中设置的路由是这样的。
路由.py
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import chat.routing
import friends.routing
application = ProtocolTypeRouter ({
'websocket': AuthMiddlewareStack(
URLRouter(
friends.routing.websocket_urlpatterns + chat.routing.websocket_urlpatterns
)
)
})
我的第二个 consumer.py 的结构与第一个 consumer.py 类似。这是我的 consumer.py,其中 scope['user']是有效的(我在第一个 consumer 中不需要 scope['user'],但我只是想测试一下它是否有效)。
聊天.消费者.py
class ChatConsumer(WebsocketConsumer):
...
def connect(self):
print(self.scope['user'])
self.room_name = self.scope['url_route']['kwargs']['room_name']
self.room_group_name = 'chat_%s' % self.room_name
# Join room group
async_to_sync (self.channel_layer.group_add)(
self.room_group_name,
self.channel_name
)
self.accept()
这段代码是我的scope['user']在登录后仍显示为匿名用户的消费者。
friends.consumer.py
class FriendRequestConsumer(JsonWebsocketConsumer):
def connect(self):
user = self.scope['user']
grp = 'notifications_{}'.format(user.username)
self.accept()
async_to_sync(self.channel_layer.group_add(grp, self.channel_name))
这里也是我为每个应用编写的路由.py
聊天.路由.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'^ws/friend-request-notification/$', consumers.FriendRequestConsumer),
]
聊天.路由.py
from django.urls import re_path
from . import consumers
websocket_urlpatterns = [
re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer),
]
我能够在我的reactjs前端连接到他们两个的websocket。我知道AuthMiddlewareStack允许我们拉动scope['user'],我只是不明白为什么一个能用,一个能用。会不会是我在前端没有正确连接到websocket,或者是我的一个消费者缺少了什么?我很感激你的帮助,并提前表示感谢。
为了在我的js中连接到websocket,我做了一个chat.js文件和一个notifications.js。
聊天.js
class Chat extends React.Component{
...
initialiseChat() {
this.waitForSocketConnection(()=> {
WebSocketInstance.fetchMessages(
this.props.username,
this.props.match.params.id
)
})
WebSocketInstance.connect(this.props.match.params.id)
}
constructor(props){
super(props)
this.initialiseChat()
}
通知.js
class Notifications extends React.Component{
...
initialiseNotification(){
this.waitForSocketConnection(() => {
NotificationWebSocketInstance.fetchFriendRequests(
this.props.id
)
})
NotificationWebSocketInstance.connect()
}
constructor(props){
super(props)
this.initialiseNotification()
}
下面是我的websocket动作。
webosocket.js (这个连接函数在chat.js中被调用)
class WebSocketService {
...
connect(chatUrl) {
const path ='ws://127.0.0.1:8000/ws/chat/'+chatUrl+'/';
console.log(path)
this.socketRef = new WebSocket(path)
this.socketRef.onopen = () => {
console.log('websocket open')
}
...
const WebSocketInstance = WebSocketService.getInstance();
export default WebSocketInstance;
这里是notification.js的websocket。
notificationWebsocket.js
class WebSocketNotifications {
...
connect(){
const path = 'ws://127.0.0.1:8000/ws/friend-request-notification/'
console.log(path)
this.socketRef = new WebSocket(path)
this.socketRef.onopen = () =>{
console.log('websocket open')
}
...
const NotificationWebSocketInstance =
WebSocketNotifications.getInstance();
export default NotificationWebSocketInstance;
这里是路由.js
class BaseRouter extends React.Component {
<Route exact path = '/chat/:id' render={(props) => <Chat {...props}
{...this.props} isAuthenticated={this.props.isAuthenticated} />}
/>
<Route exact path = '/notifications/' render={(props) =>
<Notifications {...props} {...this.props} isAuthenticated=
{this.props.isAuthenticated} />} />
一定是你的令牌中间件出了问题