我正在使用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
答案 0 :(得分:0)
See the docs for StaticFileHandler, particularly "subclassing notes":
子类只应覆盖本节中讨论的方法;覆盖其他方法容易出错。由于与compute_etag和其他方法紧密耦合,覆盖StaticFileHandler.get特别成问题。
要更改静态网址的生成方式(例如,为了匹配其他服务器或CDN的行为),请覆盖make_static_url,parse_url_path,get_cache_time和/或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