【问题标题】:Returning Output of Python CGI MySQL Script返回 Python CGI MySQL 脚本的输出
【发布时间】:2023-03-19 08:11:02
【问题描述】:

我对 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 Requests 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 语句返回到请求进程。但是,我所有的最大努力都没有帮助。谁能指出我正确的方向?非常感谢您的帮助!

马克 :-)

【问题讨论】:

    标签: python mysql sql cgi


    【解决方案1】:

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

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

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

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

    python -m CGIHTTPServer
    

    要调用的 url 如下所示:

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

    【讨论】:

    • 添加print "Content-type: text/plain\r\n\r\n" 成功了!似乎不需要 CGIHTTPServer 和端口 8000。但是,我会记住他们的未来。非常感谢您的快速回复!
    猜你喜欢
    • 1970-01-01
    • 2021-12-13
    • 1970-01-01
    • 2023-03-26
    • 1970-01-01
    • 2013-03-21
    • 1970-01-01
    • 2021-05-01
    • 2014-12-20
    相关资源
    最近更新 更多