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

I use Ubuntu and have a directory called "webchat", there are 4 files in this directory: webchat.py, webchat.css, webchat.html, webchat.js.

When creating an HTTP server using Tornado, I map the root ("/") to my Python code: "webchat.py" as follows:

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 (webchat class). However, I want to access other files in the same directory using "webchat.py", these are webchat.css, webchat.html and webchat.js.

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

+4
source share
2 answers

Tornado has a default static file handler, but it displays the url in / static /, will it be ok if you have to access your static file in /static/webchat.css?

If you're okay with this, I highly recommend that you handle the static file this way.

If you want your static file to be in the root path, take a look at web.StaticFileHandler.

If you missed it, here is an example

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

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

+12
source

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

(1) Give the wildcat handler url pattern:

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

(2) Pass the parameter represented by (. *) To the get and post methods:

 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() 
+5
source

Source: https://habr.com/ru/post/1399357/


All Articles