python - 返回 Python CGI MySQL 脚本的输出

标签 python mysql sql cgi

我是 Python 和 MySQL 的新手,这是我的第一个 Stack 问题。所以,如果我遗漏了一些明显的东西,请提前道歉。但是,我确实在询问之前确实尝试过对此进行研究。

我正在尝试学习 Python、MySQL 和 CGI​​ 脚本的基础知识。为此,我一直在阅读教程 http://www.tutorialspoint.com/python/python_cgi_programming.htmhttp://www.tutorialspoint.com/python/python_database_access.htm ,等等。

我正在尝试让 CURL GET 或 Python 请求 GET 在测试服务器上调用 Python CGI 脚本。然后,该 Python CGI 脚本将对本地 MySQL 数据库执行读取操作,并将结果返回到 CURL 或 Python 请求。

我创建的 Python CGI 脚本将 MySQL 读取数据完美地输出到远程测试服务器上的终端。但是,它不会将该输出返回到 CURL 或触发 CGI 脚本的 Python 请求。

这是我拼凑的 Python CGI 脚本:

#!/usr/bin/python

import MySQLdb

# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )

# prepare a cursor object using cursor() method
cursor = db.cursor()

# Prepare SQL query to INSERT a record into the database.
sql = "SELECT * FROM EMPLOYEE \
       WHERE INCOME > '%d'" % (1000)
try:
   # Execute the SQL command
   cursor.execute(sql)
   # Fetch all the rows in a list of lists.
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
      # Now print fetched result
      print "fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income )
except:
   print "Error: unable to fetch data"

# disconnect from server
db.close()

我的猜测 是我需要以某种方式将数据从 SQL 查询传回 Python,或者通过某种 Return 或 Output 语句传回请求进程。但是,我为此所做的所有最大努力都无济于事。谁能指出我正确的方向?非常感谢您的帮助!

马克 :-)

最佳答案

首先,根据您链接的 CGI 教程,您需要输出您正在使用的内容类型:

print "Content-type: text/plain\r\n\r\n",

如果您至少没有换行符,HTTP 客户端会认为您的内容应该是 header 的一部分并感到困惑,他们可能会认为您要求的文档是空的。

接下来,您需要一个 CGI 服务器。 Python comes with one.将您的脚本放在名为 cgi-bin 的子目录中并运行此命令(从父目录):

python -m CGIHTTPServer

要调用的 url 看起来像这样:

curl http://localhost:8000/cgi-bin/cgitest.py

关于python - 返回 Python CGI MySQL 脚本的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22443209/

相关文章:

php - MySQL 中的 stripos 等价物

sql - 从记录类型的单列中拆分/提取值,将用户定义的函数应用于多行 CTE

mysql - 如何从 2 个时间表中获取所选时间?

python - 为什么这个计时器只打印最终结果而不是每秒更新一次?

python - 在 Github Actions 上安装后找不到我的 python 模块

python - 有没有办法同步调用方法 'toHtml' ,它是 QWebEnginePage 的对象?

MySQL REGEXP 未产生预期结果(多字节不安全?)。有解决办法吗?

php - 我想从三个表中获取数据,每个表都与 id 链接

mysql - 可以在 MySQL 中不使用定界符创建过程吗?

python - OpenMDAO 的 SimpleGADriver 中自动计算的具有整数值的位