2012-03-18 80 views
0

我正在嘗試創建一種web服務器withy python和cherrypy。Python網頁登錄錯誤

我希望把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 

我想知道如果任何人都可以請幫助錯誤消息?

在此先感謝

+0

爲什麼不使用[jinja2](http://jinja.pocoo.org/)等模板引擎? – ThiefMaster 2012-03-18 10:20:43

回答

0

嗯,從錯誤,顯然Python不知道get_file()功能是什麼。你確定在welcome()函數中調用這個函數的那個​​時間點,get_file()已經被定義了嗎?

+0

OF COURSE!這現在完全令人尷尬......我以爲出了問題。但相反,該函數只是沒有在方法之前聲明...雖然非常感謝。 – Synia 2012-03-18 10:18:39

+0

@AbhranilDas:第二部分是無效的。它只需要在被調用時進行定義。 – ThiefMaster 2012-03-18 10:23:22

+0

@ThiefMaster:編輯。但你確定嗎?因爲我已經編寫了調用其他函數的函數的程序,並且函數1在函數2之前沒有被聲明,所以使用函數1的函數2失敗。這些函數從所有函數定義結束後啓動的程序主體調用。那麼問題是什麼? – 2012-03-18 10:27:48

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

Python的文件管理念起來不過,考慮使用適當的模板引擎。 Jinja2是非常好的,它允許你在模板中使用條件等 - 你肯定希望在某些時候。除此之外,如果你問它,它會爲你做一些很好的事情,例如變量自動轉義。