django 3 create async rest api

Solutions on MaxInterview for django 3 create async rest api by the best coders in the world

showing results for - "django 3 create async rest api"
Kaleb
17 Mar 2016
1import asyncio
2import concurrent.futures
3import os
4import django
5from starlette.applications import Starlette
6from starlette.responses import Response
7from starlette.routing import Route
8
9os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pjt.settings')
10django.setup()
11
12from django_app.xxx import synchronous_func1
13from django_app.xxx import synchronous_func2
14
15executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)
16
17async def simple_slow(request):
18    """ simple function, that sleeps in an async matter """
19    await asyncio.sleep(5)
20    return Response('hello world')
21
22async def call_slow_dj_funcs(request):
23    """ slow django code will be called in a thread pool """
24    loop = asyncio.get_running_loop()
25    future_func1 = executor.submit(synchronous_func1)
26    func1_result = future_func1.result()
27    future_func2 = executor.submit(synchronous_func2)
28    func2_result = future_func2.result()
29    response_txt = "OK"
30    return Response(response_txt, media_type="text/plain")
31
32routes = [
33    Route("/simple", endpoint=simple_slow),
34    Route("/slow_dj_funcs", endpoint=call_slow_dj_funcs),
35]
36
37app = Starlette(debug=True, routes=routes)
38