2011-06-30 48 views
8

我在cherrypy中遇到了一個基本概念問題,但至今我一直無法找到關於如何做到這一點的教程或示例(我是Cherrypy新手,請溫和) 。Cherrypy中的靜態html文件

問題。 (這是一個測試,因此在代碼中缺少可靠的身份驗證和會話)

用戶轉到index.html頁面,該頁面是登錄頁面類型中的詳細信息,如果詳細信息不匹配在文件上返回並顯示錯誤消息。這工作! 如果詳細信息是正確的,則向用戶顯示不同的html文件(network.html)這是我無法工作的一點。

當前的文件系統看起來是這樣的: -

AppFolder 
    - main.py (main CherryPy file) 
    - media (folder) 
     - css (folder) 
     - js (folder) 
     - index.html 
     - network.html 

文件的佈局似乎是正確的,因爲我可以訪問的index.html 的代碼如下所示:(我有一個地方在那裏評論我試圖返回新頁)

import cherrypy 
import webbrowser 
import os 
import simplejson 
import sys 

from backendSystem.database.authentication import SiteAuth 

MEDIA_DIR = os.path.join(os.path.abspath("."), u"media") 

class LoginPage(object): 
@cherrypy.expose 
def index(self): 
    return open(os.path.join(MEDIA_DIR, u'index.html')) 

@cherrypy.expose 
def request(self, username, password): 
    print "Debug" 
    auth = SiteAuth() 
    print password 
    if not auth.isAuthorizedUser(username,password): 
     cherrypy.response.headers['Content-Type'] = 'application/json' 
     return simplejson.dumps(dict(response ="Invalid username and/or password")) 
    else: 
     print "Debug 3" 
     #return network.html here 

class DevicePage(object): 
@cherrypy.expose 
def index(self): 
    return open(os.path.join(MEDIA_DIR, u'network.html')) 


config = {'/media': {'tools.staticdir.on': True, 'tools.staticdir.dir': MEDIA_DIR, }} 

root = LoginPage() 
root.network = DevicePage() 

# DEVELOPMENT ONLY: Forces the browser to startup, easier for development 
def open_page(): 
webbrowser.open("http://127.0.0.1:8080/") 
cherrypy.engine.subscribe('start', open_page) 

cherrypy.tree.mount(root, '/', config = config) 
cherrypy.engine.start() 

在這個問題上的任何幫助或指導將不勝感激

乾杯

Chris

回答

5

基本上有兩種選擇。如果您希望用戶訪問/request和獲取network.html內容背,然後只返回:

class LoginPage(object): 
    ... 
    @cherrypy.expose 
    def request(self, username, password): 
     auth = SiteAuth() 
     if not auth.isAuthorizedUser(username,password): 
      cherrypy.response.headers['Content-Type'] = 'application/json' 
      return simplejson.dumps(dict(response ="Invalid username and/or password")) 
     else: 
      return open(os.path.join(MEDIA_DIR, u'network.html')) 

另一種方法將是用戶訪問/request,如果認可,被重定向到內容在另一個URL,也許/device

class LoginPage(object): 
    ... 
    @cherrypy.expose 
    def request(self, username, password): 
     auth = SiteAuth() 
     if not auth.isAuthorizedUser(username,password): 
      cherrypy.response.headers['Content-Type'] = 'application/json' 
      return simplejson.dumps(dict(response ="Invalid username and/or password")) 
     else: 
      raise cherrypy.HTTPRedirect('/device') 

瀏覽器會再爲新資源的第二請求。

+0

乾杯的意見,這是非常有益的謝謝你。 – Lipwig