最近用 Python 做了 Tensorflow 的服务,搭建web服务框架,就使用了比较熟悉的 Tornado 框架,框架用起来非常简单快捷,一般最终使用的时候是个单独的服务,因此顺手给简单的加了跨域的头。
自以为的设置
直接找个DEMO看一下,就开始实现代码,由于是图像识别,因此分了两步,第一步是请求识别,返回识别结果,同时识别结果里面包含了一个本地识别打标图片的下载地址,一般这个图片就是客户端会直接加载的图,疏于对图片跨域测试,本地测试没问题。
大概的框架如下
class DetectStaticFileHandler(tornado.web.StaticFileHandler): |
大概是这么个原理,下载图片也是没问题的。但是真正到跨域的时候,图片下不来,也就是说跨域没生效,同样的接口跨域却成功了,直接调试了下代码,惊奇的发现程序并没用进入到自定义的处理器中。
正确的可用配置
去跟踪了一会代码,发现怎么配置都无法进入自定义处理器中,并且 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 thestatic_url_prefix
setting), and we will serve/favicon.ico
and/robots.txt
from the same directory. A custom subclass ofStaticFileHandler
can be specified with thestatic_handler_class
setting.
原来是通过配置的方式,而且貌似上面能访问完全是因为 static
重名的原因。具体的静态文档配置参数如下
static_hash_cache
: Default isTrue
; ifFalse
static urls will be recomputed on every request. This option is new in Tornado 3.2; previously this functionality was controlled by thedebug
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 defaulttornado.web.StaticFileHandler
.static_handler_args
, if set, should be a dictionary of keyword arguments to be passed to the handler’sinitialize
method.
按照官方文档进行修改即可
settings = { |
虽然通过 /static/xxxx.jpg
请求到图片了,但是却只能用默认的 static_url_prefix
参数(static
)访问,修改为其他值也没效果,只好暂时先使用 static
路径了,毕竟暂时也没什么影响。
关于跨域设置,StaticFileHandler
的源代码里面有设置头域的重载方法,重载该方法并设置跨域的头即可
class DetectStaticFileHandler(tornado.web.StaticFileHandler): |