Cherrypy中的静态HTML文件
我在使用cherrypy时遇到了一个问题,这本应该是个基本概念,但我还没找到相关的教程或例子(我是cherrypy的新手,请多包涵)。
问题是这样的。
(这是一个测试代码,所以代码里没有强健的身份验证和会话处理)
用户访问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()
如果能在这方面提供任何帮助或指导,我将非常感激。
谢谢!
克里斯
1 个回答
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
,如果他们有权限,就会被重定向到另一个网址的内容,可能是 /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')
然后他们的浏览器会再发起一次请求,去获取新的资源。