zoukankan      html  css  js  c++  java
  • django channle的使用

    频道在PyPI上可用 - 要安装它,只需运行:   参照:https://channels.readthedocs.io/en/latest/introduction.html

    pip install -U channels

    安装 channels_redis
    pip install channels_redis

    安装redis: windows 参照 https://www.cnblogs.com/juncaoit/p/10122642.html
    ubuntu 参照以下命令
    apt-get install redis-server

    完成后,您应该添加channels到您的 INSTALLED_APPS设置:

    INSTALLED_APPS = (
        'django.contrib.auth',
        'django.contrib.contenttypes',
        'django.contrib.sessions',
        'django.contrib.sites',
        ...
        'channels',
    )
    

    然后,在以下位置进行默认路由myproject/routing.py

    # mysite/routing.py
    from channels.auth import AuthMiddlewareStack
    from channels.routing import ProtocolTypeRouter, URLRouter
    import apiService.routing
    
    application = ProtocolTypeRouter({
        # (http->django views is added by default)
        'websocket': AuthMiddlewareStack(
            URLRouter(
                apiService.routing.websocket_urlpatterns
            )
        ),
    })

    最后,将您的ASGI_APPLICATION设置设置为指向该路由对象作为根应用程序:

    ASGI_APPLICATION = "myproject.routing.application"
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels_redis.core.RedisChannelLayer',
            'CONFIG': {
                "hosts": [('127.0.0.1', 6379)],
            },
        },
    }

    一旦启用本地服务,channels也将在响应的端口启用ws服务 (服务器上则不同)

    apiService中的路由:

    # chat/routing.py
    # from django.urls import path
    from django.conf.urls import url
    from . import consumers,admin_ws
    
    websocket_urlpatterns = [
        # path('ws/admin_chat/:admin_id/', admin_ws.AdminWs),
        # path('ws/cons_chat/:cons_id/', consumers.ChatConsumer),
        url(r'^ws/admin_chat/(?P<admin_id>[^/]+)/$', admin_ws.AdminWs),
        url(r'^ws/cons_chat/(?P<cons_id>[^/]+)/$', consumers.ChatConsumer),
        # url(r'^ws/chat/(?P<room_name>[^/]+)/$', consumers.ChatConsumer),
    ]

    注:服务器上要用:supervisor 和 asgi来部署。为了避免mysql链接失效:

    from django.db import close_old_connections 
    
    # 自己定义一个decorator,用来装饰使用数据库的函数
    def close_old_connections_wrapper(func):
        def wrapper(*args, **kwargs):
            close_old_connections()
            return func(*args, **kwargs)
    
        return wrapper

    可在connect函数中调用   close_old_connections 

  • 相关阅读:
    React中 checkbox 与 label 标签的搭配
    HTML5 FileReader对象
    HTML5 FormData 模拟表单控件 支持异步上传二进制文件 移动端
    Nginx 反向代理
    HTML5触摸事件
    利用React遍历数组,并且用数组的元素生成<li>arrItem</li>标签组
    ECMAScript5 [].reduce()
    E:Unable to locate package
    mv和cp命令
    Error response from daemon: Conflict. The container name "xinying_face" is already in use by container
  • 原文地址:https://www.cnblogs.com/Mvloveyouforever/p/10598028.html
Copyright © 2011-2022 走看看