HTML button to run Python function

17,581

Solution 1

I think you could do it better with jquery and Flask.

Flask is a Python microframework very easy to use and jQuery is a javascript lib that makes Ajax a breeze.

Some code

from flask import Flask, request

app = Flask(__name__)

@app.route('/')
def main():
    return """<html>
                   <head>
                      <script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
                      <script>
                           $(document).ready(function(){

                                $('#btnSend').click(function(){

                                    $.ajax({
                                      type: 'POST',
                                      url: '/process',
                                      success: function(data){
                                        alert(data);
                                      }
                                    });
                                });

                           });
                      </script>
                   </head>
                   <body>
                    <input type="button" id="btnSend" value="process">
                    </body>
                   </html>"""


@app.route('/process', methods=['POST'])
def view_do_something():

    if request.method == 'POST':
        #your database process here
        return "OK"
    else:
        return "NO OK"

if __name__ == '__main__':
    app.run()

Try http:// localhost : 5000 in a browser.

Solution 2

You can do this by combining your two snippets:

#!/usr/bin/env python


def myver(host, user, pwd, cmd):
    db = MySQLdb.connect(host, user, pwd)
    cursor = db.cursor()
    cursor.execute(cmd)
    data = cursor.fetchone()
    print "Database version : %s " % data
    db.close()

print "Content-Type: text/html"
print
print """
<html>
<body>
<h2>Test</h2>
"""

myver('localhost', 'username', 'megapass', 'SELECT VERSION()')

print """
</body>
</html>
"""

If you would like to do this on the click of a button, you'll need to investigate AJAX and something a bit more flexible than CGI, such as Flask.

Share:
17,581
setevoy
Author by

setevoy

Updated on July 18, 2022

Comments

  • setevoy
    setevoy almost 2 years

    I have script, which is running under CGIHTTPServer.

    Script contains:

    $ cat cgi-bin/mysql.py
    #!/usr/bin/env python
    
    print "Content-Type: text/html"
    print
    print """
    <html>
    <body>
    <h2>Test</h2>
    <button type="button">Get version</button>
    </body>
    </html>
    """
    

    And function (in other script or this):

    def myver(host, user, pwd, cmd):
        db = MySQLdb.connect(host, user, pwd)
        cursor = db.cursor()
        cursor.execute(cmd)
        data = cursor.fetchone()
        print "Database version : %s " % data
        db.close()
    
    myver('localhost', 'username', 'megapass', 'SELECT VERSION()')
    

    How can I get result of this function on to same web-page?

    Links to HowTo's will be perfect. Or some examples.