Возврат двух массивов из скрипта python в Django и одновременное использование в Ajax

У меня есть скрипт python, запущенный в файле views.py в Django, который возвращает два очень больших строковых массива, x и y. В настоящее время он может запускаться по нажатию кнопки в моем index.html.

def python_file(request):
    final()
    return HttpResponse("ran")

Код ajax, который я запускаю для выполнения нажатия кнопки.

<script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

    <script>
            function gotoPython(){
                $.ajax({
                  url: "/python_file",
                 context: document.body
                }).done(function() {
                 alert('finished python script');
                });
            }
    </script>

Он также прикреплен к URLS.py. Я знаю, что сейчас не возвращается массив, потому что я не знаю, как запустить скрипт, получить данные одновременно, затем добавить их на страницу без обновления страницы. Поэтому я спрашиваю, как лучше всего сделать то, что я описал. Любая помощь будет оценена по достоинству.

Вы можете добавить параметры к ajax.done(функция), чтобы получить то, что вернул ваш сервер.

 $.ajax({
              url: "/python_file",
             context: document.body
            }).done(function (response, textStatus, jqXHR) {
    // What happens when the call is successful (200 <= status code < 300 
    console.log(response); // Logs what you returned from your django 
    // x + "separator" + y
})
.fail(function (jqXHR, textStatus, errorThrown) {
    // Status code over 400
})
.always(function (jqXHR, textStatus, errorThrown) {
    // Always happens
    ...
});

Вы можете ознакомиться с документацией по ajax здесь : https://api.jquery.com/jquery.ajax/#jQuery-ajax-settings-settings

И ваше представление django должно вернуть некоторое текстовое содержимое :

def view(response):
    // code
    return HttpResponse(status=200, content=x + "separator" + y)

Обычно я так и делаю, не уверен, что это лучшая практика, но я возвращаю его с помощью Json

Я включил два примера, POST и GET.
Я также включил некоторые другие вещи, которые я обычно возвращаю status и msg. Когда я ловлю ошибку или имею недействительный POST, я отправляю обратно status = False и msg = '{error message}, затем я могу показать сообщение об ошибке во фронт-энде с помощью Javascript. Я сохраняю эту стандартизацию в своем проекте, но вы делаете это сами.

def python_file(request):

    xArray, yArray = final()

    import json
    data = {
        'status': True, #  True=All Good. False=Caught Error but didn't crash.
        'x': xArray,
        'y': yArray,
        'msg': 'returning x and y arrays',
    }
    return HttpResponse(
        json.dumps(data),
        content_type="application/json"
    )
function gotoPython(){
    $.ajax({
        method: 'GET',
        url: '/python_file',
        success: function(data){
            console.log(data)

            if (data['status']){

                // do things with arrays
                data['x']
                data['y']

            }else{
                console.log('Server Replied with Error, but did not Crash');
                console.log(data['msg']);
            };
        },
        error: function(event,xhr,settings,errorText){
            // general `xhr.status` Key for common errors
            // 0    = Server didn't Reply (Server Down)
            // 400  = Bad Request         (Syntax Error)
            // 403  = Forbidden           (Login Token Expired or not in Group)
            // 403  = Not Found           (Invalid Url)
            // 500  = Server Error        (Django Crash)
        },
    });
};



function gotoPythonWithData(){
    // if you wanted to POST data to this function you'd just do
    //   Note: Requires csrfmiddlewaretoken in template 
    //      Throw this anywhere (it's hidden): {% csrf_token %}

    submitData = {
        'return_item_count': 25,
        'csrfmiddlewaretoken': $('[name=\'csrfmiddlewaretoken\']').val(),
    };

    $.ajax({
        method: 'POST',
        url: '/python_file',
        data: submitData,
        success: function(data){
            if (data['status']{
                // do stuff
            }else{
                console.log(data['msg']);
            };
        },
        error: function(event,xhr,settings,errorText){
        },
    });
};

Примечание: Некоторые вещи, такие как объекты Django Decimal, не могут быть помещены в Json дамп. В примере с десятичной дробью вы должны превратить их в Float или Int

Вернуться на верх