(改编自这个问题)
看起来 webapp2 没有静态文件处理程序;你必须自己动手。这是一个简单的:
import mimetypes
class StaticFileHandler(webapp2.RequestHandler):
def get(self, path):
# edit the next line to change the static files directory
abs_path = os.path.join(os.path.dirname(__file__), path)
try:
f = open(abs_path, 'r')
self.response.headers.add_header('Content-Type', mimetypes.guess_type(abs_path)[0])
self.response.out.write(f.read())
f.close()
except IOError: # file doesn't exist
self.response.set_status(404)
在您的app
对象中,添加一条路线StaticFileHandler
:
app = webapp2.WSGIApplication([('/', MainHandler), # or whatever it's called
(r'/static/(.+)', StaticFileHandler), # add this
# other routes
])
现在http://localhost:8080/static/mydata.json
(比如说)将加载mydata.json
.
请记住,此代码存在潜在的安全风险:它允许您网站的任何访问者阅读您静态目录中的所有内容。出于这个原因,您应该将所有静态文件保存在一个不包含您希望限制访问的任何内容(例如源代码)的目录中。