Make static HTML directory accessible with CherryPy and file-protocol

1.8k views Asked by At

I have a WEB application with some static WEB page (the documentation). I'd like the documentation (written in html) to be accessible from the application running under cherrypy, but also as static files that we can open without running the WEB server ...

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

this works fine, but as I do have multiple pages, from cherrypy the link should be "/test" where in the static mode I have "/test.html". I wanted to make cherrypy maps the URL but I couldn't find a way to do so ...

thanks for your help, Jerome

1

There are 1 answers

2
saaj On

You can achieve it with staticdir tool and using relative URLs in your documentation. The latter will allso access from both http:// and file:// protocols.

Here's how it can look like.

.
├── 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>