How to run a Python command with JS?

Asked

Viewed 5,956 times

4

I have a button and when clicking it I want js to execute a . py command on the server side. How do I do it?

2 answers

1


You can do this through a command AJAX through the JavaScript, however, your call AJAX will be a request on HTTP (WEB) for the script Python, therefore, your command needs to listen at the door for such requests and reply back.

Below is an example using jQuery how this call can be made:

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    <title>Python - jQuery Example</title>
    <script src="http://code.jquery.com/jquery-2.0.3.js"></script>
    <script>
        $(function()
        {
            $.ajax({
                url: "http://localhost/cgi-bin/you-command.py",
                type: "post",
                datatype: "html",
                data: { var1: "foo", var2: "foo" },
                success: function(response){
                        $("#div").html(response);
                        console.log("OK"); 
                }
            });
        });

    </script>
</head>
<body>
    <div id="div">EMPTY</div>
</body>
</html>

If your script Python do not accept requests HTTP you will need to add a layer that does this and execute your command as desired.

#EDIT

Just use the CGI library of Python

import cgi, cgitb

data = cgi.FieldStorage()

output = data["var1"] // É assim que você captura os parâmetros passados.

print(output)
  • So basically Python has to listen to a request?

  • How do I get Python to receive the parameters?

  • @renanprado96 is basically this yes, I edited the answer showing a simple way to capture the parameters passed by JS in the Python. Recalling again that it is necessary that the script accepted question Requisições HTTP, give a search on the Internet that you discover how, I will not explain in detail here why it escapes the scope of the question. But any questions open a new topic here on SO and we will help you. ;)

1

For this you need a layer between the back end and the front end, something like the Django templates, in which case Voce would have a button (which could be "controlled" by js or not) that would send an HTTP object to a function in the back end. I think with an example it gets easier. Let’s just suppose a Submit button to "trigger" something in the backend.

html template.

{% block content %}
    <div class="container">
        <form method="POST" class="viewform">
            {% csrf_token %}

            <--! Implemente o form aqui -->

            <button type="submit" name="_submit" class="btn btn-primary btn-lg">Cadastrar</button>
        </form>
    </div>
{% endblock %}

py views.

def teste1(request):
    if request.method == 'POST':
       # Submit pressionado
       print ('Ok, botão pressionado)
    else:
        pass

    return render(request, 'template.html' )

Observing:

It is important to keep in mind that the idea of an element in the front-end directly execute a command in the back-end is a lousy idea, so the need of the intermediate layer, see that in this example the button does not perform anything in the back end, it just sends a request to the back and that does what is necessary, ie the front nor "dreams" if what will be run in the back will be in python, c, or bash. This ensures that if there is a need to radically change the language/platform/environment on one side, there will be no co-lateral effects on the other.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.