Skip to main content
 首页 » 编程设计

python之让我的文件夹在 twistd 中不可见/受限的最佳方法是什么

2025年05月04日9www_RR

几天前,我尝试学习python twisted..
这就是我制作网络服务器的方式:

from twisted.application import internet, service 
from twisted.web import static, server, script 
from twisted.web.resource import Resource 
import os 
 
class NotFound(Resource): 
    isLeaf=True 
    def render(self, request): 
        return "Sorry... the page you're requesting is not found / forbidden" 
 
class myStaticFile(static.File): 
    def directoryListing(self): 
        return self.childNotFound 
 
#root=static.file(os.getcwd()+"/www") 
root=myStaticFile(os.getcwd()+"/www") 
root.indexNames=['index.py'] 
root.ignoreExt(".py") 
root.processors = {'.py': script.ResourceScript} 
root.childNotFound=NotFound() 
application = service.Application('web') 
sc = service.IServiceCollection(application)  
i = internet.TCPServer(8080, server.Site(root))#@UndefinedVariable 
i.setServiceParent(sc) 

在我的代码中,我为 twisted.web.static.File 创建了一个实例类并override directoryListing。
因此,当用户尝试访问我的资源文件夹(http://localhost:8080/resource/ 或 http://localhost:8080/resource/css)时,它将返回一个 notFound 页面。
但他仍然可以打开/阅读 http://localhost:8080/resource/css/style.css。
它有效...

我想知道的是..这是正确的方法吗???
还有另一种“完美”的方式吗?
我正在寻找一个禁用 directoryListing 的配置,如 root.dirListing=False。但没有运气......

请您参考如下方法:

是的,这是一种合理的方式。您还可以使用 twisted.web.resource.NoResource 或 twisted.web.resource.Forbidden 而不是定义您自己的 NotFound。