我正在使用 python tornado 构建一个简单的服务器。代码如下:
class IndexHandler(tornado.web.RequestHandler):
def get(self, param):
print("\n\nthis is a get request from indexhandler:")
if param:
#print("frontend/" + param)
self.render("frontend/" + param)
print("I'm html")
else:
print("index.html")
self.render("index.html")
class StaticHandler(tornado.web.StaticFileHandler):
def initialize(self, path, default_filename=None):
self.root = os.path.abspath(path) + os.path.sep
self.default_filename = default_filename
def head(self, path):
self.get(path, include_body=False)
def get(self, param, include_body=True):
abspath = "frontend/" + param
print(abspath)
myfile = open(abspath, "rb")
try:
self.write(myfile.read())
finally:
myfile.close()
class Application(tornado.web.Application):
def __init__(self):
handlers = [
(r"/(.*jpg$)", StaticHandler, {"path": "/frontend"}),
(r"/(.*css$)", StaticHandler, {"path": "/frontend"}),
(r"/(.*html$)", IndexHandler)
]
super(Application, self).__init__(handlers, **settings)
if __name__ == "__main__":
tornado.options.parse_command_line()
http_server = tornado.httpserver.HTTPServer(Application())
http_server.listen(options.port)
tornado.ioloop.IOLoop.instance().start()
但是,当我访问我的网站时,所有 img 和 css 文件都会出错:
Traceback (most recent call last):
File "/usr/local/lib/python3.5/site-packages/tornado/web.py", line 1513, in _execute
self.finish()
File "/usr/local/lib/python3.5/site-packages/tornado/web.py", line 973, in finish
self.set_etag_header()
File "/usr/local/lib/python3.5/site-packages/tornado/web.py", line 1416, in set_etag_header
etag = self.compute_etag()
File "/usr/local/lib/python3.5/site-packages/tornado/web.py", line 2436, in compute_etag
version_hash = self._get_cached_version(self.absolute_path)
AttributeError: 'StaticHandler' object has no attribute 'absolute_path'
[E 170502 11:44:48 web:2063] 500 GET /css/reset.css (108.61.177.156) 2.06ms
最佳答案
See the docs for StaticFileHandler, particularly "subclassing notes" :
Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding StaticFileHandler.get is particularly problematic due to the tight coupling with compute_etag and other methods.
To change the way static urls are generated (e.g. to match the behavior of another server or CDN), override make_static_url, parse_url_path, get_cache_time, and/or get_version.
这里的问题尤其是 get
应该设置 self.absolute_path
( see the code here ) 但您已经用您自己的代码替换了该代码。
我想你不想重写 get
,而是想重写 parse_url_path
:
def parse_url_path(self, url_path):
return 'frontend/' + url_path
关于python - Tornado :AttributeError: 'StaticHandler' 对象没有属性 'absolute_path',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43729781/