如何在Tornado中处理对文件的HTTP GET请求? [英] How to handle a HTTP GET request to a file in Tornado?

查看:352
本文介绍了如何在Tornado中处理对文件的HTTP GET请求?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Ubuntu并且有一个名为webchat的目录,在这个目录下有4个文件:webchat.py,webchat.css,webchat.html,webchat.js。

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.

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

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

访问< a href =http:// localhost:9999 =nofollow> http:// lo calhost:9999 将引导我进入'网络聊天'处理程序(类网聊)。但是,我想使用'webchat.py'访问同一目录中的其他文件,这些文件是webchat.css,webchat.html和webchat.js。

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.

这个URL给了我404: http:// localhost:9999 / webchat.html
这个问题的任何可能的解决方案?

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

推荐答案

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

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.

如果你想要你的静态文件在根路径,请看一下web.StaticFileHandler。

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 处理程序在Python中不被视为好的变量名。

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

这篇关于如何在Tornado中处理对文件的HTTP GET请求?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆