Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ValueError: HTTP response has not yet been started but got http.response.body - web page is freezing on loading. #344

Open
HT-Moh opened this issue Nov 4, 2020 · 3 comments

Comments

@HT-Moh
Copy link

HT-Moh commented Nov 4, 2020

Hi
I am facing an issue which I am trying to resolve for quite a long time now.
Background
The integration of Daphne with Django and Channels "was working" fine but suddenly stopped working, and I am getting the problem "ValueError: HTTP response has not yet been started but got http.response.body" which I can not resolve. I have ws endpoint which trigger the consumer make celery task calls, I simplified the consumer to the minimum to check if the problem disappear but no luck.
The setup I had it with Django 2 but upgraded to Django 3 to solve the problem but same problem.

channels == 3.0.0
django == 3.1.3
channels-redis == 3.2.0

/static/tradeplatform/styles/scss/dashboard.css' http.response.body
Start writing request
Stop writing request
{'type': 'http.response.body'}
127.0.0.1:33644 - - [04/Nov/2020:12:20:11] "GET /static/tradeplatform/styles/scss/dashboard.css" 304 -
b'/static/jquery/dist/jquery.min.js' http.response.start
b'/static/jquery/dist/jquery.min.js' http.response.body
Start writing request
Stop writing request
{'type': 'http.response.body'}
127.0.0.1:33644 - - [04/Nov/2020:12:20:11] "GET /static/jquery/dist/jquery.min.js" 304 -
2020-11-04 12:20:12,537 ERROR    Exception inside application: HTTP response has not yet been started but got http.response.body
Traceback (most recent call last):
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/channels/routing.py", line 71, in __call__
    return await application(scope, receive, send)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/channels/http.py", line 200, in __call__
    await self.handle(body_stream)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/asgiref/sync.py", line 304, in __call__
    ret = await asyncio.wait_for(future, timeout=None)
  File "/usr/lib/python3.8/asyncio/tasks.py", line 455, in wait_for
    return await fut
  File "/usr/lib/python3.8/concurrent/futures/thread.py", line 57, in run
    result = self.fn(*self.args, **self.kwargs)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/asgiref/sync.py", line 343, in thread_handler
    return func(*args, **kwargs)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/channels/http.py", line 258, in handle
    self.send(response_message)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/asgiref/sync.py", line 147, in __call__
    return call_result.result()
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 432, in result
    return self.__get_result()
  File "/usr/lib/python3.8/concurrent/futures/_base.py", line 388, in __get_result
    raise self._exception
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/asgiref/sync.py", line 212, in main_wrap
    result = await self.awaitable(*args, **kwargs)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/server.py", line 233, in handle_reply
    protocol.handle_reply(message)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/http_protocol.py", line 262, in handle_reply
    raise ValueError(
ValueError: HTTP response has not yet been started but got http.response.body
b'/static/bootstrap4/dist/css/bootstrap.min.css' http.response.start
2020-11-04 12:20:12,540 ERROR    Exception in callback AsyncioSelectorReactor.callLater.<locals>.run() at /home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287
handle: <TimerHandle when=67852.310794924 AsyncioSelectorReactor.callLater.<locals>.run() at /home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py:287>
Traceback (most recent call last):
  File "/usr/lib/python3.8/asyncio/events.py", line 81, in _run
    self._context.run(self._callback, *self._args)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/twisted/internet/asyncioreactor.py", line 290, in run
    f(*args, **kwargs)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/server.py", line 295, in application_checker
    protocol.handle_exception(exception)
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/http_protocol.py", line 307, in handle_exception
    self.basic_error(500, b"Internal Server Error", "Exception inside application.")
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/http_protocol.py", line 348, in basic_error
    self.handle_reply(
  File "/home/moh/codess/trade-platoform/.venv/lib/python3.8/site-packages/daphne/http_protocol.py", line 244, in handle_reply
    raise ValueError("HTTP response has already been started")
ValueError: HTTP response has already been started
b'/media/img/components_images/WTP%20Product%20Images/TagFa
 

The code

# wsgi
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myapp.settings")
application = get_wsgi_application()
# asgi.py
import os
import django
from myapp.wsgi import *
from channels.routing import get_default_application

from channels.sessions import SessionMiddlewareStack
from tp_celery.consumers import UpdateOrderStatus
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from myapp.routing import websocket_urlpatterns
application = ProtocolTypeRouter({

    "websocket": SessionMiddlewareStack(
        URLRouter(websocket_urlpatterns)
    ),

})
# 
rooting.py
from tp_celery.consumers import UpdateOrderStatus
from django.urls import path

websocket_urlpatterns = [
    path("ws/update-order-status/", UpdateOrderStatus),
]
# consummer.py
from channels.consumer import SyncConsumer

class UpdateOrderStatus(SyncConsumer):

    def websocket_connect(self, event):
        self.send({
            "type": "websocket.accept",
        })

    def websocket_receive(self, event):
        self.send({
            "type": "websocket.send",
            "text": event["text"],
        })


What I notice as well by simplifying the page template if I delete the row where we use the static `link href="{% static 'awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css' %}" rel="stylesheet" />
the page is loading and it's not blocked, and If I add a any source using static it does freeze.

{% load i18n  sekizai_tags static sass_tags %}

<!doctype html>
<html lang="en">
<head>
    <title>Tradeplatform</title>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="description" content="{% block tp_desc %}Tradeplatform description{% endblock %}">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/all.css">
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.14.0/css/v4-shims.css">
    <link href="{% static 'bootstrap4/dist/css/bootstrap.min.css' %}" rel="stylesheet" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css?family=Ubuntu" rel="stylesheet">

    <!-- <link href="{% static 'bootstrap-datepicker/dist/css/bootstrap-datepicker.min.css' %}" rel="stylesheet" /> -->
    <link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/daterangepicker/daterangepicker.css" />

    <link href="{% static 'awesome-bootstrap-checkbox/awesome-bootstrap-checkbox.css' %}" rel="stylesheet" />

</head>

</body>

</html>
``
@arthtyagi
Copy link

Yeah, I'm facing the same issue. That too out of the blue, what do I even do in such a situation?

@carltongibson
Copy link
Member

Upgrade to Channels 3.0.1, and make sure to review the 3.0.0 release notes — it's a major version upgrade.

At the least it looks like you'll need to as as_asgi() calls when routing your consumers.

@arthtyagi
Copy link

That doesn't work. Also looked at the docs and changed my code as indicated.

asgi.py

"""
import os
import django

# from django.core.asgi import get_asgi_application

from channels.routing import get_default_application

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'domecode.devsettings')
django.setup()  # to deploy with asgi when using channels
application = get_default_application()
"""
change devsettings to settings when deploying
"""

routing.py - project level

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import messaging.routing

application = ProtocolTypeRouter({
    # (http -> django views is added by default)
    'websocket':
    AuthMiddlewareStack(URLRouter(messaging.routing.websocket_urlpatterns), ),
})

routing.py - application level ( messaging )

from messaging import consumers
from django.urls import re_path

websocket_urlpatterns = [
    re_path(r'^wss$', consumers.ChatConsumer.as_asgi()),
    # change to ws during testing
]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants