我在用户提交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表单调用此脚本后我得到的输出(当用户输入有效,即用户有效时):
此人存在位置:http:localhost / mongo / loggedin.html
我是cgi的新手使用python所以任何帮助对我来说都很棒
答案 0 :(得分:1)
来自cgi
模块
CGI脚本的输出应由两部分组成,用空行分隔。第一部分包含许多标题,告诉客户端正在跟踪哪种数据。
您必须发送标题before
您要发送的任何其他数据。要实现您的目标,只需在HTML发送之前放置所有标头发送逻辑。
但你最好将所有表单检查代码移动到另一个文件,这样它就不会打印任何东西,只是发送重定向和东西。
答案 1 :(得分:0)
# 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"
在将任何其他数据发送到浏览器之前,需要在开始时初始化标题。在问题中,打印语句如print&#34; <html>
&#34;是在位置标题之前写入的,因此需要结果没有实现。