在 Flask 中找不到"static"文件的正确路径



运行Flask应用程序时,我使用带有Gunicorn和Apache的ProxyPass将站点的"根"更改为"子目录"URL。

我终于 https://example.com/flaskapp 加载了网站,但我所有的静态文件都返回 404。没有 url 结构的组合允许我在浏览器中查看文件(例如.css文件(。

我有:

* flaskapp (project folder)
* app (main folder)
* __init__.py
* views.py
* controllers.py
* static
* templates
* venv
* requirements.txt

我用:gunicorn app:app -b 0.0.0.0:8000

我的init.py 文件包含:

from flask import Flask
import logging
from logging.config import dictConfig
dictConfig({
'version': 1,
'formatters': {'default': {
'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
}},
'handlers': {'wsgi': {
'class': 'logging.StreamHandler',
'stream': 'ext://flask.logging.wsgi_errors_stream',
'formatter': 'default'
}},
'root': {
'level': 'DEBUG',
'handlers': ['wsgi']
}
})
logger = logging.getLogger(__name__)
if __name__ == '__main__':
gunicorn_logger = logging.getLogger('gunicorn.debug')
logger.handlers = gunicorn_logger.handlers
logger.setLevel(gunicorn_logger.level)
# Initialize the app
app = Flask(__name__, instance_relative_config=True, static_url_path='', static_folder='static')
# Load the config file
app.config.from_pyfile('app.cfg')
from app import controllers
from app import views
if __name__ == '__main__':
app.run(host='0.0.0.0', port=8000, debug=app.config['DEBUG'])

在我的一个 html 文件中,以下是我尝试包含.css文件的方式:

<link href="{{ url_for('static', filename='lib/font-awesome/css/font-awesome.css') }}" rel="stylesheet">

由于该站点以"/flaskapp"作为根运行,因此我认为URL有问题,或者我没有为静态路由正确设置。

编辑:这是我如何在Apache中设置我的.conf来代理

ProxyPreserveHost On
ProxyPass /flaskapp http://localhost:8000/
ProxyPassReverse /flaskapp http://localhost:8000/
Timeout 2400
ProxyTimeout 240

正确设置它会出错的地方?

这是我将静态文件和缓存加载到内存的代码

STATIC_FILE = {}
def load_file(file_name):
ext = file_name.split(".")[-1]
if file_name not in STATIC_FILE:
with open("./public{}".format(file_name), 'rb') as file:
STATIC_FILE[file_name] = file.read()
return STATIC_FILE[file_name]
MIME_TYPE = {"js": "text/javascript", "css": "text/css", "png": "image/png", "woff": "font/woff", "woff2": "font/woff2"}
@app.route('/assets/<path:path>')
def assets(path):
ext = path.split("/")[-1].split(".")[-1]
return Response(load_file(path), mimetype=MIME_TYPE[ext])
// access via /assets/css/style.css if your file in ./public/assets/css/style.css

我似乎通过从主应用程序初始化行中删除额外的参数来解决此问题:

app = Flask(__name__, instance_relative_config=True)

然后,在 html 中引用时,我只是使用了:

<link href="static/lib/font-awesome/css/font-awesome.css" rel="stylesheet">

这似乎正在解决问题。我不确定为什么"从子域运行"让我如此失望。

最新更新