2

I would like to call a python function when an image (button) is clicked which would allow me to control the servo from the web interface.

Here is part of my jQuery code:

$('#left_button').click(function(){
            $.post("cameraservo2.py", {direction:"left"}).done(function (reply) {
                $('#camerapos').empty().append(reply);
                alert("left button clicked");});

        });

And this is my Python code:

#!/usr/bin/python

def index (self, **data):

    import pigpio
    import time

    servos=4
    key = data['direction']

    m=1500
    while (m >= 500 and m <= 2500):
        if (key =="left"):
            m=m+100
        elif (key =="right"):
            m=m-100

    pigpio.start()

    pigpio.set_servo_pulsewidth(servos, m) 
    servostatus= "Servo {} {} micro pulses".format(servos[0], key, m)
    print servostatus
    time.sleep(1)

    pigpio.stop()

    return servostatus

My problem is when the button is clicked, it will alert "left button is clicked" which means it has run through the python file. But instead of showing the "servostatus", i get the whole python code displayed in my #camerapos div.

Please let me know if i need to post more information. Thanks!!

msvalkon
  • 11,887
  • 2
  • 42
  • 38
yvonnezoe
  • 7,129
  • 8
  • 30
  • 47

2 Answers2

2

You need some additional tools in order to call server side python code from client side query. Flask, a lightweight python web framework is often the tool of choice for problems like this.

Flask documentation: http://flask.pocoo.org

Flask with JQuery: http://flask.pocoo.org/docs/patterns/jquery/

Flask with Jquery POST: how can I use data posted from ajax in flask?

To use POST with Flask/Jquery, you must annotate the receiving method in python. Your code would look something like this.

@app.route('/servo_pos', method=["POST"])
def servo_pos():
    do_your_work_here
    return jsonify({"servo_pos", ret_val})

You'll also need to tweak your jquery a bit.

$('#left_button').click(function(){
            $.post("/servo_post", {direction:"left"}).done(function (reply) {
                $('#camerapos').empty().append(reply);
                alert("left button clicked");});

        });

I'm not sure about this step, but you may also need to replace .post with .ajax. Since you don't want the page to reload before you display the new contents, this isn't a traditional post request, but rather an ajax one.

Alternatively, is there a reason that you MUST be using a post request, and a GET_JSON won't work, like in the jquery ajax pattern above?

Key notes:

  1. add `methods=['POST']
  2. data request argument is found in data.request.data
  3. return data in a "jsonified" dictionary requires from Flask import jsonfiy
Community
  • 1
  • 1
Joan Smith
  • 931
  • 6
  • 15
  • thanks for your reply. you mean i can just add this `from flask import Flask, jsonify, render_template, request app = Flask(__name__) @app.route('/')`? – yvonnezoe Feb 28 '14 at 06:42
  • but i am using a `post` instead of `get` mentioned on the flask page. – yvonnezoe Feb 28 '14 at 06:43
  • That's fine, you can use POST with Flask pretty easily. Just annotate your Flask function accordingly. Updated my answer above. – Joan Smith Feb 28 '14 at 14:40
  • Thank you! :) I will try it tomorrow and update you again. the reason why i want to use "post" is because I have used it with cherrypy web server (with everything inside just 1 python script) before and it works well. So i am trying to adopt the codes that i have done. But the problem now is that i'm not using cherrypy (and not sure if i can use it concurrently with other server) and my html & python scripts are separated. – yvonnezoe Feb 28 '14 at 18:34
0

In addition to running a full server-side python web framework, a minimal approach could be to use cgi e.g. uwsgi.

See the official python docs for more information on minimal working setups.

Interactivity

If your webapp requires more interactivity with the server, you might want to consider using websockets instead of AJAX as a communication framework. Caveat: WebSockets aren't supported by older browsers.

An example of a well developed framework that has websocket support is tornado.

jmetz
  • 12,144
  • 3
  • 30
  • 41
  • thanks! i tried cgi before but i don't want to use a form format. I'm using an image button when clicked, would execute a function in python – yvonnezoe Mar 03 '14 at 01:59
  • @yvonnezoe- I added a small additional about cases where you might need more interactivity; my recommendation there would be to use something like tornado with websockets – jmetz Mar 03 '14 at 10:32