How to Django handle multiple requests send at the same time

In a web application, multiple requests can be sent to the server at the same time. Handling these requests can become a challenging task, especially if the server has to perform complex operations, like making API requests, performing database queries, etc. In this post, we will discuss how Django can handle multiple requests sent at the same time.

    group_name_status = {'name': '', 'status':''}


def tokem_update(access_token):
    try:
        intervalInfo = UserIntervalInfo.objects.first()
        headers = {'Content-Type': 'application/json', 'Accept': 'application/json'}
        data = {'client_id': intervalInfo.client_id,
                'client_secret': intervalInfo.client_secret,
                'grant_type': 'password',
                'username': intervalInfo.user_id,
                'password': intervalInfo.user_password
                }
        response_token = requests.post(user_token, headers=headers, data=json.dumps(data))
        data = response_token.text
        tokens = json.loads(data)
        access_token.access_token = tokens['access_token']
        access_token.token_type = tokens['token_type']
        access_token.expires_in = tokens['expires_in']
        access_token.refresh_token = tokens['refresh_token']
        access_token.save()
        return access_token
    except:
        return False


def nema_status(request):
    if request.method == 'POST':
        try:
            group_id = request.POST.get('group_id')
            access_token = API_ACCESS_TOKEN.objects.first()
            current_datetime = timezone.now()
            difference = int((current_datetime - access_token.updated_at).total_seconds() / 3600)
            if difference > 7:
                access_token = tokem_update(access_token)
                if access_token == False:
                    messages.error(request, "Failed update the access token" )
                else:
                    messages.success(request, 'Successfully updated the access token')
            headers = {
                "Accept": "application/json",
                "Content-Type": "application/json",
                "Authorization": f"Bearer {access_token.access_token}"
            }
            if group_id != '0':
                group_name = Group.objects.get(id=group_id)
                if group_name.object_id:
                    par_group_nemas_status = f"https://rpt.tvilight.io/api/status?type=group&q={group_name.object_id}"
                    response_nema_status = requests.get(par_group_nemas_status, headers=headers)
                    if response_nema_status.status_code == 200:
                        datas = response_nema_status.json()
                        nemas = Nema.objects.filter(group=group_name)
                        for data in datas:
                            for nema in nemas:
                                if nema.object_id == data['object_id']:
                                    Nema_status.objects.create(
                                        status = data['status'],
                                        api_created_at= data['created_at'],
                                        message = data['message'],
                                        object_id=data['object_id'],
                                        object_type= data['object_type'],
                                        session_id= data['session_id'],
                                    )
                                    break
                        messages.success(request, f"{group_name.name} name status added successfully")
                    else:
                        messages.error(request, f"Something went wrong. Try again.")
                else:
                    messages.info(request, 'Group object not found.')
            elif group_id == '0':
                all_group = Group.objects.filter(is_delete=False)
                for group_name in all_group: 
                   
                    if group_name.object_id:
                        par_group_nemas_status = f"https://rpt.tvilight.io/api/status?type=group&q={group_name.object_id}"
                        response_nema_status = requests.get(par_group_nemas_status, headers=headers)
                        global group_name_status
                        group_name_status['name'] = group_name.name
                        group_name_status['status'] = response_nema_status.status_code
                        if response_nema_status.status_code == 200:
                            datas = response_nema_status.json()
                            nemas = Nema.objects.filter(group=group_name)
                            for data in datas:
                                for nema in nemas:
                                    if nema.object_id == data['object_id']:
                                        Nema_status.objects.create(
                                            status = data['status'],
                                            api_created_at= data['created_at'],
                                            message = data['message'],
                                            object_id=data['object_id'],
                                            object_type= data['object_type'],
                                            session_id= data['session_id'],
                                        )
                                        break
                messages.success(request, f"All group name status added successfully")
        except:
            messages.error(request, f"Something went wrong. Try again.")
    else:
        messages.error(request, "Something went wrong. Try again.")
    return redirect('nema:view_nema')


def get_group_name(request):
    global group_name_status
    return JsonResponse(group_name_status, status=200)

Request ajax and django url same time:

document.querySelectorAll('.nema-status-group').forEach(item => item.addEventListener('submit', e => {
            for(let i = 0; i < 5000; i++){
                setTimeout(get_table_name, i * 1000)
            }
        })
        );
        function get_table_name(){
            let label = document.querySelector('#lable');
            $.ajax({
                url: "{% url 'nema:group_name_status' %}",
    
                    type: "get",
                    dataType: "json",
                    success : (data) => {
                        if(label.innerHTML != `<b>Group:</b> ${data.name} <b>Status:</b> ${data.status}`){
                            if (data.name != ''){
                                
                                label.classList.add('badge');
                                label.innerHTML = `<b>Group:</b> ${data.name} <b>Status:</b> ${data.status}`;
                                if (data.status == 200){
                                    label.classList.remove('badge-gradient-danger')
                                    label.classList.add('badge-gradient-success');
                                }
                                else{
                                    label.classList.remove('badge-gradient-success');
                                    label.classList.add('badge-gradient-danger');
                                }
                            }
                        }
                    }
            })
        }