静态文件的路由问题

Routing issues for static files

嗨,当我不完全是 localhost:4242:

时,我的静态文件(例如:header [部分模板] 中的 <script type="text/javascript" src="js/main.js"></script>)似乎无法提供

我的文件是这样组织的:

我有以下应用,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)

static_fileroot路径应该是绝对路径而不是相对路径,因为工作目录可能与项目目录不同。

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

这条路线也匹配所有路径

@app.get('/<filename:path>')

好的,我设法创建了一个可行的解决方案,同时考虑了 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)

还有我的静态文件"imports":

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

致谢:部分灵感来自 Github 上的 MS 存储库:https://github.com/Microsoft/project-python-bottle-webapp