Skip to content

Commit

Permalink
Threadpool test in API view
Browse files Browse the repository at this point in the history
  • Loading branch information
theognis1002 committed Feb 19, 2023
1 parent 5e7ce23 commit 85aa221
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
16 changes: 16 additions & 0 deletions apps/products/api/views.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
import asyncio
import concurrent.futures

import requests
from django.contrib.auth import get_user_model
from rest_framework.decorators import action
from rest_framework.response import Response
Expand All @@ -15,6 +17,12 @@ async def fetch_ip():
return "123.42.941"


def fetch_headers():
response = requests.get("http://httpbin.org/headers")
print(response.status_code)
return response.json()


class UserViewSet(ModelViewSet):
serializer_class = UserSerializer
queryset = User.objects.all()
Expand All @@ -25,3 +33,11 @@ def ip(self, request):
asyncio.set_event_loop(loop)
ip = loop.run_until_complete(fetch_ip())
return Response({"result": ip})

@action(detail=False, methods=["get"])
def headers(self, request):
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
futures = [executor.submit(fetch_headers) for _ in range(2)]
for future in concurrent.futures.as_completed(futures):
future.result()
return Response({"result": "ok"})
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@ python-dateutil==2.8.2
pytz==2021.1
PyYAML==6.0
regex==2021.8.28
requests
six==1.16.0
sqlparse==0.4.1
text-unidecode==1.3
Expand Down

0 comments on commit 85aa221

Please sign in to comment.