2013-10-30 23 views
1

我想用烧瓶application dispatching cherrypy。该文档以开发服务器为例,但使用cherrypy example snippet并修改url前缀时,页面无法找到静态文件夹。获取正确的静态URL与烧瓶应用程序的cherrypy调度

我的目录结构如下:

cherry 
├── app1 
│   ├── __init__.py 
│   └── app1.py 
├── app2 
│   ├── __init__.py 
│   ├── app2.py 
│   ├── static 
│   │   └── js.js 
│   └── templates 
│    └── index.html 
└── cherry_app.py 

一些相关文件:

## cherry_app.py 
from cherrypy import wsgiserver 
from app1.app1 import app as app1 
from app2.app2 import app as app2 

d = wsgiserver.WSGIPathInfoDispatcher({'/first': app1, 
             '/second': app2, 
             }) 

server = wsgiserver.CherryPyWSGIServer(('0.0.0.0', 9999), d) 

if __name__ == '__main__': 
    try: 
     print 'Start at 0.0.0.0:9999' 
     server.start() 
    except KeyboardInterrupt: 
     server.stop() 


## app2.py 
from flask import Flask, send_file 
import flask 

app = Flask(__name__) 
@app.route("/") 
def root(): 
    return ("Hello World!\nThis is the second app. Url is %s" 
      % flask.url_for('root')) 

@app.route("/index") 
def index(): 
    return send_file('templates/index.html') 

if __name__ == "__main__": 
    app.run() 


## index.html 
<script src="/static/js.js"></script> 

JS loaded? 

## js.js 
alert('Loaded!'); 

http://0.0.0.0:9999/second/正确地告诉我,Url is /second/,当我去http://0.0.0.0:9999/second/static/js.js的JavaScript加载。但html给出了错误GET http://0.0.0.0:9999/static/js.js 404 (Not Found)。看来它不知道找/static时使用的前缀/second,甚至当我改变行:

app = Flask(__name__, static_url_path='/second/static') 

我如何才能让网页正确加载静态文件吗?最好没有html模板(如jinja)。

回答

2

您是否尝试使用url_for来查找静态文件?这里是Flask quickstart中的static files section

所以在您的情况,修改script元素src值的index.html:

<script src="{{ url_for("static", "js.js") }}"></script> 

第二个参数js.js应该是静态文件的相对路径(说js.js)的静态文件夹。所以,如果静态看起来像目录结构:

static/scripts/js.js 

只是scripts/js.js替换js.js

<script src="{{ url_for("static", "scripts/js.js") }}"></script> 

希望这将是有意义的。

+0

'url_for'正常工作(app2.py中的第一条路线),但我想要一种不涉及模板的方法(最后一句),因为它给Angular带来了太多麻烦... if尽管如此,我也没有其他办法可以解决这个问题。 – beardc