> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/django/21django3-shi-xian-websocket-zui-jian-dan-demo.md).

# 21、Django3实现Websocket最简单demo

## django3实现Websocket最简单demo

> 根据本文步骤可配出来最简单的一个demo。

### 1. 新建django项目

### 2.安装依赖

```python
pip install channels
```

{% hint style="success" %}
安装channels之后，

在 setttings.py 的 INSTALLED\_APPS 里添加 channels。

注意每个app后面加上逗号。
{% endhint %}

### 3.修改为Asgi

将asgi.py文件的内容更改为：(这是一个仅支持http的写法，方便后面测试，支持websocket的路由后面会给出）

```python
import os

from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
})
```

在settings.py中添加(myproject替换为你的project名称)

```python

ASGI_APPLICATION = "myproject.asgi.application"
```

{% hint style="info" %}
这个时候运行项目应该可以看到出现了：&#x20;

Starting ASGI/Channels version 3.0.4 development server at <http://127.0.0.1:8000/>
{% endhint %}

### 4.新建消费者（类似于views，负责接受连接、接收消息等操作）

新建APP，假设为'backend'。

在backend目录新建consumers.py，填写代码为：（类名自定义，和下面的代码对应就行）

```python
import json
from channels.generic.websocket import WebsocketConsumer

class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.accept()

    def disconnect(self, close_code):
        pass

    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']

        self.send(text_data=json.dumps({
            'message': message
        }))
```

注意这种写法要求前端发送的消息为json，且消息内容放在'message'key下。即前端发送的消息为

```python
{"message":"消息内容"}
```

{% hint style="danger" %}
如果不是这样的格式修改 receive 函数即可。

该文件负责定义websocket的连接、接收消息等操作。
{% endhint %}

### 5.修改路由

```python
# 新建routing.py，填写内容为：
from django.urls import re_path

from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/$', consumers.ChatConsumer.as_asgi()),
]
```

然后修改我们的asgi为：

```python

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.core.asgi import get_asgi_application
import backend.routing

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")

application = ProtocolTypeRouter({
  "http": get_asgi_application(),
  "websocket": AuthMiddlewareStack(
        URLRouter(
            backend.routing.websocket_urlpatterns
        )
    ),
})
```

OK，大功告成，此时后端的WebSocket就写好了，在配合一个前端就可以使用了。


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://close.gitbook.io/yun-wei-bi-ji/python/django/21django3-shi-xian-websocket-zui-jian-dan-demo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
