18

.html将 CherryPy 用作将在某个文件夹中显示文件的 Web 服务器有什么简单的方法吗?所有 CherryPy 介绍性文档都声明内容是动态生成的:

import cherrypy
class HelloWorld(object):
    def index(self):
        return "Hello World!"
    index.exposed = True
cherrypy.quickstart(HelloWorld())

有什么简单的方法可以index.html代替 HelloWorld.index() 方法吗?

4

4 回答 4

35

这个简单的代码将提供当前目录中的文件。

import os
import cherrypy

PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass

cherrypy.tree.mount(Root(), '/', config={
        '/': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': PATH,
                'tools.staticdir.index': 'index.html',
            },
    })

cherrypy.quickstart()
于 2009-04-17T11:53:00.620 回答
6

以下是有关使用 CherryPy 提供静态内容的一些信息:http: //docs.cherrypy.org/stable/progguide/files/static.html

顺便说一句,这是通过 HTTP 与 python 共享当前目录的简单方法:

# Python 3
$ python -m http.server [端口]

# Python 2
$ python -m SimpleHTTPServer [端口]
于 2009-04-17T09:06:31.317 回答
0
# encode: utf-8

import cherrypy
WEB_ROOT = "c:\\webserver\\root\\"

class CServer( object ) :
    @cherrypy.expose
    def do_contact(self, **params):
        pass

cherrypy.server.socket_port = 80
# INADDR_ANY: listen on all interfaces
cherrypy.server.socket_host = '0.0.0.0'
conf = { '/':
  { 'tools.staticdir.on' : True,
    'tools.staticdir.dir' : WEB_ROOT,
    'tools.staticdir.index' : 'index.html' } }
cherrypy.quickstart( CServer(), config = conf )
于 2009-04-17T11:48:02.957 回答
0

我发布了这个新答案,因为已接受答案的解决方案已过时。这个简单的代码将提供当前目录中的文件。

import os
import cherrypy

PATH = os.path.abspath(os.path.dirname(__file__))
class Root(object): pass

cherrypy.tree.mount(Root(), '/', config={
        '/': {
                'tools.staticdir.on': True,
                'tools.staticdir.dir': PATH,
                'tools.staticdir.index': 'index.html',
            },
    })

cherrypy.engine.start()
cherrypy.engine.block()

当然,这只是对已经发布的内容的总结。

于 2021-01-06T14:06:35.553 回答