如何使用 python 执行 HTTP 重定向

How to perform a HTTP redirection using python

我在用户提交 HTML 表单后调用我的 python 脚本。我的 python 脚本出现在 usr/lib/cgi-bin 中。我想根据用户提供的输入重定向到另一个页面,基本上我正在创建一个登录脚本,如果用户输入有效,那么用户将被重定向到 loggedin.html 页面,否则到 error.html 页

signin.py(我正在尝试执行这段代码)

#! /usr/bin/python2.7

import cgi, cgitb 

# import pymongo module for connecting to mongodb database

import pymongo
from pymongo import MongoClient

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# creating a mongo client to the running mongod instance
client = MongoClient()

# selecting the database mydb 
db_mydb = client.mydb

# selecting the collection user
collection_user = db_mydb.user

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Signin</title>"
print "</head>"

# Get data from fields
email = form.getvalue('login-username')
password  = form.getvalue('login-password')

#checking whether user inputs are correct or not
 existence_query=collection_user.find_one({"_id":email,"password":password})

print "<body>"

if(existence_query):
    print "person exists"
    print "Status: 301 Moved\r\n\r\n"
    print "Location : http://localhost/mongo/loggedin.html\r\n\r\n"

else:
    print "person does't exists"
    #redirecting to error.html page
print "</body>"
print "</html>"

从我的 html 表单调用此脚本后得到的输出(当用户输入有效时,即用户有效):

存在 Location:http:localhost/mongo/loggedin.html

我是使用 python 的 cgi 新手,所以任何帮助对我来说都是很好的

来自 cgi 模块上的 Python 文档

The output of a CGI script should consist of two sections, separated by a blank line. The first section contains a number of headers, telling the client what kind of data is following.

您必须发送 headers before 您想要发送的任何其他数据。要实现您的目标,只需将所有 header 发送逻辑放在 HTML-sending 之前。

但是 您最好将所有 form-checking 代码移动到另一个文件,这样它就不会打印任何内容,只会发送重定向和内容。

 # Import modules for CGI handling 

    import cgi, cgitb 

    # import pymongo module for connecting to mongodb database
    import pymongo
    from pymongo import MongoClient

    # Create instance of FieldStorage 
    form = cgi.FieldStorage() 

    # creating a mongo client to the running mongod instance
    # The code will connect on the default host and port i.e 'localhost' and '27017'
    client = MongoClient()

    # selecting the database mydb 
    db_mydb = client.mydb

    # selecting the collection user
    collection_user = db_mydb.user

    #print "Content-type:text/html\r\n\r\n"

    # Get data from fields
    email = form.getvalue('login-username')
    password  =     form.getvalue('login-password')

    #checking whether user inputs are correct or not
    existence_query = collection_user.find_one({"_id":email,"password":password})


    if(existence_query):
        print "Location:http://localhost/mongo/index.html\r\n"
        print "Content-type:text/html\r\n\r\n"
    else:
        print "Location:http://localhost/mongo/index.html\r\n"
        print "Content-type:text/html\r\n\r\n"

Headers 需要在任何其他数据发送到 browser.In 之前初始化,问题打印语句如打印“<html>”是在位置 [=15 之前写入的=] 所以没有达到预期的结果。