python - bottle + gevent无法提供静态文件

时间:2011-12-22 10:29:55

标签: python gevent bottle

我正在使用bottlegevent进行我的python webdev实验。 我的问题是我无法提供静态文件,例如在我的模板中使用外部css。 我的文件夹结构是: /static/css/style.css

我的代码:

index.py

# -*- coding: UTF-8 -*-
from gevent import monkey; monkey.patch_all() #patching default Python threads
from bottle import mount, run, debug #initializing bottle
from routes import root #importing site routes
debug( True )
run( app = root , host = '0.0.0.0' , port = 80 , server = 'gevent' )

routes.py

# -*- coding: UTF-8 -*-
from bottle import *
root = Bottle()

@root.get('/static/<path:path>')
def serve_files( path ):
    return static_file( path , root = '/static/' )

这是我从终端追溯的回溯:

xxx.xxx.xxx.xxx - - [2011-12-22 09:36:44] "GET /static/css/style.css HTTP/1.1" 500 161 0.002867
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/gevent-0.13.6-py2.7-linux-i686.egg/gevent/pywsgi.py", line 438, in handle_one_response
    self.run_application()
  File "/usr/local/lib/python2.7/dist-packages/gevent-0.13.6-py2.7-linux-i686.egg/gevent/pywsgi.py", line 424, in run_application
    self.result = self.application(self.environ, self.start_response)
  File "/usr/local/lib/python2.7/dist-packages/bottle-0.10.4-py2.7.egg/bottle.py", line 849, in __call__
    return self.wsgi(environ, start_response)
  File "/usr/local/lib/python2.7/dist-packages/bottle-0.10.4-py2.7.egg/bottle.py", line 841, in wsgi
    % (html_escape(repr(_e())), html_escape(format_exc(10)))
NameError: global name '_e' is not defined

请帮助。

更新

我已下载不稳定版的Bottle(版本0.11)并将其导入我的脚本。现在没有500错误和追溯,但style.css给了我404。

[2011-12-22 12:42:59] "GET /static/css/style.css HTTP/1.1" 404 122 0.000591

2 个答案:

答案 0 :(得分:4)

你的404是因为你的静态文件的根路径可能是错误的。

只有在根文件系统中有root='/static/'文件夹时,

static才可以。可能不是你真正拥有的。如果您有一个项目文件夹,并且在此文件夹中有一个static文件夹,请使用root='./static/',它将正常工作。

答案 1 :(得分:0)

我知道已经解决了这个问题,但是如果您想要一些面向生产的产品,那么白噪声很棒。

from app import appRoute
from client import clientRoute
from main import mainRoute
from api import apiRoute
from beaker.middleware import SessionMiddleware
from whitenoise import WhiteNoise
if whitecompress:
    static_compress(whitecompress) # auto mins and gzips all js and css files
botapp = bottle.app()
for nftyRoute in (mainRoute, appRoute, clientRoute, apiRoute):          
    botapp.merge(nftyRoute)
botapp = SessionMiddleware(botapp, beaker_opts)
botapp = WhiteNoise(botapp)
botapp.add_files(staticfolder, prefix='static/')
botapp.add_files('{}/common/img/favicon.ico'.format(staticfolder), prefix='favicon.ico')
print('WhiteNoise Enabled')
WSGIServer(("0.0.0.0", int(port)), botapp, handler_class=WebSocketHandler).serve_forever()

这使您可以发布您的静态文件,并且还可以自动为您交付已压缩的文件。我发现此解决方案比瓶子中内置的选项更强大。