Python 通过cherrypy分派flask应用程序获取正确的静态URL
我正试着用cherrypy来做烧瓶。文档给出了一个开发服务器的示例,但是当使用和修改url前缀时,页面无法找到静态文件夹 我的目录结构如下:Python 通过cherrypy分派flask应用程序获取正确的静态URL,python,flask,url-routing,cherrypy,static-files,Python,Flask,Url Routing,Cherrypy,Static Files,我正试着用cherrypy来做烧瓶。文档给出了一个开发服务器的示例,但是当使用和修改url前缀时,页面无法找到静态文件夹 我的目录结构如下: cherry ├── app1 │ ├── __init__.py │ └── app1.py ├── app2 │ ├── __init__.py │ ├── app2.py │ ├── static │ │ └── js.js │ └── templates │ └── index.html └── cher
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!');
如何让网页正确加载静态文件?最好不使用html模板(如jinja)。您是否尝试使用
url\u来定位静态文件?这是烧瓶中的快速启动
因此,在您的情况下,修改index.html中script
元素的src
值:
<script src="{{ url_for("static", "js.js") }}"></script>
只需将js.js
替换为scripts/js.js
:
<script src="{{ url_for("static", "scripts/js.js") }}"></script>
希望这会有意义。url\u for
工作正常(app2.py中的第一个路径),但我希望有一种不涉及模板的方法(最后一句),因为它给我带来了太多的角度问题…如果没有其他方法,我可能会这样做。
static/scripts/js.js
<script src="{{ url_for("static", "scripts/js.js") }}"></script>