0

i have a simple django rest framework and i want to know how can use StreamingHttpResponse in my project.

my model is like this:

class Article(models.Model):
    user = models.CharField(max_length=100)
    title = models.CharField(max_length=200)
    description = models.TextField()
    date = models.DateTimeField(auto_now_add=True)

    def __str__(self): 
          return self.title

and serializer for this model is like this:

class ArticleSerializers(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'user', 'title', 'description', 'date']

i think my problem is in mu view or url. so i wrote code in view like this:

class StreamPost(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    serializer_class = ArticleSerializers

    def get_queryset(self):
        stream = event_stream()
        response = StreamingHttpResponse(stream, status=200, content_type='text/event-stream')
        response['Cache-Control'] = 'no-cache'
        return response

that the event_stream is like this:

def event_stream():
    initial_data = ''
    while True:
        list_article = list(Article.objects.all())
        data = json.dumps(list_article, cls=DjangoJSONEncoder)

        if not initial_data == data:
            yield "\ndata: {}\n\n".format(data)
            initial_data = data
        time.sleep(1)

the url is like this:

router = DefaultRouter()
router.register('stream', StreamPost, basename='stream')
urlpatterns = [
    path('', include(router.urls)),
    
]

urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

i can't track the error and so i don't know where is my problem but when run my project with this codes the problem is like this:

Object of type Article is not JSON serializable

when i change the event_stream function the error changed like this:

def event_stream():
    initial_data = ''
    while True:
        list_article = list(Article.objects.all().values('id', 'user', 'title', 'description', 'date'))
        data = json.dumps(list_article, cls=DjangoJSONEncoder)

        if not initial_data == data:
            yield "\ndata: {}\n\n".format(data)
            initial_data = data
        time.sleep(1)

the error:

Got AttributeError when attempting to get a value for field `user` on serializer `ArticleSerializers`.
The serializer field might be named incorrectly and not match any attribute or key on the `bytes` instance.
Original exception text was: 'bytes' object has no attribute 'user'.
Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
  • You're supposed to return a queryeset from `get_queryset` method of your view not a `StreamingHttpResponse` object. Return the `StreamingHttpResponse` from a ModelViewSet method e.g. - list, create, retrieve, update, partial_update etc. – alamshafi2263 Feb 03 '22 at 09:05
  • i put the StreamHttpRequest on list and this error appear: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. – Shahram Zarie Feb 03 '22 at 09:08

0 Answers0