Tutorial :How to use cherrypy as a web server for static files?



Question:

Is it any easy way to use CherryPy as an web server that will display .html files in some folder? All CherryPy introductory documentation states that content is dynamically generated:

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

Is it any easy way to use index.html instead of HelloWorld.index() method?


Solution:1

This simple code will serve files on current directory.

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


Solution:2

Here is some information on serving static content with CherryPy: http://docs.cherrypy.org/stable/progguide/files/static.html

BTW, here is a simple way to share the current directory over HTTP with python:

  # Python 3  $ python -m http.server [port]    # Python 2  $ python -m SimpleHTTPServer [port]  


Solution:3

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

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »