限制对 python tornado 网络服务器中某些文件、文件夹的访问

restrict access to certain files, folders in python tornado web server

我在 python3 中启动了一个 tornado 网络服务器,这里是一些简化的启动代码:

import tornado.ioloop, tornado.web
root = os.path.dirname(__file__)
startPage = 'index.html' 

class allStops(tornado.web.RequestHandler):
    def get(self):
        self.write('yo man')

def make_app():
    return tornado.web.Application([
        (r"/API/allStops", allStops),
        (r"/(.*)", tornado.web.StaticFileHandler, {"path": root, "default_filename": startPage})
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(5005)
    tornado.ioloop.IOLoop.current().start()

网络服务器工作正常。我在 index.html 周围有各种文件和文件夹。因此,当我们在浏览器中打开 localhost:5005 时,我们会看到 index.html(静态网站)的内容,并且通过其中的链接可以访问所有其他内容。我也可以通过输入 URL.

直接访问它们

这就是我的问题所在。如果这个程序在 launch.py 中,那么我可以通过 localhost:5050/launch.py 从浏览器中看到整个程序。我想禁止。我还想阻止浏览器访问特定子文件夹的内容。但与此同时,我不想限制对所有其他文件和文件夹的访问:默认的允许所有状态很好。我怎样才能做到这一点?

Subclass StaticFileHandler 然后在 validate_absolute_path 方法中验证文件名。为您不想提供的文件引发 404 或 403 错误。

from tornado import web
from tornado.web import HTTPError

class MyStaticFileHandler(web.StaticFileHandler):
    def validate_absolute_path(self, root, absolute_path):
        if absolute_path.endswith('.py'):
            # raise 403 Forbidden error for all files ending with .py
            raise HTTPError(403)

        return super().validate_absolute_path(root, absolute_path)

然后在您的 url 处理程序中使用此 class。


自定义错误响应:

如果您设置debug=False,Tornado 将自动显示与状态代码相关的适当消息而不是异常。

如果要发送自定义错误模板,可以这样做:

...

def validate_absolute_path(self, root, absolute_path):
    if absolute_path.endswith('.py'):
        self.set_status(404)
        # send a custom 404 response from an html file
        with open("path/to/404.html", "r") as f:
            self.write(f.read())

        return None

    return super().validate_absolute_path(root, absolute_path)