2023-07-29 08:43:15 +00:00
|
|
|
import asyncio
|
2021-06-30 15:37:10 +00:00
|
|
|
import threading
|
2022-12-21 19:25:24 +00:00
|
|
|
import time
|
2021-06-30 15:37:10 +00:00
|
|
|
|
2023-07-29 08:43:15 +00:00
|
|
|
from django.http import FileResponse, HttpResponse, StreamingHttpResponse
|
2019-04-12 13:15:18 +00:00
|
|
|
from django.urls import path
|
2022-05-30 20:45:48 +00:00
|
|
|
from django.views.decorators.csrf import csrf_exempt
|
2019-04-12 13:15:18 +00:00
|
|
|
|
|
|
|
|
2019-06-17 14:27:04 +00:00
|
|
|
def hello(request):
|
|
|
|
name = request.GET.get("name") or "World"
|
|
|
|
return HttpResponse("Hello %s!" % name)
|
|
|
|
|
|
|
|
|
2022-12-21 19:25:24 +00:00
|
|
|
def hello_with_delay(request):
|
|
|
|
name = request.GET.get("name") or "World"
|
|
|
|
time.sleep(1)
|
|
|
|
return HttpResponse(f"Hello {name}!")
|
|
|
|
|
|
|
|
|
2019-06-17 14:27:04 +00:00
|
|
|
def hello_meta(request):
|
|
|
|
return HttpResponse(
|
|
|
|
"From %s" % request.META.get("HTTP_REFERER") or "",
|
|
|
|
content_type=request.META.get("CONTENT_TYPE"),
|
|
|
|
)
|
2019-04-12 13:15:18 +00:00
|
|
|
|
|
|
|
|
2021-06-30 15:37:10 +00:00
|
|
|
def sync_waiter(request):
|
|
|
|
with sync_waiter.lock:
|
|
|
|
sync_waiter.active_threads.add(threading.current_thread())
|
|
|
|
sync_waiter.barrier.wait(timeout=0.5)
|
|
|
|
return hello(request)
|
|
|
|
|
|
|
|
|
2022-05-30 20:45:48 +00:00
|
|
|
@csrf_exempt
|
|
|
|
def post_echo(request):
|
2022-06-02 21:19:16 +00:00
|
|
|
if request.GET.get("echo"):
|
|
|
|
return HttpResponse(request.body)
|
|
|
|
else:
|
|
|
|
return HttpResponse(status=204)
|
2022-05-30 20:45:48 +00:00
|
|
|
|
|
|
|
|
2021-06-30 15:37:10 +00:00
|
|
|
sync_waiter.active_threads = set()
|
|
|
|
sync_waiter.lock = threading.Lock()
|
|
|
|
sync_waiter.barrier = threading.Barrier(2)
|
|
|
|
|
|
|
|
|
2023-07-29 08:43:15 +00:00
|
|
|
async def streaming_inner(sleep_time):
|
|
|
|
yield b"first\n"
|
|
|
|
await asyncio.sleep(sleep_time)
|
|
|
|
yield b"last\n"
|
|
|
|
|
|
|
|
|
|
|
|
async def streaming_view(request):
|
|
|
|
sleep_time = float(request.GET["sleep"])
|
|
|
|
return StreamingHttpResponse(streaming_inner(sleep_time))
|
|
|
|
|
|
|
|
|
2019-04-12 13:15:18 +00:00
|
|
|
test_filename = __file__
|
|
|
|
|
|
|
|
|
|
|
|
urlpatterns = [
|
2019-06-17 14:27:04 +00:00
|
|
|
path("", hello),
|
2019-04-12 13:15:18 +00:00
|
|
|
path("file/", lambda x: FileResponse(open(test_filename, "rb"))),
|
2019-06-17 14:27:04 +00:00
|
|
|
path("meta/", hello_meta),
|
2022-05-30 20:45:48 +00:00
|
|
|
path("post/", post_echo),
|
2021-06-30 15:37:10 +00:00
|
|
|
path("wait/", sync_waiter),
|
2022-12-21 19:25:24 +00:00
|
|
|
path("delayed_hello/", hello_with_delay),
|
2023-07-29 08:43:15 +00:00
|
|
|
path("streaming/", streaming_view),
|
2019-04-12 13:15:18 +00:00
|
|
|
]
|