setevoy
setevoy

Reputation: 4662

HTML button to run Python function

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.

Upvotes: 3

Views: 18460

Answers (3)

setevoy
setevoy

Reputation: 4662

Found next solution - using GET:

$ cat cgi-bin/mysql.py
#!/usr/bin/python

import cgi, MySQLdb

data = None
form = cgi.FieldStorage()

def myver(host, user, pwd, cmd):
    db = MySQLdb.connect(host, user, pwd)
    cursor = db.cursor()
    cursor.execute(cmd)
    global data
    data = cursor.fetchone()
    db.close()

form = cgi.FieldStorage()

print "Content-type:text/html\r\n\r\n"
print "<title>Test to get MySQL version</title>"
print "<h2>MySQL version</h2>"
print '''Get version: <form action="/cgi-bin/mysql.py" method="get">
<input type="submit" name="getvers" value="Get version" />
<input type="submit" name="exit" value="Exit" />
</form>
'''

if "getvers" in form:
    myver('localhost', 'username', 'megapass', 'SELECT VERSION()')
    print 'Current MySQL version: ' + ''.join(data)
elif "exit" in form:
    print 'Exit'

Please, correct me if anything wrong... But - it works.

P.S. Can't run it with POST method :-(

Upvotes: 0

andmart
andmart

Reputation: 552

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.

Upvotes: 4

robbrit
robbrit

Reputation: 17960

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.

Upvotes: 1

Related Questions