我是django-websocket-redis的新手,不能用它来发布消息。收到心跳消息,但是关于来自后端的已发布消息,前端收到最后一条消息(页面重新加载后),忽略其他消息。这是我的代码结构:
-mysite
|- __init__.py
|-settings.py
|-urls.py
|-wsgi.py
-websockets
|-migrations
|-__init__.py
|-templates
|-index.html
|-__init__.py
|-admin.py
|-models.py
|-tests.py
|-urls.py
|-views.py
-db.sqlite3
-manage.py
和settings.py:
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))
DEBUG = True
TEMPLATE_DEBUG = True
ALLOWED_HOSTS = []
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
SITE_ID = 1
ROOT_URLCONF = 'mysite.urls'
SECRET_KEY = 'super.secret'
MEDIA_ROOT = ''
MEDIA_URL = ''
STATIC_ROOT = os.environ.get('DJANGO_STATIC_ROOT', '')
STATIC_URL = '/static/'
SESSION_ENGINE = 'redis_sessions.session'
SESSION_REDIS_PREFIX = 'session'
TEMPLATE_CONTEXT_PROCESSORS = (
'django.contrib.auth.context_processors.auth',
'django.core.context_processors.static',
'django.core.context_processors.request',
'ws4redis.context_processors.default',
)
TEMPLATE_LOADERS = (
'django.template.loaders.app_directories.Loader',
)
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Europe/Berlin'
USE_I18N = True
USE_L10N = True
USE_TZ = True
INSTALLED_APPS = (
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'ws4redis',
'websockets',
)
MIDDLEWARE_CLASSES = (
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
WSGI_APPLICATION = 'ws4redis.django_runserver.application'
WEBSOCKET_URL = '/ws/'
WS4REDIS_EXPIRE = 3600
WS4REDIS_HEARTBEAT = '--heartbeat--'
WS4REDIS_PREFIX = 'demo'
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'simple': {
'format': '[%(asctime)s %(module)s] %(levelname)s: %(message)s'
},
},
'handlers': {
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler',
'formatter': 'simple',
},
},
'loggers': {
'django': {
'handlers': ['console'],
'level': 'DEBUG',
'propagate': True,
},
},
}
的WebSockets / views.py:
class BroadcastChatView(TemplateView):
template_name = 'websockets/index.html'
def get(self, request, *args, **kwargs):
welcome = RedisMessage('Hello everybody') # create a welcome message to be sent to everybody
RedisPublisher(facility='foobar', broadcast=True).publish_message(welcome)
return super(BroadcastChatView, self).get(request, *args, **kwargs)
的WebSockets / index.html中:
<div id="billboard"></div>
<button type="button" id="send_message">click to send message</button>
<!--<input type="text" id="text_message">-->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="{{ STATIC_URL }}js/ws4redis.js" type="text/javascript"></script>
<script>
jQuery(document).ready(function($) {
var ws4redis = WS4Redis({
uri: ' ws://localhost:8080/ws/foobar?subscribe-broadcast&publish-broadcast&echo',
receive_message: receiveMessage,
heartbeat_msg: {{ WS4REDIS_HEARTBEAT }}
});
var billboard = $('#billboard');
// attach this function to an event handler on your site
function sendMessage() {
ws4redis.send_message('A message');
}
// receive a message though the websocket from the server
function receiveMessage(msg) {
console.log('Message from Websocket: ' + msg);
billboard.append('<br/>' + msg);
billboard.scrollTop(billboard.scrollTop() + 25);
}
$('#send_message').click(function() {
ws4redis.send_message("hello");
});
});
</script>
和mysite / wsgi.py:
import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')
from django.conf import settings
from django.core.wsgi import get_wsgi_application
from ws4redis.uwsgi_runserver import uWSGIWebsocketServer
_django_app = get_wsgi_application()
_websocket_app = uWSGIWebsocketServer()
def application(environ, start_response):
if environ.get('PATH_INFO').startswith(settings.WEBSOCKET_URL):
return _websocket_app(environ, start_response)
return _django_app(environ, start_response)