Python网页登录错误

时间:2012-03-18 09:55:04

标签: python html login cherrypy

我正在尝试创建一种带有python和cherrypy的webserver。

我希望将htmls放入单独的文件中并将它们嵌入到我的python脚本中。我以前用的代码就是。

    @cherrypy.expose
def welcome(self, loginAttempt = None):
    """ Prompt the user with a login form. The form will be submitted to /signin
        as a POST request, with arguments "username", "password" and "signin"
        Dispaly a login error above the form if there has been one attempted login already.
    """
    #Debugging Process Check
    print "welcome method called with loggedIn = %s" % (loginAttempt)

    if loginAttempt == '1':
       """ If the user has attempted to login once, return the original login page
       with a error message"""
       page = get_file("loginPageE.html") 
       return page

    else:    
        page = """
               <form action='/signin' method='post'>
               Username:  <input type='text' name='username' /> <br />
               Password:  <input type='password' name='password' />
                 <input type='submit' name='signin' value='Sign In'/>
               </form>
        """          
        return page

其中loginPageE.html是

<html>
<head>
<title>Failed Login Page</title>
</head>

<body>

<!-- header-wrap -->
<div id="header-wrap">
    <header>

        <hgroup>
            <h1><a href="loginPageE.html">Acebook</a></h1>
            <h3>Not Just Another Social Networking Site</h3>
        </hgroup>


        <ul>
            <form action='/signin' method='post'>
                Username:  <input type='text' name='username' />
                Password:  <input type='password' name='password' />
                           <input type='submit' name='signin' value='Sign In'/>
            </form>
        </ul>


    </header>
</div>

</body>
</html>

但是我继续收到错误消息

Traceback (most recent call last):
  File "/usr/lib/pymodules/python2.7/cherrypy/_cprequest.py", line 606, in respond
    cherrypy.response.body = self.handler()
  File "/usr/lib/pymodules/python2.7/cherrypy/_cpdispatch.py", line 25, in __call__
    return self.callable(*self.args, **self.kwargs)
  File "proj1base.py", line 74, in welcome
    page = get_file("loginPageE.html")
NameError: global name 'get_file' is not defined

我想知道是否有人可以请求帮助?

提前致谢

3 个答案:

答案 0 :(得分:0)

好吧,从错误来看,显然python不知道get_file()函数是什么。您确定在welcome()函数中调用此函数的那个​​时间点,get_file()已经定义了吗?

答案 1 :(得分:0)

get_file不是标准的Python函数之一,因此它必须是您以前拥有的自定义函数。您可以创建一个简单的函数来读取文件并将其内容作为字符串返回,如下所示:

def get_file(path):
    f = open(path, 'r')
    output = f.read()
    f.close()
    return output

您可以在http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files

上阅读Python文件管理

答案 2 :(得分:0)

def get_file(path):
    with open(path, 'r') as f:
        return f.read()

但是,请考虑使用适当的模板引擎。 Jinja2非常好,它允许你在模板中使用条件等 - 这在某些方面你肯定想要的。除此之外,如果您要求它,它会为您提供诸如变量自动转换之类的好东西。