使用Python在CGI中重定向页面

时间:2015-07-03 07:06:30

标签: python cgi

我正在尝试在python中编写一个简单的登录页面的cgi脚本。 我正在尝试将此页面重定向到我的主页,提交用户名和密码。

任何人都可以在不操纵HTTP标头的情况下帮助我这样做。

这是我正在使用的代码::

    #!"D:\Python34\python.exe"

    import cgi
    username=""
    password=""

    def htmlTop():
        print("""Content-type:text/html\n\n
                 <!DOCTYPE html>
                 <html lang="en">
                    <head>
                        <meta charset="utf-8"/>
                        <title>Login Form</title>
                        <link rel="stylesheet" href="../css/bootstrap.min.css">
                        <link rel="stylesheet" href="../css/bootstrap-theme.min.css">
                        <link rel="stylesheet" href="../css/userStyles.css">
                    </head>
                    </body>""")
    def htmlBody():
        print("""
                <div class = "container">
                    <div class="wrapper">
                        <form action="" method="get" name="Login_Form" class="form-signin">       
                            <h3 class="form-signin-heading">Welcome Back! Please Sign In</h3>
                              <hr class="colorgraph"><br>

                              <input type="text" class="form-control" name="Username" placeholder="Username" required="" autofocus="" />
                              <input type="password" class="form-control" name="Password" placeholder="Password" required=""/>            

                              <button class="btn btn-lg btn-primary btn-block"  name="Submit" value="Login" type="Submit">Login</button>            
                        </form>         
                    </div>
                </div>
                """)
    def checkForm():
        formData=cgi.FieldStorage()
        if formData.getvalue("Submit"):
            username=formData.getvalue("Username")
            password=formData.getvalue("Password")
            print("Your Username is {0} and your password is {1}".format(username,password))
        else:
            htmlBody()
    def htmlTail():
        print("""   
                    <script src="../js/bootstrap.min.js"></script>
                    </body>
                 </html>""")

    #main program
    if __name__=="__main__":
        try:
                htmlTop()
                checkForm()
                htmlTail()
        except:
            print ("This is the exception")
            cgi.print_exception()

1 个答案:

答案 0 :(得分:0)

正如他们在this post中所说的那样:

  

这一集突出了CGIHTTPServer模块的一个小缺点    - 它不允许我们发布302重定向。在这种情况下,我们使用替代方法进行重定向。概述了正确的方法   更详细的Python Cookbook Recipe

所以,或者你使用

<meta http-equiv="refresh" content="0;url=http://www.example.com" /> 
在您的标题中

或您编写重定向功能,如上例所示。