python tornado读取静态文件

# python tornado读取静态文件
from tornado.web import Application, RequestHandler
from tornado.ioloop import IOLoop
import os


class IndexHandle(RequestHandler):
    def get(self):
        self.render('readImg.html')

app = Application(
    [(r'^/$', IndexHandle)], template_path=os.path.join(os.getcwd(), 'templates'),
      static_path=os.path.join(os.getcwd(), 'static', 'images')
)
app.listen(8000)
IOLoop.instance().start()
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Tornado是一个Python的Web框架,用于开发高性能、可扩展的Web应用程序。在Tornado中,静态文件与重定向是非常常见的功能。下面是对它们的使用说明: 1. 静态文件: 在Tornado中,可以使用`StaticFileHandler`处理静态文件。可以通过以下方式来创建一个`StaticFileHandler`: ```python import tornado.web class StaticHandler(tornado.web.StaticFileHandler): pass ``` `StaticFileHandler`的默认路径是`./static`,可以通过设置`StaticFileHandler`的`path`属性来指定静态文件的路径。例如: ```python import tornado.web class StaticHandler(tornado.web.StaticFileHandler): def initialize(self, path): super().initialize(path=path) ``` 在使用`StaticFileHandler`时,需要指定静态文件的URL和文件路径。可以通过以下方式来指定: ```python import tornado.web class StaticHandler(tornado.web.StaticFileHandler): def initialize(self, path): super().initialize(path=path, default_filename='index.html') def get(self): return super().get(self.request.path[1:]) ``` 上面的代码中,`default_filename`指定了默认返回的文件名,如果URL中没有指定具体的文件名,则返回该文件。`get()`方法实际上是调用了`StaticFileHandler`的`get()`方法,`self.request.path[1:]`是指去掉URL中的第一个字符(即'/')后的字符串。例如,当URL为`http://localhost:8000/static/css/style.css`时,`self.request.path[1:]`的值为`static/css/style.css`。 2. 重定向: 在Tornado中,可以使用`RedirectHandler`来进行重定向。可以通过以下方式来创建一个`RedirectHandler`: ```python import tornado.web class RedirectHandler(tornado.web.RedirectHandler): pass ``` `RedirectHandler`的默认代码是302,可以通过设置`RedirectHandler`的`code`属性来指定重定向的代码。例如: ```python import tornado.web class RedirectHandler(tornado.web.RedirectHandler): def initialize(self, url): super().initialize(url=url, code=301) ``` 在使用`RedirectHandler`时,需要指定重定向的URL。可以通过以下方式来指定: ```python import tornado.web class RedirectHandler(tornado.web.RedirectHandler): def initialize(self, url): super().initialize(url=url, permanent=True) def get(self): return super().get(self.request.path[1:]) ``` 上面的代码中,`permanent`指定了是否永久重定向。`get()`方法实际上是调用了`RedirectHandler`的`get()`方法,`self.request.path[1:]`是指去掉URL中的第一个字符(即'/')后的字符串。例如,当URL为`http://localhost:8000/old`时,`self.request.path[1:]`的值为`old`。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值