how to use StreamingHttpResponse in django rest framework?

1.3k Views Asked by At

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'.
0

There are 0 best solutions below