我正在尝试使用CherryPy的WSGI服务器来提供静态文件,就像在Using Flask with CherryPy to serve static files中一样。可接受答案的选项2看起来和我想做的完全一样,但是当我尝试使用静态目录处理程序时,我得到了一个KeyError。
我尝试过的:
>>>> import cherrypy
>>>> from cherrypy import wsgiserver
>>>> import os
>>>> static_handler = cherrypy.tools.staticdir.handler(section='/', dir=os.path.abspath('server_files')
>>>> d = wsgiserver.WSGIPathInfoDispatcher({'/': static_handler})
>>>> server = wsgiserver.CherryPyWSGIServer(('localhost', 12345), d)
>>>> server.start()然后,当我尝试访问服务器时,我在控制台中得到一个500响应和以下错误:
KeyError('tools',)
Traceback (most recent call last):
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 1353, in communicate
req.respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 868, in respond
self.server.gateway(self).respond()
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2267, in respond
response = self.req.server.wsgi_app(self.env, self.start_response)
File "/Library/Python/2.7/site-packages/cherrypy/wsgiserver/wsgiserver2.py", line 2477, in __call__
return app(environ, start_response)
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 175, in handle_func
handled = self.callable(*args, **self._merged_args(kwargs))
File "/Library/Python/2.7/site-packages/cherrypy/_cptools.py", line 102, in _merged_args
tm = cherrypy.serving.request.toolmaps[self.namespace]
KeyError: 'tools'每次我尝试点击服务器应该能够显示的任何内容时,它都会显示两次。当我将Flask应用程序连接到服务器上时,Flask应用程序按预期工作,但静态文件服务仍然给出相同的错误。
要让staticdir.handler正常工作,我需要做些什么?
发布于 2015-04-07 19:08:12
我已经尝试了各种方法来让它工作,直到今天,你已经看到的KeyError (在其他问题中)也受到了影响。
通过修改来自this gist的代码(包含在下面),我最终成功地让CherryPy在Django应用程序旁边提供静态服务。
import os
import cherrypy
from cherrypy import wsgiserver
from my_wsgi_app import wsgi
PATH = os.path.abspath(os.path.join(os.path.dirname(__file__), 'public'))
class Root(object):
pass
def make_static_config(static_dir_name):
"""
All custom static configurations are set here, since most are common, it
makes sense to generate them just once.
"""
static_path = os.path.join('/', static_dir_name)
path = os.path.join(PATH, static_dir_name)
configuration = {static_path: {
'tools.staticdir.on': True,
'tools.staticdir.dir': path}
}
print configuration
return cherrypy.tree.mount(Root(), '/', config=configuration)
# Assuming your app has media on diferent paths, like 'c', 'i' and 'j'
application = wsgiserver.WSGIPathInfoDispatcher({
'/': wsgi.application,
'/c': make_static_config('c'),
'/j': make_static_config('j'),
'/i': make_static_config('i')})
server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 8070), application,
server_name='www.cherrypy.example')
try:
server.start()
except KeyboardInterrupt:
print "Terminating server..."
server.stop()希望包装一个Flask应用程序会非常类似。
对我来说,关键是在一个虚拟类上使用cherrypy.tree.mount,而不是尝试直接使用staticdir.handler。
对于好奇的人-我使用了要点中的代码来定制django-cherrypy的runcpserver管理命令的一个版本,尽管事后看来从头开始创建一个新命令可能会更容易。
祝你好运(感谢Alfredo Deza)!
https://stackoverflow.com/questions/29356166
复制相似问题