【问题标题】:Can't find correct path to "static" files in Flask在 Flask 中找不到“静态”文件的正确路径
【发布时间】:2020-04-13 19:48:42
【问题描述】:

在运行一个 Flask 应用程序时,我已经使用 ProxyPass 与 Gunicorn 和 Apache 将网站的“根”更改为“子目录”网址,这真是太棒了。

我终于在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: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">

由于该站点以 root 身份在“/flaskapp”运行,我认为 URL 有问题,或者我没有为静态路由正确设置。

编辑:这是我在 Apache 中设置 .conf 以进行代理的方式

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

正确设置我哪里出错了?

【问题讨论】:

    标签: python flask


    【解决方案1】:

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

    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
    

    【讨论】:

      【解决方案2】:

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

      app = Flask(__name__, instance_relative_config=True)
      

      然后,在html中引用的时候,我就简单的使用了:

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

      这似乎起到了作用。我不确定为什么“从子域运行”让我如此失望。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-10-08
        • 1970-01-01
        • 2020-12-15
        • 1970-01-01
        • 1970-01-01
        • 2019-12-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多