HTML按钮运行Python函数

3 投票
3 回答
18416 浏览
提问于 2025-04-18 06:32

我有一个脚本,它是在 CGIHTTPServer 下运行的。

这个脚本里面包含:

$ 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>
"""

还有一个函数(可能在另一个脚本里或者在这个脚本里):

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()')

我该怎么把这个函数的结果显示在同一个网页上呢?

如果能提供一些如何做的链接就太好了,或者一些例子。

3 个回答

0

找到了下一个解决方案 - 使用 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'

如果有什么不对的地方,请纠正我……不过 - 这个方法是有效的。

附言:我无法用 POST 方法运行这个 :-(

1

你可以通过把你两个代码片段结合起来来实现这个功能:

#!/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>
"""

如果你想在点击按钮的时候实现这个功能,你需要了解一下AJAX,还有一些比CGI更灵活的东西,比如Flask

4

我觉得你可以用jQuery和Flask做得更好。

Flask 是一个非常简单易用的Python微框架,而jQuery 是一个让Ajax变得非常简单的JavaScript库。

这里有一些代码

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

在浏览器中试试 http://localhost:5000。

撰写回答