How to handle a HTTP GET request to a file in Tornado?

﹥>﹥吖頭↗ 提交于 2020-01-01 06:08:34

问题


I'm using Ubuntu and have a directory called "webchat", under this directory there are 4 files: webchat.py, webchat.css, webchat.html, webchat.js.

When creating a HTTP server using Tornado, i map the root ("/") to my python code: 'webchat.py' as follow:

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()

Accessing http://localhost:9999 will lead me to the 'webchat' handler (class webchat). However, i want to access the other files in the same directory with 'webchat.py', those are webchat.css, webchat.html, and webchat.js.

This URL gives me 404: http://localhost:9999/webchat.html. Any possible solutions to this matter?


回答1:


Tornado has a default static file handler, but it maps url to /static/, will it be ok if you must access your static file at /static/webchat.css ?

If you are ok with this, I strongly suggest that you handle static file this way.

If you want your static file at root path, have a glance look at web.StaticFileHandler.

In case you missed it, here is the example

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

BTW, File_Name and Handlers are not considered good variable names in Python.




回答2:


Solution for a simple file request with only file name and relative path:

(1) Give the handler URL pattern a wildcat:

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

(2) Pass the parameter presented by (.*) to methods 'get' and '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()      


来源:https://stackoverflow.com/questions/9531092/how-to-handle-a-http-get-request-to-a-file-in-tornado

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!