【问题标题】:Make static HTML directory accessible with CherryPy and file-protocol使用 CherryPy 和文件协议使静态 HTML 目录可访问
【发布时间】:2015-08-27 08:15:48
【问题描述】:

我有一个带有一些静态 WEB 页面(文档)的 WEB 应用程序。我希望文档(用 html 编写)可以从运行在 cherrypy 下的应用程序访问,也可以作为静态文件,我们可以在不运行 WEB 服务器的情况下打开......

class AppServer( JFlowServer ):

    @cherrypy.expose
    def index(self, **kwargs):
        return " ".join( open(os.path.join(WEB_DIR, "index.html" )).readlines() )


    @cherrypy.expose
    def test(self, **kwargs):
        return " ".join( open(os.path.join(WEB_DIR, "test.html" )).readlines() )

这很好用,但是因为我有多个页面,所以从cherrypy 链接应该是“/test”,在静态模式下我有“/test.html”。我想让cherrypy映射URL,但我找不到这样做的方法......

感谢您的帮助, 杰罗姆

【问题讨论】:

    标签: python html cherrypy file-uri


    【解决方案1】:

    您可以使用staticdir tool 并在您的文档中使用相对 URL 来实现它。后者也可以从 http://file:// 协议访问。

    这是它的样子。

    .
    ├── app.py
    └── docs
        ├── a.html
        ├── b.html
        └── index.html
    

    app.py

    #!/usr/bin/env python3
    
    
    import os
    
    import cherrypy
    
    
    path   = os.path.abspath(os.path.dirname(__file__))
    config = {
      'global' : {
        'server.socket_host' : '127.0.0.1',
        'server.socket_port' : 8080,
        'server.thread_pool' : 8,
      },
      '/docs' : {
        'tools.staticdir.on'    : True,
        'tools.staticdir.dir'   : os.path.join(path, 'docs'),
        'tools.staticdir.index' : 'index.html',
        'tools.gzip.on'         : True  
      }  
    }
    
    
    class App:
    
      @cherrypy.expose
      def index(self):
        return '''Some dynamic content<br/><a href="/docs">See docs</a>'''
    
    
    if __name__ == '__main__':
      cherrypy.quickstart(App(), '/', config)
    

    docs/index.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>Docs index</title>
    </head>
    <body>
      <p><a href='/'>Back to home page</a> (not relevant from file://)</p>
      <p><a href='a.html'>See A</a></p>
      <p><a href='b.html'>See B</a></p>
    </body>
    </html>
    

    docs/a.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>A page</title>
    </head>
    <body>
      <p><a href='index.html'>Back to index</a></p>
      <p><a href='b.html'>See B</a></p>
    </body>
    </html>
    

    docs/b.html

    <!DOCTYPE html>
    <html>
    <head>
      <title>B page</title>
    </head>
    <body>
      <p><a href='index.html'>Back to index</a></p>
      <p><a href='a.html'>See A</a></p>
    </body>
    </html>
    

    【讨论】:

    • 感谢您的回答,但这不是我想要的。我确实希望cherrypy服务器本身返回html页面!这里只有一个文档链接。
    • @user1595929 HTML 页面实际上是由 CherryPy 提供的,您可以在 sn-p 运行时访问http://localhost:8080/docs 和下面的链接来确认这一点。它们由工具提供服务,您的代码中没有处理程序。这不应该让你感到困惑。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2010-10-31
    • 2014-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多