【问题标题】:How to handle a HTTP GET request to a file in Tornado?如何在 Tornado 中处理对文件的 HTTP GET 请求?
【发布时间】:2023-10-30 20:54:01
【问题描述】:

我使用的是Ubuntu,有一个名为“webchat”的目录,在这个目录下有4个文件:webchat.py、webchat.css、webchat.html、webchat.js。

使用 Tornado 创建 HTTP 服务器时,我将根 ("/") 映射到我的 python 代码:'webchat.py',如下所示:

import os,sys
import tornado.ioloop
import tornado.web
import tornado.httpserver

#http server for webchat
class webchat(tornado.web.RequestHandler):
  def get(self):
    self.write("Hello, chatter! [GET]")
  def post(self):
    self.write("Hello, chatter! [POST]")

#create http server
Handlers     = [(r"/",webchat)]
App_Settings = {"debug":True}
HTTP_Server  = tornado.web.Application(Handlers,**App_Settings)

#run http server
HTTP_Server.listen(9999)
tornado.ioloop.IOLoop.instance().start()

访问http://localhost:9999 将引导我进入“网络聊天”处理程序(网络聊天类)。但是,我想使用“webchat.py”访问同一目录中的其他文件,它们是 webchat.css、webchat.html 和 webchat.js。

这个 URL 给了我 404:http://localhost:9999/webchat.html。 这个问题有什么可能的解决方案吗?

【问题讨论】:

    标签: python http web chat tornado


    【解决方案1】:

    Tornado 有一个默认的静态文件处理程序,但它会将 url 映射到 /static/,如果你必须访问 /static/webchat.css 中的静态文件可以吗?

    如果你没问题,我强烈建议你用这种方式处理静态文件。

    如果您希望静态文件位于根路径,请查看 web.StaticFileHandler。

    如果你错过了,这里是例子

    (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
    

    顺便说一句,File_NameHandlers 在 Python 中不被视为好的变量名。

    【讨论】:

      【解决方案2】:

      只有文件名和相对路径的简单文件请求的解决方案:

      (1) 为处理程序 URL 模式赋予一个通配符:

      Handlers = [(r"/(.*)",webchat)]
      

      (2) 将(.*) 给出的参数传递给方法'get'和'post':

      def get(self,File_Name):
        File = open(File_Name,"r")
        self.write(File.read())
        File.close()
      
      def post(self,File_Name):
        File = open(File_Name,"r")
        self.write(File.read())
        File.close()      
      

      【讨论】:

      • 安全问题呢?