Cherrypy中的静态html文件

Kra*_*n18 8 python web-applications cherrypy

我有一个问题,应该是一个基本的概念在cherrypy但是我一直无法找到关于如何做到这一点的教程或例子(我是一个Cherrypy新手,温柔).

问题.(这是一个测试部分,因此代码中缺乏强大的身份验证和会话)

用户转到index.html页面,该页面是登录页面,用于输入详细信息,如果详细信息与文件中的内容不匹配,则会返回并显示错误消息.这有效!如果细节是正确的,那么向用户显示不同的html文件(network.html)这是我无法工作的一点.

当前的文件系统如下所示: -

AppFolder
  - main.py (main CherryPy file)
  - media (folder)
      - css (folder)
      - js (folder)
      - index.html
      - network.html
Run Code Online (Sandbox Code Playgroud)

文件的布局似乎是正确的,因为我可以访问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()
Run Code Online (Sandbox Code Playgroud)

任何有关此事的帮助或指导将不胜感激

干杯

克里斯

fum*_*chu 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'))
Run Code Online (Sandbox Code Playgroud)

另一种方法是让用户访问/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')
Run Code Online (Sandbox Code Playgroud)

然后,他们的浏览器将再次请求新资源.