python-3.x - 使用 Bottle.py 提供嵌套的静态文件

标签 python-3.x bottle

我有以下代码。它可以为 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()

最佳答案

改变这一行:

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

为此:

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

(添加“:路径”。)

The Bottle docs解释原因:

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

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

关于python-3.x - 使用 Bottle.py 提供嵌套的静态文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15696358/

相关文章:

python - Ajax:无法将 Json 对象发送到 Bottle Web 服务

python - Tensorflow 中的分类和连续交叉特征列

python - Bottle 服务器未完全重置,保留旧的、不正确的功能

linux - python bottle 服务器在 Linux 上不工作

javascript - 在 Javascript 和 Python 之间传递变量

python - 单击 HTML 按钮时如何运行脚本(Python、Bottle)

python-3.x - 如何在 OpenCV 中获取 VideoCapture 对象的 4 字符编解码器代码?

Python 关闭一个闪存驱动器,如何启动 IDLE?

python-3.x - Pandas 创建没有周末的日期范围

python - 如何将未知时区的字符串datetime转换为python中的时间戳