O
O
opgmc2021-05-27 14:32:21
Django
opgmc, 2021-05-27 14:32:21

How to fix AttributeError: 'ASGIRequest' object has no attribute 'accept' error?

Please help me figure out the error. Created a web application with django. I connected web sockets according to the instructions ( https://alex-oleshkevich.medium.com/websockets-in-... ).
When the web application starts, it connects to web sockets using js ( ws://localhost/websocket/ ). Actually, an error occurs during the websocket.accept event:

Internal Server Error: /websocket/
Traceback (most recent call last):
  File "/home/pi/microwire/venv/lib/python3.7/site-packages/asgiref/sync.py", line 458, in thread_handler
    raise exc_info[1]
  File "/home/pi/microwire/venv/lib/python3.7/site-packages/django/core/handlers/exception.py", line 38, in inner
    response = await get_response(request)
  File "/home/pi/microwire/venv/lib/python3.7/site-packages/django/core/handlers/base.py", line 233, in _get_response_async
    response = await wrapped_callback(request, *callback_args, **callback_kwargs)
  File "./app/views.py", line 76, in websocket
    await socket.accept()
AttributeError: 'ASGIRequest' object has no attribute 'accept'


List of dependencies:
asgiref             3.3.4   
click               7.1.2   
Django              3.2.3   
django-user-agents  0.4.0   
djangorestframework 3.12.4  
gunicorn            20.1.0  
h11                 0.12.0  
pip                 18.1    
pkg-resources       0.0.0   
psycopg2            2.8.6   
pytz                2021.1  
setuptools          40.8.0  
sqlparse            0.4.1   
typing-extensions   3.10.0.0
ua-parser           0.10.0  
user-agents         2.2.0   
uvicorn             0.13.4


views.py:
from django.http import *
from django.shortcuts import render
from .models import Settings
from microwire.connection import WebSocket

async def websocket(socket: WebSocket):
    await socket.accept()
    while True:
        message = await socket.receive_text()
        await socket.send_text(message)

def index(request):
    current_settings = Settings.objects.all()[0]
    settings = Settings.objects.all()[1:]
    return render(request, 'index.html', {'current_settings': current_settings, 'settings': settings})


URLs.py:
from app import views
from django.urls import path, include

websocket = path

urlpatterns = [
    websocket('websocket/', views.websocket),
    path('', views.index)
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
alexbprofit, 2021-05-27
@alexbprofit

pip install channels

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question