2

我正在使用 Python 编程 CGI,发现 CGI 以名为 FieldStorage 的类的形式将信息传递给 Python。我遇到的 FieldStorage 类的主要属性是“getvalue”,用于从表单字段中获取数据。是否可以获取字段的 id 值?

编辑

我想知道我是否可以获得有关表单发送数据的一些独特信息。这是因为,我有一个表单和 2 个脚本。在表单中,我放置了项目详细信息,然后脚本 1 获取该数据并将其保存在数据库中。我有另一个脚本2,它查询已保存的项目数据,创建表单并使用数据填充表单以启用编辑项目,并且在用户编辑后,数据将更新回数据库。

更新回数据库是问题所在。我想使用脚本 1 进行更新,但在这种情况下,我不会执行 INSERT INTO ... 我将执行 UPDATE Table1 ... 现在,我如何知道哪个请求用于编辑或更新。我这样做是因为我在表单有 70 个字段的情况下创建另一个脚本只会复制 script1 并添加更新逻辑。这就是我想用脚本做的

脚本1.py

#!/usr/bin/env python

import cgi
import cgitb; cgitb.enable()     # for troubleshooting
import MySQLdb

form = cgi.FieldStorage()

#there are 70 fields
id = form.getfirst("id");
error = form.getfirst("error");
comment = form.getfirst("comment");
product_name = form.getfirst("product_name");
verified_product_name = form.getfirst("verified_product_name");
url = form.getfirst("url");
verified_url= form.getfirst("verified_url");
.
.
.
source = form.getfirst("source");

print 'Content-type: text/html\r\n\r'
print '<html>'
print 'Update Successfull ! !'
print '</html>'


db = MySQLdb.connect(host="localhost", user="root", passwd="", db="products")


cursor = db.cursor()
sql=""

### Check the request---How do i do this?

if update: ##if the request is for updating

sql = """UPDATE item SET (id=id, error=error, comment=comment, product_name=product_name, verified_product_name=verified_product_name, url=url, verified_url=verified_url, image_url=image_url,..., source=source)"""

else: ##if the request is for inserting

sql = """INSERT INTO item (id, error, comment, product_name, verified_product_name, url, verified_url, image_url, verified_image_url, brand, verified_brand, type, verified_type, price, min_price, max_price, verified_price,..., source) VALUES ('%s', '%s', "%s", '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s',..., '%s')""" %(id, error, comment, product_name, verified_product_name, url, verified_url, image_url, verified_image_url, brand,..., source)

try:
  cursor.execute(sql,(id, error, comment, product_name, verified_product_name, url, verified_url, image_url, verified_image_url, brand, verified_brand, type, verified_type, price, min_price, max_price, verified_price, measure_unit, ..., source))

   db.commit()
except Exception as err:


   db.rollback()

   db.autocommit(True)
cursor.execute(sql)
cursor.fetchall()
db.close()

希望你能解决我的问题。我可以在不创建另一个脚本单独进行更新的情况下执行此操作吗?

4

0 回答 0