| 1 |
import asyncio |
| 2 |
import threading |
| 3 |
import time |
| 4 |
|
| 5 |
from django.http import FileResponse, HttpResponse, StreamingHttpResponse |
| 6 |
from django.urls import path |
| 7 |
from django.views.decorators.csrf import csrf_exempt |
| 8 |
|
| 9 |
|
| 10 |
def hello(request): |
| 11 |
name = request.GET.get("name") or "World" |
| 12 |
return HttpResponse("Hello %s!" % name) |
| 13 |
|
| 14 |
|
| 15 |
def hello_with_delay(request): |
| 16 |
name = request.GET.get("name") or "World" |
| 17 |
time.sleep(1) |
| 18 |
return HttpResponse(f"Hello {name}!") |
| 19 |
|
| 20 |
|
| 21 |
def hello_meta(request): |
| 22 |
return HttpResponse( |
| 23 |
"From %s" % request.META.get("HTTP_REFERER") or "", |
| 24 |
content_type=request.META.get("CONTENT_TYPE"), |
| 25 |
) |
| 26 |
|
| 27 |
|
| 28 |
def sync_waiter(request): |
| 29 |
with sync_waiter.lock: |
| 30 |
sync_waiter.active_threads.add(threading.current_thread()) |
| 31 |
sync_waiter.barrier.wait(timeout=0.5) |
| 32 |
return hello(request) |
| 33 |
|
| 34 |
|
| 35 |
@csrf_exempt |
| 36 |
def post_echo(request): |
| 37 |
if request.GET.get("echo"): |
| 38 |
return HttpResponse(request.body) |
| 39 |
else: |
| 40 |
return HttpResponse(status=204) |
| 41 |
|
| 42 |
|
| 43 |
sync_waiter.active_threads = set() |
| 44 |
sync_waiter.lock = threading.Lock() |
| 45 |
sync_waiter.barrier = threading.Barrier(2) |
| 46 |
|
| 47 |
|
| 48 |
async def streaming_inner(sleep_time): |
| 49 |
yield b"first\n" |
| 50 |
await asyncio.sleep(sleep_time) |
| 51 |
yield b"last\n" |
| 52 |
|
| 53 |
|
| 54 |
async def streaming_view(request): |
| 55 |
sleep_time = float(request.GET["sleep"]) |
| 56 |
return StreamingHttpResponse(streaming_inner(sleep_time)) |
| 57 |
|
| 58 |
|
| 59 |
test_filename = __file__ |
| 60 |
|
| 61 |
|
| 62 |
urlpatterns = [ |
| 63 |
path("", hello), |
| 64 |
path("file/", lambda x: FileResponse(open(test_filename, "rb"))), |
| 65 |
path("meta/", hello_meta), |
| 66 |
path("post/", post_echo), |
| 67 |
path("wait/", sync_waiter), |
| 68 |
path("delayed_hello/", hello_with_delay), |
| 69 |
path("streaming/", streaming_view), |
| 70 |
] |