【问题标题】:when redirecting getting an error malformed header重定向时收到格式错误的标头
【发布时间】:2013-06-12 16:19:08
【问题描述】:

前几天我在堆栈溢出中看到如何使用函数重定向.. 但它在这里不起作用

#!/Python27/python
import cgi
import cgitb ; cgitb.enable()
import MySQLdb
from datetime import datetime
f= cgi.FieldStorage()
l=f["roll"].value
def redirect(url):
    print "Content-Type: text/plain"
    print "Refresh: 0; url='%s'" % url
    print
    print "Redirecting..."

Con = MySQLdb.Connect(host="127.0.0.1", port=3306, user="root", passwd="jesus",        db="student")
cursor = Con.cursor()
sql="SELECT YEAR FROM STDDET WHERE id='%s'"%(l)
cursor.execute(sql)
data=cursor.fetchone()
cyear=datetime.now().year
cmonth=datetime.now().month
data=data[0]
data=int(data)
year=cyear-data
print year
if(year==3):
    redirect("intro.html")
elif(year==4):
     redirect("yea4.html")

即使满足 if 条件,它也不会被重定向...我收到错误格式错误的标头...请帮助!!

【问题讨论】:

  • 请修正您的代码缩进。

标签: python mysql apache


【解决方案1】:

据我所知,您的脚本会产生以下响应:

Content-Type: text/plain Refresh: 0; url='x.y.com'

Redirecting...

这不是有效的 http 响应,因为缺少 status line。

如果你生成一个“有效”页面,你应该回复一个状态

HTTP/1.1 302 Found

如果您要重定向,最好使用 3xx 代码之一进行回复。举个例子:

HTTP/1.1 302 Found
Location: http://www.google.fr/

HTTP/1.1 ... 行必须是标题的第一行。所以它应该由你程序的第一个print 生成。示例见Python CGI returning an http status code, such as 403?。

【讨论】:

  • 我可以使用 http 标头响应来根据条件进行重定向吗...我编辑了代码.....你能告诉我 http 标头是否适用于该代码吗?如果不是请帮我解答
猜你喜欢
  • 2017-06-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多