2

我有以下代码。它适用于提供 index.html 或位于 home/ 目录中的任何文件,但不会提供位于嵌套目录中的任何文件,例如 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()
4

1 回答 1

7

更改此行:

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

对此:

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

(添加“:路径”。)

Bottle 文档解释了原因:

static_file() 函数是一个帮助程序以安全方便的方式提供文件(请参阅静态文件)。此示例仅限于直接位于 /path/to/your/static/files 目录中的文件,因为通配符不会匹配带有斜杠的路径。要在子目录中提供文件,请将通配符更改为使用路径过滤器...

我用我的修改运行了你的代码,它对我有用——它也对你有用吗?

于 2013-03-29T23:24:05.177 回答