【问题标题】:Static html Files in CherrypyCherrypy 中的静态 html 文件
【发布时间】:2011-09-25 19:03:39
【问题描述】:

我对 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()

在此问题上的任何帮助或指导将不胜感激

干杯

克里斯

【问题讨论】:

    标签: python web-applications cherrypy


    【解决方案1】:

    您基本上有两种选择。如果您希望用户访问 /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')
    

    然后,他们的浏览器将对新资源进行第二次请求。

    【讨论】: