Tornado静态文件跨域设置

最近用 Python 做了 Tensorflow 的服务,搭建web服务框架,就使用了比较熟悉的 Tornado 框架,框架用起来非常简单快捷,一般最终使用的时候是个单独的服务,因此顺手给简单的加了跨域的头。

自以为的设置

直接找个DEMO看一下,就开始实现代码,由于是图像识别,因此分了两步,第一步是请求识别,返回识别结果,同时识别结果里面包含了一个本地识别打标图片的下载地址,一般这个图片就是客户端会直接加载的图,疏于对图片跨域测试,本地测试没问题。

大概的框架如下

class DetectStaticFileHandler(tornado.web.StaticFileHandler):
def get(self):
self.set_header('Access-Control-Allow-Origin', "*")
super().get()

class DetectDataHandler(tornado.web.RequestHandler):
def post(self):
self.set_header('Access-Control-Allow-Origin', "*")
...

tornado.web.Application(
[(r"/vege/data", DetectDataHandler),
(r"/(.*\.jpg)", DetectStaticFileHandler, {'path':'static'})],
**settings,
)

大概是这么个原理,下载图片也是没问题的。但是真正到跨域的时候,图片下不来,也就是说跨域没生效,同样的接口跨域却成功了,直接调试了下代码,惊奇的发现程序并没用进入到自定义的处理器中。

正确的可用配置

去跟踪了一会代码,发现怎么配置都无法进入自定义处理器中,并且 tornado.web.StaticFileHandler 的注释也写了是支持继承的,那到底哪不对了。网上也是这个问题很多,都没什么解决办法。无意间发现 static_handler_class 及其在线文档说明地址:

https://www.tornadoweb.org/en/stable/web.html

里面有明确说明

You can serve static files by sending the static_path setting as a keyword argument. We will serve those files from the /static/ URI (this is configurable with the static_url_prefixsetting), and we will serve /favicon.ico and /robots.txt from the same directory. A custom subclass of StaticFileHandler can be specified with the static_handler_class setting.

原来是通过配置的方式,而且貌似上面能访问完全是因为 static 重名的原因。具体的静态文档配置参数如下

  • static_hash_cache: Default is True; if False static urls will be recomputed on every request. This option is new in Tornado 3.2; previously this functionality was controlled by the debug setting.
  • static_path: Directory from which static files will be served.
  • static_url_prefix: Url prefix for static files, defaults to "/static/".
  • static_handler_class, static_handler_args: May be set to use a different handler for static files instead of the default tornado.web.StaticFileHandler.static_handler_args, if set, should be a dictionary of keyword arguments to be passed to the handler’s initialize method.

按照官方文档进行修改即可

settings = {
"static_path": 'static_images',
"static_handler_class": DetectStaticFileHandler
}

tornado.web.Application(
[(r"/vege/data", DetectDataHandler)],
**settings
)

虽然通过 /static/xxxx.jpg 请求到图片了,但是却只能用默认的 static_url_prefix 参数(static)访问,修改为其他值也没效果,只好暂时先使用 static 路径了,毕竟暂时也没什么影响。

关于跨域设置,StaticFileHandler 的源代码里面有设置头域的重载方法,重载该方法并设置跨域的头即可

class DetectStaticFileHandler(tornado.web.StaticFileHandler):
def set_extra_headers(self, path):
self.set_header('Access-Control-Allow-Origin', "*")
最近的文章

Systemd服务无目录访问权限问题

记录一下,在系统安装 Systemd 服务无法访问某些目录的问题。 问题出现CentOS7已经采用Systemd机制了,比如使用 Caddy 服务器,使用YUM即可安装。 Caddy 是一个优秀的Web服务器,支持 HTTP2.0 以及 QUIC 协议,另外也支持代理功能。同时这个服务器还支持自动 …

技术 继续阅读
更早的文章

GCC4.8正则异常问题

之前在做28181服务开发的时候有意使用了boost库,以及VS 2010以及CentOS 7 自带 GCC都能支持的C++11的特性,月初发现程序好像不正常工作了。日志拉取还真是一个漫长的过程,好的一点是之前日志还算打的足够详细,特别是异常错误部分,所以很容易就找到了出错日志。 关于正则的使用直接 …

技术 继续阅读