【问题标题】:Flask Blueprints cant override static path烧瓶蓝图不能覆盖静态路径
【发布时间】:2019-08-25 13:00:53
【问题描述】:

我正在尝试使用 Flask 蓝图来提供多页 web 应用程序。 Webapp 结构:

登陆页面 html->登录->Vuejs SPA

烧瓶结构:

app/
    client/
        dist/
            static/
                js/
                css/
            vue_index.html
        client.py
    main/
        main.py
    static/
        index.html
    __init__.py

__init_.py

app.register_blueprint(main_bp)
app.register_blueprint(client_bp)

client.py

client_bp = Blueprint('client', __name__,
                  url_prefix='/client',
                  static_url_path='/client/static',
                  static_folder='dist/static',
                  template_folder='dist',
                  )

@client_bp.route('/')
def client():
    dist_dir = current_app.config['DIST_DIR'] #full path to dist folder
    entry = os.path.join(dist_dir, 'vue_index.html')
    return send_file(entry)

vue_index.html

<!DOCTYPE html><html>...<script src=/static/js/index.js></script></body></html>

然后我运行应用程序并重定向到 host:port/client 找到 vue_index.html 但找不到文件中引用的 .js 文件。

但是,当我将 js/ 文件夹从 app/client/dist/static 移动到 app/static 时,vue_index.html 文件可以找到 js 代码。

所以很明显,蓝图并没有覆盖烧瓶应用程序的静态路径。关于如何调试静态路径/修复此问题的任何想法?

【问题讨论】:

    标签: python vue.js flask


    【解决方案1】:

    我通过将所有烧瓶静态文件和模板放在一个新的 dist/ 文件夹中并将所有 vuejs 文件添加到这个文件夹中来完成这个工作,例如

    webapp/
        dist/
            js/ (vuejs files)
            css/ (vuejs and flask landing page .css)
            index.html (vuejs entry)
            other.html (flask misc webpage)
    

    然后运行应用程序:

    app = Flask(__name__,
            static_folder='./dist',
            template_folder='./dist',
            static_url_path='')
    

    它并不理想(我想将 vuejs 文件单独保存在 dist 中,并拥有静态和模板文件夹,但无法让它工作)

    【讨论】:

      【解决方案2】:
      1. send_file 替换为render_templatehttps://flask.palletsprojects.com/en/1.1.x/quickstart/#rendering-templates
      from flask import render_template
      
      # .....
      
      @client_bp.route('/')
      def client():
          return render_template('vue_index.html')
      
      1. 对于client_bp,请使用static_url_path='static',因为如果是/client/static,您将创建一个额外的嵌套

      2. 更新你的 webpack 配置,将公共 URL 路径更改为带有 /client 命名空间的 JS 文件:

      &lt;!DOCTYPE html&gt;&lt;html&gt;...&lt;script src=/client/static/js/index.js&gt;&lt;/script&gt;&lt;/body&gt;&lt;/html&gt;

      无论如何我建议你为静态文件和模板使用不同的非嵌套文件夹

      【讨论】:

      • 我在渲染 vue_index.html 文件时没有问题,我可以使用 render_tempate 或 send_file。两者都有效。问题是获得一个带有 vue SPA 的 vuejs 文件的静态目录(登录后)和一个带有烧瓶模板(登录前)的烧瓶文件的静态目录,两者都可以工作。目前我可以找到一个或其他静态文件夹
      猜你喜欢
      • 2018-09-21
      • 1970-01-01
      • 2017-02-09
      • 2017-09-20
      • 2015-07-16
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      • 1970-01-01
      相关资源
      最近更新 更多