Tags

, , , , ,

So one of the options to run a Python function from the web is to use this Python web framework – Flask.

There is no practical examples that I can refer to and I posted many questions** regarding it before i finally got it running.

A summary of how to use Flask / what I did to get it work:

  1. Install it as a package for Python
    pip install Flask
  2. Install Jinja2 as well
    pip install Jinja2
  3. Create directories “templates” and “static” in /var/www where my web page files reside
  4. Put index.html into “templates” as Jinja2 will render the template; and static files into “static”
  5. Do the routing in a new python script, routes.py
    from flask import Flask, jsonify, render_template, request
    from cameraservo3 import turnCamera
    
    app = Flask(__name__)
    
    @app.route('/')
    def homepage():
        return render_template('index.html')
    
    @app.route('/turn_servo', methods=['POST'])
    def turn_servo_ajax():
        direction = request.form['direction']
        cam_result = turnCamera(direction=direction)
        return '<div> {} </div>'.format(cam_result)   
    
    
    if __name__ == '__main__':
        app.debug = True
        app.run(host='0.0.0.0') #so that can access it by any host IP
    
    
  6. In the index.html, the jQuery script is as follow:
    $('#left_button').click(function(){
    				$.post("{{ url_for('turn_servo_ajax') }}", {direction:"left"}).done(function (reply) {
                        $('#camerapos').empty().append(reply);
    					alert("left button clicked");});
    				
    			});
    			$('#right_button').click(function(){
    				$.post("{{ url_for('turn_servo_ajax') }}", {direction:"right"}).done(function (reply) {
                        $('#camerapos').html(reply)});
    				alert("right button clicked");
    			});
    
  7. As for my cameraservo3.py, my algorithm had some obvious problem but I just wanted to try it. Apparently, it failed but surprisingly some modifications to the code make it work! 😀 just worked
    #!/usr/bin/python
    
    
    def turnCamera (**data):
    
        import pigpio
        import time
    
        # import serial
        # def servo_control(command):
        # serialport= serial.Serial ("/dev/ttyACM0", 9600, timeout=0.5)
        # serialport.write(command)
        # return serialport.readlines(1)
    
        servos=4
        key = data['direction']
        if key=="left":
            servostatus = "left"
            print servostatus
            m=1500
        else:
            m=1000
    
    ##    m=1500
    ##    while (m >= 500 and m <= 2500): #this is an obviously failed code
    ##        if (key =="left"):
    ##            print "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
    
    
  8. Start the flask server by python routes.py
  9. Start PiGpio sudo pigpiod
  10. Load the web app at http://192.168.1.109:5000 from another computer on the same network where the front part is Raspberry Pi IP address.

Sorry that my post isn’t very structured as I have been troubleshooting this for the whole day and night. My brain couldn’t take anymore processing. Thank God that it finally work. Also, thanks to those, especially Martin, who helped me on the forum.
Tomorrow I will have to think of some algorithms and write some serious codes. By the way, Flask is actually similar to CherryPy, it’s time consuming and seemingly effort wasting but no harm knowing a new framework. 🙂

But then I foresee there is another problem regarding the camera server because it is by default hosted at http://192.168.1.109 but now i have to access port 5000 instead. Well, I have no idea where to change that port for Flask. Perhaps CherryPy would do it better but I doubt it can start its server at port 80 too.

Anyway, I should have learned and chosen Web2Py from the start. It is a python web framework which can be readily deployed on the web. It has modules, controller and view – the MVC model… but to learn it from the start will take quite some time…

My eyes are really tired now. Good night.

Note: One problem with current code = the servostatus was not returned properly as it is not shown in the #camerapos div.

**Questions on StackOverflow – some didn’t get acceptable answer

How jQuery do POST to a python function?

How do flask know which python file to look at?

can flask use with jquery post?

How to execute python function from jquery post

Accessing Flask server from my web page

 

Advertisements