0

我有一个简单的 django rest 框架,我想知道如何在我的项目中使用 StreamingHttpResponse。

我的模型是这样的:

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

这个模型的序列化器是这样的:

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

我认为我的问题出在 mu 视图或 url 中。所以我在视图中写了这样的代码:

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

event_stream 是这样的:

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)

网址是这样的:

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

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

我无法跟踪错误,所以我不知道我的问题在哪里,但是当使用此代码运行我的项目时,问题是这样的:

Object of type Article is not JSON serializable

当我更改 event_stream 函数时,错误更改如下:

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)

错误:

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

0 回答 0