2011-06-30 47 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