python重定向作用_Python重定向不起作用

I'm trying to redirect the user to my homepage. Its suppose to be as simple as

print "Location:http://localhost:8000/index.html"

print ""

This isn't working for some reason. I'm running CGIHTTPServer on Kali Linux. I'm using Python 2.7.3

When I try to run the script it simply prints out

Location:http://localhost:8000/index.html

I have also tried using 127.0.0.1 instead of localhost. It doesn't work either.Here is the CGI script that I'm trying to run

#!/usr/bin/python

import MySQLdb,cgi, os, sys

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

flag=False

query = db.cursor()

sys.stdout.write("Content-type: text/html\r\n\r\n")

sys.stdout.write("")

sys.stdout.write("

")

form = cgi.FieldStorage()

name = form.getvalue('temp')

passwd = form.getvalue('temp2')

if(query.execute("select * from cred where uname='"+name+"' and pass='"+passwd+"'")):

db.commit()

sys.stdout.write("Hello "+name)

else:

db.commit()

flag=True

sys.stdout.write("")

if(flag == True):

print "Location:http://localhost:8000/"

print ""

解决方案

You have 2 problems here:

You always write the Content-Type header plus extra newlines at the start. You've now completed all headers and you can no longer add more.

Write these headers only when you are not redirecting.

A Location header is only used for redirects, a status 30x HTTP response. You'll need to add a Status: header to signal to the web server to respond with a status other than 200.

Adjusting your code to address these issues:

#!/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/'

print

else:

print 'Content-type: text/html'

print

print '

Hello {}'.format(name)

Note that I altered the code somewhat to use some best practices:

NEVER use string interpolation to put user-information into a SQL query. You'll get hammered by a SQL injection attack that way. Use SQL parameters to have the database driver escape the values for you.

You can use the connection as a context manager to auto-commit.

I used string formatting to produce the HTML output.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值