你有两个问题:你总是在开头写一个Content-Type头,加上额外的换行符。您现在已完成所有标题,无法再添加更多。在
当你正在重定向时,只写这些标题。
Location头仅用于重定向,即一个状态为30x的HTTP响应。您需要添加一个Status:头,以向web服务器发出信号,以非200状态响应。
调整代码以解决这些问题:#!/usr/bin/python
import cgitb
cgitb.enable()
import MySQLdb, cgi, os, sys
db = MySQLdb.connect(host="localhost", user="root", passwd="", db="test")
form = cgi.FieldStorage()
name = form.getvalue('temp')
passwd = form.getvalue('temp2')
with db as query:
query.execute("select * from cred where uname=%s and %s", (name, passwd))
result = query.fetchone()
if result is None:
# no such user, redirect
print 'Status: 302 Found'
print 'Location: http://localhost:8000/'
else:
print 'Content-type: text/html'
print '
Hello {}'.format(name)请注意,我稍微修改了代码以使用一些最佳实践:从不使用字符串插值将用户信息放入SQL查询中。那样的话,SQL注入攻击会让你大吃一惊。使用SQL参数让数据库驱动程序为您转义这些值。
您可以将连接用作上下文管理器来自动提交。
用于生成HTML格式的字符串。