[Python] Communicating with REST service using Python/Flask, javascript and ajax

Discussão em 'Python' iniciado por Stack, Janeiro 27, 2025.

  1. Stack

    Stack Membro Participativo

    I have a web application fetching data from database behind a REST service creating output in form of a table:

    [​IMG]

    As you see, there are two buttons (Collect/Archive) in each row of the table allowing the user to update the database via another REST service which accepts data via html PUT.

    The click action(s) of the buttons is implemented in javascript. When a button is clicked the following code is executed:

    function updateSourceState(sourceTypeId, sourceId, dataForUpdate) {
    $.ajax({
    url: '/update',
    data: {source_type_id: sourceTypeId, source_id: sourceId, data_for_update: dataForUpdate},
    dataType: 'json',
    type: 'PUT',
    success: function (data) {
    console.log('Data updated successfully');
    },
    error: function(data) {
    console.log('Data update failed. Response: ' + data);
    }
    }).done(function() {
    console.log('DONE: data updated successfully');
    }).fail(function(msg) {
    console.log('FAIL: data update failed: ' + msg);
    }).always(function(msg) {
    console.log('ALWAYS message: ' + dataForUpdate + ', url: ' + url);
    });
    }


    The communication with the REST service is implemented using Python-Flask and javascript. The main program (WebViewer.py) defines routes like this:

    @bp.route('/update')
    def update_source_state():
    app.logger.debug('[DEBUG] entering update_source_state()')

    source_id = request.args.get('source_id')
    source_type = request.args.get('source_type_id')
    dataForUpdate = request.args.get('data_for_update')

    url = '{0}/{1}/source/{2}'.format(ARCHIVE_CONFIG_BASE_URL, source_type, source_id)
    response = requests.put( url=url
    , data=dataForUpdate
    , headers={'Content-Type': 'application/json', 'accept': 'application/json'}
    )

    if response.status_code == 200:
    return jsonify({'status': 'success'}), 200
    elif response.status_code == 405:
    return jsonify({'status': 'method not allowed'}), 405
    elif response.status_code == 500:
    return jsonify({'status': 'server error'}), 500
    else:
    return jsonify({'status': 'failed'}), 600


    I see in the browser debugger that javascript updateSourceState() is called and the variables are filled. However, I never see that the output of app.logger.debug(...) appears in the log file. The server responds with state 405. As it seems, the method update_source_state() is not called (but I am not sure).

    What is the right syntax to perform a PUT request to the REST service in this setup? Any help appreciated.

    Continue reading...

Compartilhe esta Página