我对 cherrypy 中的基本概念应该是什么有疑问,但到目前为止,我一直无法找到有关如何执行此操作的教程或示例(我是 Cherrypy 新手,请保持温和)。
问题。 (这是一个测试片,因此代码中缺少可靠的身份验证和 session )
用户转到 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()
在此问题上的任何帮助或指导将不胜感激
干杯
克里斯
最佳答案
您基本上有两个选择。如果您希望用户访问 /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')
然后他们的浏览器将对新资源发出第二次请求。
关于python - Cherrypy 中的静态 html 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6531963/