Search
 
SCRIPT & CODE EXAMPLE
 

PYTHON

django 3 create async rest api

import asyncio
import concurrent.futures
import os
import django
from starlette.applications import Starlette
from starlette.responses import Response
from starlette.routing import Route

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pjt.settings')
django.setup()

from django_app.xxx import synchronous_func1
from django_app.xxx import synchronous_func2

executor = concurrent.futures.ThreadPoolExecutor(max_workers=2)

async def simple_slow(request):
    """ simple function, that sleeps in an async matter """
    await asyncio.sleep(5)
    return Response('hello world')

async def call_slow_dj_funcs(request):
    """ slow django code will be called in a thread pool """
    loop = asyncio.get_running_loop()
    future_func1 = executor.submit(synchronous_func1)
    func1_result = future_func1.result()
    future_func2 = executor.submit(synchronous_func2)
    func2_result = future_func2.result()
    response_txt = "OK"
    return Response(response_txt, media_type="text/plain")

routes = [
    Route("/simple", endpoint=simple_slow),
    Route("/slow_dj_funcs", endpoint=call_slow_dj_funcs),
]

app = Starlette(debug=True, routes=routes)
Comment

PREVIOUS NEXT
Code Example
Python :: python collections counter methods 
Python :: add two dataframes together 
Python :: python monitor directory for files count 
Python :: every second value python 
Python :: how to append a tuple to a list 
Python :: winsound python 
Python :: cascaed models in django 
Python :: key pressed pygame 
Python :: pd df merge 
Python :: random seed python 
Python :: python dataframe add rank column 
Python :: python library 
Python :: best way to access nested key in python 
Python :: python any in string 
Python :: python use variable name as string 
Python :: django float validator 
Python :: python dataframe reihe anzeigen 
Python :: protected vs private python 
Python :: with torch.no_grad() if condition 
Python :: drf serializer 
Python :: python add columns to dataframe without changing the original 
Python :: hash function in python 
Python :: python set split limit 
Python :: python booleans 
Python :: pandas read columns as list 
Python :: python int in list 
Python :: python search a string in another string get last result 
Python :: create pdf in python 
Python :: unicode error python 
Python :: class __call__ method python 
ADD CONTENT
Topic
Content
Source link
Name
3+7 =