仅通过 dJango SSE 服务器端事件在 POST 请求上广播数据

问题描述 投票:0回答:1

一旦用户发出请求,我就会尝试向所有客户端广播 SSE。

我能够启动并运行这个基本示例

async def dashboard_oc_interface(request):
    """
    Sends server-sent events to the client.
    """
    async def event_stream():
          
        i = 0   
        while True: 
            # yield {'id' : random.randint(0, 99) , 'status' : 'success'}
            yield f'data: {random.choice(range(1,40))},SUCCESS\n\n'
            await asyncio.sleep(100)

    return StreamingHttpResponse(event_stream(), content_type='text/event-stream')

但我不确定下面该怎么做:

# user will be making this request
def post_request(request): 
    success = random.choice([True, False]) # NOT ACTUAL LOGIC
    return JsonResponse ({'success' : success }) 

# I would like to stream the success data from above
async def stream():
    # HOW CAN I STREAM ONLY WHEN post request

# we will listen here 
async def event_stream(request):
    return StreamingHttpResponse(stream(), content_type='text/event-stream') 

您对此解决方案有何看法:性能方面:

data = set()

def oc_interface_communicate(request): 
    global data
    new_data = random.choice(range(1, 40))
    data.add(new_data) 
    return JsonResponse ({'data' : new_data }) 

async def post_request(request): 

    async def event_stream():
        global data  
        while True: 
            if len(data) != 0: 
                yield f'data: {'{},SUCCESS\n\n'.format(data.pop())},SUCCESS\n\n' 
            else: 
                await asyncio.sleep(0.1)

    return StreamingHttpResponse(event_stream(), content_type='text/event-stream')
python django real-time server-sent-events daphne
1个回答
0
投票

您可以使用请求方法装饰器。

from django.views.decorators.http import require_http_methods


@require_http_methods(["GET", "POST"])
def my_view(request):
    # I can assume now that only GET or POST requests make it this far
    # ...
    pass

https://docs.djangoproject.com/en/5.0/topics/http/decorators/

© www.soinside.com 2019 - 2024. All rights reserved.