我能够启动并运行这个基本示例
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')
您可以使用请求方法装饰器。
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/