静态文件的路由问题

时间:2018-05-20 22:04:38

标签: python python-3.x bottle

嗨,好像我的静态文件(例如:<script type="text/javascript" src="js/main.js"></script>在我的标题[部分模板]中)在我不完全localhost:4242时无法提供:

  • http://localhost:4242/:正常工作
  • http://localhost:4242/samples:无效,似乎Bottle使用当前位置连接js/main.js

我的文件以这种方式组织:

  • /runserver.py
  • /project/static/js/main.js

我有以下应用和static_file使用:

static.py

from project.libs.bottle import static_file
from runserver import app


# (Agnostic) Static Routes
@app.get('/<filename:path>')
def send_static(filename):
    return static_file(filename, root='project/static/')

runserver.py

import os
import sys

from project.libs.bottle import Bottle, run, TEMPLATE_PATH, default_app

app = default_app()

dir_name = os.path.dirname(sys.argv[0])

TEMPLATE_PATH.insert(0, './project/views/layout')
TEMPLATE_PATH.insert(1, './project/views')

import project.routes.static
import project.routes.business
import project.routes.error

if __name__ == '__main__':
    run(host="localhost", port=4242, debug=True, reloader=True)

2 个答案:

答案 0 :(得分:0)

root的{​​{1}}路径应该是绝对路径而不是相对路径,因为工作目录可能与项目目录不同。

static_file

此路线也匹配所有路径

return static_file(filename, root='project/static/')

答案 1 :(得分:0)

好的,我设法创建了一个有效的解决方案,考虑了jspcal提到的绝对路径(在实际部署的情况下,例如Azure)。

保持相同的结构(文件):

static.py

# (Agnostic-ish) Static Routes
@app.get('/:path#(css|favicons|fonts|img|js)\/.+#')
def send_static(path):
    return static_file(path, root=STATIC_ROOT)

runserver.py

"""
This script runs the application using a development server.
"""

import os
import sys

from project.libs.bottle import run, TEMPLATE_PATH, default_app, debug

app = default_app()

TEMPLATE_PATH.insert(0, './project/views/layout')
TEMPLATE_PATH.insert(1, './project/views')

# routes contains the HTTP handlers for our server and must be imported.
import project.routes.static
import project.routes.business
import project.routes.error

if '--debug' in sys.argv[1:] or 'SERVER_DEBUG' in os.environ:
    # Debug mode will enable more verbose output in the console window.
    # It must be set at the beginning of the script.
    debug(True)


def wsgi_app():
    """Returns the application to make available through wfastcgi. This is used
    when the site is published to Microsoft Azure."""
    return app


PROJECT_ROOT = os.path.abspath(os.path.dirname(__file__))
STATIC_ROOT = os.path.join(PROJECT_ROOT, 'project/static').replace('\\', '/')
HOST = os.environ.get('SERVER_HOST', 'localhost')
try:
    PORT = int(os.environ.get('SERVER_PORT', '5555'))
except ValueError:
    PORT = 5555


if __name__ == '__main__':
    run(host=HOST, port=PORT, debug=True, reloader=True)

我的静态文件&#34;导入&#34;:

<script type="text/javascript" src="/js/main.js"></script>

致谢:部分灵感来自Github的MS回购:https://github.com/Microsoft/project-python-bottle-webapp