Python 在tornado中阻止对服务器文件的直接文件访问
我正在使用python和tornado Web服务器。 该应用程序运行良好,但我无法找到一种方法来阻止用户通过url直接访问服务器文件。 例如,我在服务器中有以下文件: program.pyPython 在tornado中阻止对服务器文件的直接文件访问,python,tornado,Python,Tornado,我正在使用python和tornado Web服务器。 该应用程序运行良好,但我无法找到一种方法来阻止用户通过url直接访问服务器文件。 例如,我在服务器中有以下文件: program.py index.html main.html 我想阻止用户通过web url直接访问上述服务器文件 例如:localhost:8080/program.py或/index.html 我只想让他们访问localhost:8080/或/home 提前谢谢 from ws4py.client.tornadoclien
index.html
main.html
我想阻止用户通过web url直接访问上述服务器文件
例如:localhost:8080/program.py或/index.html 我只想让他们访问localhost:8080/或/home 提前谢谢
from ws4py.client.tornadoclient import TornadoWebSocketClient
import tornado.ioloop
import tornado.web
import tornado.websocket
import tornado.template
SETTING_CLIENT_LISTEN_PORT = 8080
class MainHandler(tornado.web.RequestHandler):
def get(self):
try:
loader = tornado.template.Loader(".")
self.write(loader.load("index.html").generate())
except Exception as e:
print("exception occured", e)
class CWSHandler(tornado.websocket.WebSocketHandler):
global waiters
def open(self):
print('###FUNCTION CWSHandler.open(self) start')
def on_close(self):
print('###FUNCTION CWSHandler.open(self) close')
def on_message(self, message):
print('###FUNCTION CWSHandler.on_message msg:', message)
settings = {
"cookie_secret": "bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=",
"login_url": "/",
}
application = tornado.web.Application(handlers=[
(r'/', MainHandler),
(r'/cws', CWSHandler),
(r"/(.*)", tornado.web.StaticFileHandler,{'path':'./'})
], cookie_secret="bZJc2sWbQLKos6GkHn/VB9oXwQt8S0R0kRvJ5/xJ89E=")
if __name__ == "__main__":
server = tornado.httpserver.HTTPServer(application)
server.listen(SETTING_CLIENT_LISTEN_PORT)
try:
tornado.ioloop.IOLoop.instance().start()
server.stop()
except KeyboardInterrupt:
print("Keyboard interupt")
pass
finally:
server.stop()
tornado.ioloop.IOLoop.instance().stop()
问题在于您的URL,特别是:
(r"/(.*)", tornado.web.StaticFileHandler,{'path':'./'})
您已将r'/(.*)
映射到项目目录{'path':'./'}
。因此,如果一个请求像localhost:8080/program.py
,它将与这个-/(*)
匹配,然后tornado将在项目目录中查找名为program.py
的文件。如果它在那里找到它,它将提供该文件
您应该将所有静态文件保存在项目目录中名为static
(您可以随意命名)的单独目录中。然后将此目录映射到所需的url
例如:
(r"/(.*)", tornado.web.StaticFileHandler,{'path': 'static'})
或者更好的是,在/static/
url下提供该目录,而不是-*
(r"/static/(.*)", tornado.web.StaticFileHandler,{'path': 'static'})
如果他们有访问权限,那是因为您正在启用它。如果您需要具体建议,请发布您的代码。hi添加了我的代码。非常感谢您指出了静态路径。这就是我需要的。谢谢again@chipnot不客气。如果此答案解决了您的问题,请随意单击此答案左侧的检查图标。