Michael
Michael

Reputation: 83

Serving nested static files with Bottle.py

I have the following code. It works to serve the index.html or any file located in the home/ directory, but will not serve any files that are located in nested directories, such as home/image/xyz.png.

import os
import sys
import ctypes
import pprint
import bottle
import socket

from bottle import *

#global functions
def ReadStringFromFile( file ):
    f = open(file, 'r')
    data = f.read()
    f.close()
    return data

def getBits():
    #get the system bits
    sysBit = (ctypes.sizeof(ctypes.c_voidp) * 8)
    if((not(sysBit == 32)) and (not (sysBit == 64))):
        sysBit = 0
    return sysBit

class DevelServer( object ):

    addr = ''

    def __init__( self ):
        self.addr = socket.gethostbyname( socket.gethostname() )
        pass

    def index( self ):
        return ReadStringFromFile('home/index.html')

    #these are not the URLs you are looking for
    def error404( self, error):
        return '<br><br><br><center><h1>Go <a href="/">home</a>, You\'re drunk.'

    def send_static( self, filename):
        print (static_file(filename, root=os.path.join(os.getcwd(), 'home')))
        return static_file(filename, root=os.path.join(os.getcwd(), 'home'))

    #start hosting the application
    def startThis( self ):
        bottle.run(host=self.addr, port=80, debug=True)


#instatiate the main application class an initalize all of the app routes
def Main():
    ThisApp = DevelServer()

    bottle.route('/')(ThisApp.index)
    bottle.route('/home/<filename>')(ThisApp.send_static)

    bottle.error(404)(ThisApp.error404)

    ThisApp.startThis()


Main()

Upvotes: 2

Views: 2407

Answers (1)

ron rothman
ron rothman

Reputation: 18128

Change this line:

bottle.route('/home/<filename>')(ThisApp.send_static)

to this:

bottle.route('/home/<filename:path>')(ThisApp.send_static)

(Add ":path".)

The Bottle docs explain why:

The static_file() function is a helper to serve files in a safe and convenient way (see Static Files). This example is limited to files directly within the /path/to/your/static/files directory because the wildcard won’t match a path with a slash in it. To serve files in subdirectories, change the wildcard to use the path filter...

I ran your code with my modification and it worked for me--does it work for you, too?

Upvotes: 7

Related Questions