3

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.

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but this one is too complicated for me :-)
If you want to do anything more complex than the one-page app you posted in your question, Flask and jQuery will make your life a million times easier than trying to slog through the CGI way.
you're welcome, but listen to @robbrit advice. Jquery and Flask( or anyother Python web framework ) it's the way to go.
1

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.

Comments

0

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 :-(

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.